blob: e7c32e063e5479428f2b8adc8a7ca8b38058a192 [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
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +090027#define AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH 128
28#define AUDIO_POLICY_XML_CONFIG_FILE_NAME "audio_policy_configuration.xml"
François Gaffief4ad6e52015-11-19 16:59:57 +010029
Eric Laurentd4692962014-05-05 18:13:44 -070030#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070031#include <math.h>
Eric Laurentd4692962014-05-05 18:13:44 -070032
François Gaffie2110e042015-03-24 08:41:51 +010033#include <AudioPolicyManagerInterface.h>
34#include <AudioPolicyEngineInstance.h>
Mathias Agopian05d19b02017-02-28 16:28:19 -080035#include <cutils/atomic.h>
Eric Laurente552edb2014-03-10 17:42:56 -070036#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070037#include <utils/Log.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>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070041#include <system/audio.h>
Mikhail Naganov9ee05402016-10-13 15:58:17 -070042#include <audio_policy_conf.h>
Eric Laurentd4692962014-05-05 18:13:44 -070043#include "AudioPolicyManager.h"
François Gaffied1ab2bd2015-12-02 18:20:06 +010044#ifndef USE_XML_AUDIO_POLICY_CONF
François Gaffie53615e22015-03-19 09:24:12 +010045#include <ConfigParsingUtils.h>
François Gaffied1ab2bd2015-12-02 18:20:06 +010046#include <StreamDescriptor.h>
François Gaffief4ad6e52015-11-19 16:59:57 +010047#endif
François Gaffied1ab2bd2015-12-02 18:20:06 +010048#include <Serializer.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010049#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010050#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070051
Eric Laurent3b73df72014-03-11 09:06:29 -070052namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070053
Eric Laurentdc462862016-07-19 12:29:53 -070054//FIXME: workaround for truncated touch sounds
55// to be removed when the problem is handled by system UI
56#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070057
58// Largest difference in dB on earpiece in call between the voice volume and another
59// media / notification / system volume.
60constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
61
Eric Laurente552edb2014-03-10 17:42:56 -070062// ----------------------------------------------------------------------------
63// AudioPolicyInterface implementation
64// ----------------------------------------------------------------------------
65
Eric Laurente0720872014-03-11 09:30:41 -070066status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -080067 audio_policy_dev_state_t state,
68 const char *device_address,
69 const char *device_name)
Eric Laurente552edb2014-03-10 17:42:56 -070070{
Paul McLeane743a472015-01-28 11:07:31 -080071 return setDeviceConnectionStateInt(device, state, device_address, device_name);
Eric Laurentc73ca6e2014-12-12 14:34:22 -080072}
73
François Gaffie44481e72016-04-20 07:49:57 +020074void AudioPolicyManager::broadcastDeviceConnectionState(audio_devices_t device,
75 audio_policy_dev_state_t state,
76 const String8 &device_address)
77{
78 AudioParameter param(device_address);
79 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganov388360c2016-10-17 17:09:41 -070080 AudioParameter::keyStreamConnect : AudioParameter::keyStreamDisconnect);
François Gaffie44481e72016-04-20 07:49:57 +020081 param.addInt(key, device);
82 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
83}
84
Eric Laurentc73ca6e2014-12-12 14:34:22 -080085status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
Eric Laurenta1d525f2015-01-29 13:36:45 -080086 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -080087 const char *device_address,
88 const char *device_name)
Eric Laurentc73ca6e2014-12-12 14:34:22 -080089{
Paul McLeane743a472015-01-28 11:07:31 -080090 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s",
91- device, state, device_address, device_name);
Eric Laurente552edb2014-03-10 17:42:56 -070092
93 // connect/disconnect only 1 device at a time
94 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
95
François Gaffie53615e22015-03-19 09:24:12 +010096 sp<DeviceDescriptor> devDesc =
97 mHwModules.getDeviceDescriptor(device, device_address, device_name);
Paul McLeane743a472015-01-28 11:07:31 -080098
Eric Laurente552edb2014-03-10 17:42:56 -070099 // handle output devices
100 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700101 SortedVector <audio_io_handle_t> outputs;
102
Eric Laurent3a4311c2014-03-17 12:00:47 -0700103 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
104
Eric Laurente552edb2014-03-10 17:42:56 -0700105 // save a copy of the opened output descriptors before any output is opened or closed
106 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
107 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700108 switch (state)
109 {
110 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800111 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700112 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700113 ALOGW("setDeviceConnectionState() device already connected: %x", device);
114 return INVALID_OPERATION;
115 }
116 ALOGV("setDeviceConnectionState() connecting device %x", device);
117
Eric Laurente552edb2014-03-10 17:42:56 -0700118 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700119 index = mAvailableOutputDevices.add(devDesc);
120 if (index >= 0) {
François Gaffie53615e22015-03-19 09:24:12 +0100121 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700122 if (module == 0) {
123 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
124 device);
125 mAvailableOutputDevices.remove(devDesc);
126 return INVALID_OPERATION;
127 }
Paul McLeane743a472015-01-28 11:07:31 -0800128 mAvailableOutputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700129 } else {
130 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700131 }
132
François Gaffie44481e72016-04-20 07:49:57 +0200133 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
134 // parameters on newly connected devices (instead of opening the outputs...)
135 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
136
Eric Laurenta1d525f2015-01-29 13:36:45 -0800137 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700138 mAvailableOutputDevices.remove(devDesc);
François Gaffie44481e72016-04-20 07:49:57 +0200139
140 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
141 devDesc->mAddress);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700142 return INVALID_OPERATION;
143 }
François Gaffie2110e042015-03-24 08:41:51 +0100144 // Propagate device availability to Engine
145 mEngine->setDeviceConnectionState(devDesc, state);
146
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700147 // outputs should never be empty here
148 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
149 "checkOutputsForDevice() returned no outputs but status OK");
150 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
151 outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800152
Eric Laurent3ae5f312015-02-03 17:12:08 -0800153 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700154 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700155 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700156 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700157 ALOGW("setDeviceConnectionState() device not connected: %x", device);
158 return INVALID_OPERATION;
159 }
160
Paul McLean5c477aa2014-08-20 16:47:57 -0700161 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
162
Paul McLeane743a472015-01-28 11:07:31 -0800163 // Send Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200164 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700165
Eric Laurente552edb2014-03-10 17:42:56 -0700166 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700167 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700168
Eric Laurenta1d525f2015-01-29 13:36:45 -0800169 checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress);
François Gaffie2110e042015-03-24 08:41:51 +0100170
171 // Propagate device availability to Engine
172 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700173 } break;
174
175 default:
176 ALOGE("setDeviceConnectionState() invalid state: %x", state);
177 return BAD_VALUE;
178 }
179
Eric Laurent3a4311c2014-03-17 12:00:47 -0700180 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
181 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700182 checkA2dpSuspend();
183 checkOutputForAllStrategies();
184 // outputs must be closed after checkOutputForAllStrategies() is executed
185 if (!outputs.isEmpty()) {
186 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700187 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700188 // close unused outputs after device disconnection or direct outputs that have been
189 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700190 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700191 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
192 (desc->mDirectOpenCount == 0))) {
193 closeOutput(outputs[i]);
194 }
195 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700196 // check again after closing A2DP output to reset mA2dpSuspended if needed
197 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700198 }
199
200 updateDevicesAndOutputs();
Eric Laurent87ffa392015-05-22 10:32:38 -0700201 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700202 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
203 updateCallRouting(newDevice);
204 }
Eric Laurente552edb2014-03-10 17:42:56 -0700205 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700206 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
207 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
208 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700209 // do not force device change on duplicated output because if device is 0, it will
210 // also force a device 0 for the two outputs it is duplicated to which may override
211 // a valid device selection on those outputs.
Eric Laurentc75307b2015-03-17 15:29:32 -0700212 bool force = !desc->isDuplicated()
François Gaffie53615e22015-03-19 09:24:12 +0100213 && (!device_distinguishes_on_address(device)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700214 // always force when disconnecting (a non-duplicated device)
215 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
Eric Laurentc75307b2015-03-17 15:29:32 -0700216 setOutputDevice(desc, newDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700217 }
Eric Laurente552edb2014-03-10 17:42:56 -0700218 }
219
Eric Laurentd60560a2015-04-10 11:31:20 -0700220 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
221 cleanUpForDevice(devDesc);
222 }
223
Eric Laurent72aa32f2014-05-30 18:51:48 -0700224 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700225 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700226 } // end if is output device
227
Eric Laurente552edb2014-03-10 17:42:56 -0700228 // handle input devices
229 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700230 SortedVector <audio_io_handle_t> inputs;
231
Eric Laurent3a4311c2014-03-17 12:00:47 -0700232 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700233 switch (state)
234 {
235 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700236 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700237 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700238 ALOGW("setDeviceConnectionState() device already connected: %d", device);
239 return INVALID_OPERATION;
240 }
François Gaffie53615e22015-03-19 09:24:12 +0100241 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700242 if (module == NULL) {
243 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
244 device);
245 return INVALID_OPERATION;
246 }
François Gaffie44481e72016-04-20 07:49:57 +0200247
248 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
249 // parameters on newly connected devices (instead of opening the inputs...)
250 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
251
Paul McLean9080a4c2015-06-18 08:24:02 -0700252 if (checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress) != NO_ERROR) {
François Gaffie44481e72016-04-20 07:49:57 +0200253 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
254 devDesc->mAddress);
Eric Laurentd4692962014-05-05 18:13:44 -0700255 return INVALID_OPERATION;
256 }
257
Eric Laurent3a4311c2014-03-17 12:00:47 -0700258 index = mAvailableInputDevices.add(devDesc);
259 if (index >= 0) {
Paul McLeane743a472015-01-28 11:07:31 -0800260 mAvailableInputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700261 } else {
262 return NO_MEMORY;
263 }
Eric Laurent3ae5f312015-02-03 17:12:08 -0800264
François Gaffie2110e042015-03-24 08:41:51 +0100265 // Propagate device availability to Engine
266 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700267 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700268
269 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700270 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700271 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700272 ALOGW("setDeviceConnectionState() device not connected: %d", device);
273 return INVALID_OPERATION;
274 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700275
276 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
277
278 // Set Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200279 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700280
Paul McLean9080a4c2015-06-18 08:24:02 -0700281 checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700282 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700283
François Gaffie2110e042015-03-24 08:41:51 +0100284 // Propagate device availability to Engine
285 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700286 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700287
288 default:
289 ALOGE("setDeviceConnectionState() invalid state: %x", state);
290 return BAD_VALUE;
291 }
292
Eric Laurentd4692962014-05-05 18:13:44 -0700293 closeAllInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700294 // As the input device list can impact the output device selection, update
295 // getDeviceForStrategy() cache
296 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700297
Eric Laurent87ffa392015-05-22 10:32:38 -0700298 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700299 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
300 updateCallRouting(newDevice);
301 }
302
Eric Laurentd60560a2015-04-10 11:31:20 -0700303 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
304 cleanUpForDevice(devDesc);
305 }
306
Eric Laurentb52c1522014-05-20 11:27:36 -0700307 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700308 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700309 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700310
311 ALOGW("setDeviceConnectionState() invalid device: %x", device);
312 return BAD_VALUE;
313}
314
Eric Laurente0720872014-03-11 09:30:41 -0700315audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100316 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700317{
Eric Laurent634b7142016-04-20 13:48:02 -0700318 sp<DeviceDescriptor> devDesc =
319 mHwModules.getDeviceDescriptor(device, device_address, "",
320 (strlen(device_address) != 0)/*matchAddress*/);
321
322 if (devDesc == 0) {
323 ALOGW("getDeviceConnectionState() undeclared device, type %08x, address: %s",
324 device, device_address);
325 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
326 }
François Gaffie53615e22015-03-19 09:24:12 +0100327
Eric Laurent3a4311c2014-03-17 12:00:47 -0700328 DeviceVector *deviceVector;
329
Eric Laurente552edb2014-03-10 17:42:56 -0700330 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700331 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700332 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700333 deviceVector = &mAvailableInputDevices;
334 } else {
335 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
336 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700337 }
Eric Laurent634b7142016-04-20 13:48:02 -0700338
339 return (deviceVector->getDevice(device, String8(device_address)) != 0) ?
340 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800341}
342
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800343status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
344 const char *device_address,
345 const char *device_name)
346{
347 status_t status;
348
349 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s",
350 device, device_address, device_name);
351
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800352 // connect/disconnect only 1 device at a time
353 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
354
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800355 // Check if the device is currently connected
356 sp<DeviceDescriptor> devDesc =
357 mHwModules.getDeviceDescriptor(device, device_address, device_name);
358 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
359 if (index < 0) {
360 // Nothing to do: device is not connected
361 return NO_ERROR;
362 }
363
364 // Toggle the device state: UNAVAILABLE -> AVAILABLE
365 // This will force reading again the device configuration
366 status = setDeviceConnectionState(device,
367 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
368 device_address, device_name);
369 if (status != NO_ERROR) {
370 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
371 status);
372 return status;
373 }
374
375 status = setDeviceConnectionState(device,
376 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
377 device_address, device_name);
378 if (status != NO_ERROR) {
379 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
380 status);
381 return status;
382 }
383
384 return NO_ERROR;
385}
386
Eric Laurentdc462862016-07-19 12:29:53 -0700387uint32_t AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700388{
389 bool createTxPatch = false;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700390 status_t status;
391 audio_patch_handle_t afPatchHandle;
392 DeviceVector deviceList;
Eric Laurentdc462862016-07-19 12:29:53 -0700393 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700394
Andy Hunga76c7de2016-12-13 19:14:31 -0800395 if(!hasPrimaryOutput() || mPrimaryOutput->device() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurentdc462862016-07-19 12:29:53 -0700396 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700397 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800398 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700399 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
400
401 // release existing RX patch if any
402 if (mCallRxPatch != 0) {
403 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
404 mCallRxPatch.clear();
405 }
406 // release TX patch if any
407 if (mCallTxPatch != 0) {
408 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
409 mCallTxPatch.clear();
410 }
411
412 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
413 // via setOutputDevice() on primary output.
414 // Otherwise, create two audio patches for TX and RX path.
415 if (availablePrimaryOutputDevices() & rxDevice) {
Eric Laurentdc462862016-07-19 12:29:53 -0700416 muteWaitMs = setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700417 // If the TX device is also on the primary HW module, setOutputDevice() will take care
418 // of it due to legacy implementation. If not, create a patch.
419 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
420 == AUDIO_DEVICE_NONE) {
421 createTxPatch = true;
422 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700423 } else { // create RX path audio patch
424 struct audio_patch patch;
425
426 patch.num_sources = 1;
427 patch.num_sinks = 1;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700428 deviceList = mAvailableOutputDevices.getDevicesFromType(rxDevice);
429 ALOG_ASSERT(!deviceList.isEmpty(),
430 "updateCallRouting() selected device not in output device list");
431 sp<DeviceDescriptor> rxSinkDeviceDesc = deviceList.itemAt(0);
432 deviceList = mAvailableInputDevices.getDevicesFromType(AUDIO_DEVICE_IN_TELEPHONY_RX);
433 ALOG_ASSERT(!deviceList.isEmpty(),
434 "updateCallRouting() no telephony RX device");
435 sp<DeviceDescriptor> rxSourceDeviceDesc = deviceList.itemAt(0);
436
437 rxSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
438 rxSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
439
440 // request to reuse existing output stream if one is already opened to reach the RX device
441 SortedVector<audio_io_handle_t> outputs =
442 getOutputsForDevice(rxDevice, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700443 audio_io_handle_t output = selectOutput(outputs,
444 AUDIO_OUTPUT_FLAG_NONE,
445 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700446 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700447 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700448 ALOG_ASSERT(!outputDesc->isDuplicated(),
449 "updateCallRouting() RX device output is duplicated");
450 outputDesc->toAudioPortConfig(&patch.sources[1]);
Eric Laurent3bcf8592015-04-03 12:13:24 -0700451 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700452 patch.num_sources = 2;
453 }
454
455 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentdc462862016-07-19 12:29:53 -0700456 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700457 ALOGW_IF(status != NO_ERROR, "updateCallRouting() error %d creating RX audio patch",
458 status);
459 if (status == NO_ERROR) {
François Gaffie98cc1912015-03-18 17:52:40 +0100460 mCallRxPatch = new AudioPatch(&patch, mUidCached);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700461 mCallRxPatch->mAfPatchHandle = afPatchHandle;
462 mCallRxPatch->mUid = mUidCached;
463 }
464 createTxPatch = true;
465 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700466 if (createTxPatch) { // create TX path audio patch
Eric Laurentc2730ba2014-07-20 15:47:07 -0700467 struct audio_patch patch;
Eric Laurent8ae73122016-04-12 10:13:29 -0700468
Eric Laurentc2730ba2014-07-20 15:47:07 -0700469 patch.num_sources = 1;
470 patch.num_sinks = 1;
471 deviceList = mAvailableInputDevices.getDevicesFromType(txDevice);
472 ALOG_ASSERT(!deviceList.isEmpty(),
473 "updateCallRouting() selected device not in input device list");
474 sp<DeviceDescriptor> txSourceDeviceDesc = deviceList.itemAt(0);
475 txSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
476 deviceList = mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_TELEPHONY_TX);
477 ALOG_ASSERT(!deviceList.isEmpty(),
478 "updateCallRouting() no telephony TX device");
479 sp<DeviceDescriptor> txSinkDeviceDesc = deviceList.itemAt(0);
480 txSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
481
482 SortedVector<audio_io_handle_t> outputs =
483 getOutputsForDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700484 audio_io_handle_t output = selectOutput(outputs,
485 AUDIO_OUTPUT_FLAG_NONE,
486 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700487 // request to reuse existing output stream if one is already opened to reach the TX
488 // path output device
489 if (output != AUDIO_IO_HANDLE_NONE) {
490 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
491 ALOG_ASSERT(!outputDesc->isDuplicated(),
492 "updateCallRouting() RX device output is duplicated");
493 outputDesc->toAudioPortConfig(&patch.sources[1]);
Eric Laurent3bcf8592015-04-03 12:13:24 -0700494 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700495 patch.num_sources = 2;
496 }
497
Eric Laurentc0a889f2015-10-14 14:36:34 -0700498 // terminate active capture if on the same HW module as the call TX source device
499 // FIXME: would be better to refine to only inputs whose profile connects to the
500 // call TX device but this information is not in the audio patch and logic here must be
501 // symmetric to the one in startInput()
Eric Laurentfb66dd92016-01-28 18:32:03 -0800502 Vector<sp <AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
503 for (size_t i = 0; i < activeInputs.size(); i++) {
504 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
505 if (activeDesc->hasSameHwModuleAs(txSourceDeviceDesc)) {
506 AudioSessionCollection activeSessions =
507 activeDesc->getAudioSessions(true /*activeOnly*/);
508 for (size_t j = 0; j < activeSessions.size(); j++) {
509 audio_session_t activeSession = activeSessions.keyAt(j);
510 stopInput(activeDesc->mIoHandle, activeSession);
511 releaseInput(activeDesc->mIoHandle, activeSession);
512 }
Eric Laurentc0a889f2015-10-14 14:36:34 -0700513 }
514 }
515
Eric Laurentc2730ba2014-07-20 15:47:07 -0700516 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentdc462862016-07-19 12:29:53 -0700517 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700518 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
519 status);
520 if (status == NO_ERROR) {
François Gaffie98cc1912015-03-18 17:52:40 +0100521 mCallTxPatch = new AudioPatch(&patch, mUidCached);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700522 mCallTxPatch->mAfPatchHandle = afPatchHandle;
523 mCallTxPatch->mUid = mUidCached;
524 }
525 }
Eric Laurentdc462862016-07-19 12:29:53 -0700526
527 return muteWaitMs;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700528}
529
Eric Laurente0720872014-03-11 09:30:41 -0700530void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700531{
532 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100533 // store previous phone state for management of sonification strategy below
534 int oldState = mEngine->getPhoneState();
535
536 if (mEngine->setPhoneState(state) != NO_ERROR) {
537 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700538 return;
539 }
François Gaffie2110e042015-03-24 08:41:51 +0100540 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurente552edb2014-03-10 17:42:56 -0700541 // if leaving call state, handle special case of active streams
542 // pertaining to sonification strategy see handleIncallSonification()
Eric Laurent63dea1d2015-07-02 17:10:28 -0700543 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700544 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800545 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700546 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700547 }
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800548
Eric Laurent63dea1d2015-07-02 17:10:28 -0700549 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800550 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700551 }
552
François Gaffie2110e042015-03-24 08:41:51 +0100553 /**
554 * Switching to or from incall state or switching between telephony and VoIP lead to force
555 * routing command.
556 */
557 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
558 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700559
560 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700561 checkA2dpSuspend();
562 checkOutputForAllStrategies();
563 updateDevicesAndOutputs();
564
Eric Laurente552edb2014-03-10 17:42:56 -0700565 int delayMs = 0;
566 if (isStateInCall(state)) {
567 nsecs_t sysTime = systemTime();
568 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700569 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700570 // mute media and sonification strategies and delay device switch by the largest
571 // latency of any output where either strategy is active.
572 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100573 if ((isStrategyActive(desc, STRATEGY_MEDIA,
574 SONIFICATION_HEADSET_MUSIC_DELAY,
575 sysTime) ||
576 isStrategyActive(desc, STRATEGY_SONIFICATION,
577 SONIFICATION_HEADSET_MUSIC_DELAY,
578 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700579 (delayMs < (int)desc->latency()*2)) {
580 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700581 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700582 setStrategyMute(STRATEGY_MEDIA, true, desc);
583 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700584 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700585 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
586 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700587 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
588 }
589 }
590
Eric Laurent87ffa392015-05-22 10:32:38 -0700591 if (hasPrimaryOutput()) {
592 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
593 // the device returned is not necessarily reachable via this output
594 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
595 // force routing command to audio hardware when ending call
596 // even if no device change is needed
597 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
598 rxDevice = mPrimaryOutput->device();
599 }
Eric Laurente552edb2014-03-10 17:42:56 -0700600
Eric Laurent87ffa392015-05-22 10:32:38 -0700601 if (state == AUDIO_MODE_IN_CALL) {
602 updateCallRouting(rxDevice, delayMs);
603 } else if (oldState == AUDIO_MODE_IN_CALL) {
604 if (mCallRxPatch != 0) {
605 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
606 mCallRxPatch.clear();
607 }
608 if (mCallTxPatch != 0) {
609 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
610 mCallTxPatch.clear();
611 }
612 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
613 } else {
614 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700615 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700616 }
Eric Laurente552edb2014-03-10 17:42:56 -0700617 // if entering in call state, handle special case of active streams
618 // pertaining to sonification strategy see handleIncallSonification()
619 if (isStateInCall(state)) {
620 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800621 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700622 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700623 }
Eric Laurent63dea1d2015-07-02 17:10:28 -0700624
625 // force reevaluating accessibility routing when call starts
626 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700627 }
628
629 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700630 if (state == AUDIO_MODE_RINGTONE &&
631 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700632 mLimitRingtoneVolume = true;
633 } else {
634 mLimitRingtoneVolume = false;
635 }
636}
637
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700638audio_mode_t AudioPolicyManager::getPhoneState() {
639 return mEngine->getPhoneState();
640}
641
Eric Laurente0720872014-03-11 09:30:41 -0700642void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700643 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700644{
François Gaffie2110e042015-03-24 08:41:51 +0100645 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700646 if (config == mEngine->getForceUse(usage)) {
647 return;
648 }
Eric Laurente552edb2014-03-10 17:42:56 -0700649
François Gaffie2110e042015-03-24 08:41:51 +0100650 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
651 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
652 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700653 }
François Gaffie2110e042015-03-24 08:41:51 +0100654 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
655 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
656 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700657
658 // check for device and output changes triggered by new force usage
659 checkA2dpSuspend();
660 checkOutputForAllStrategies();
661 updateDevicesAndOutputs();
Phil Burk09bc4612016-02-24 15:58:15 -0800662
Eric Laurentdc462862016-07-19 12:29:53 -0700663 //FIXME: workaround for truncated touch sounds
664 // to be removed when the problem is handled by system UI
665 uint32_t delayMs = 0;
666 uint32_t waitMs = 0;
667 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
668 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
669 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700670 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700671 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
Eric Laurentdc462862016-07-19 12:29:53 -0700672 waitMs = updateCallRouting(newDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700673 }
Eric Laurente552edb2014-03-10 17:42:56 -0700674 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700675 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
676 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
677 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700678 waitMs = setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE),
679 delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700680 }
Eric Laurente552edb2014-03-10 17:42:56 -0700681 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700682 applyStreamVolumes(outputDesc, newDevice, waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700683 }
684 }
685
Eric Laurentfb66dd92016-01-28 18:32:03 -0800686 Vector<sp <AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
687 for (size_t i = 0; i < activeInputs.size(); i++) {
688 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
689 audio_devices_t newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700690 // Force new input selection if the new device can not be reached via current input
Eric Laurentfb66dd92016-01-28 18:32:03 -0800691 if (activeDesc->mProfile->getSupportedDevices().types() &
692 (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
693 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700694 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800695 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700696 }
Eric Laurente552edb2014-03-10 17:42:56 -0700697 }
Eric Laurente552edb2014-03-10 17:42:56 -0700698}
699
Eric Laurente0720872014-03-11 09:30:41 -0700700void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700701{
702 ALOGV("setSystemProperty() property %s, value %s", property, value);
703}
704
705// Find a direct output profile compatible with the parameters passed, even if the input flags do
706// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800707sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700708 audio_devices_t device,
709 uint32_t samplingRate,
710 audio_format_t format,
711 audio_channel_mask_t channelMask,
712 audio_output_flags_t flags)
713{
Eric Laurent861a6282015-05-18 15:40:16 -0700714 // only retain flags that will drive the direct output profile selection
715 // if explicitly requested
716 static const uint32_t kRelevantFlags =
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700717 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
718 AUDIO_OUTPUT_FLAG_VOIP_RX);
Eric Laurent861a6282015-05-18 15:40:16 -0700719 flags =
720 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
721
722 sp<IOProfile> profile;
723
Eric Laurente552edb2014-03-10 17:42:56 -0700724 for (size_t i = 0; i < mHwModules.size(); i++) {
725 if (mHwModules[i]->mHandle == 0) {
726 continue;
727 }
728 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent861a6282015-05-18 15:40:16 -0700729 sp<IOProfile> curProfile = mHwModules[i]->mOutputProfiles[j];
730 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700731 samplingRate, NULL /*updatedSamplingRate*/,
732 format, NULL /*updatedFormat*/,
733 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700734 flags)) {
735 continue;
736 }
737 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100738 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700739 continue;
740 }
741 // if several profiles are compatible, give priority to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100742 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700743 continue;
744 }
745 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100746 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700747 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700748 }
Eric Laurente552edb2014-03-10 17:42:56 -0700749 }
750 }
Eric Laurent861a6282015-05-18 15:40:16 -0700751 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700752}
753
Eric Laurente0720872014-03-11 09:30:41 -0700754audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +0100755 uint32_t samplingRate,
756 audio_format_t format,
757 audio_channel_mask_t channelMask,
758 audio_output_flags_t flags,
759 const audio_offload_info_t *offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -0700760{
Eric Laurent3b73df72014-03-11 09:06:29 -0700761 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700762 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
763 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
764 device, stream, samplingRate, format, channelMask, flags);
765
Kevin Rocard169753c2017-03-06 14:18:23 -0800766 return getOutputForDevice(device, AUDIO_SESSION_ALLOCATE, stream, samplingRate, format,
767 channelMask, flags, offloadInfo);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700768}
769
Eric Laurente83b55d2014-11-14 10:06:21 -0800770status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
771 audio_io_handle_t *output,
772 audio_session_t session,
773 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700774 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800775 const audio_config_t *config,
Eric Laurente83b55d2014-11-14 10:06:21 -0800776 audio_output_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700777 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800778 audio_port_handle_t *portId)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700779{
Eric Laurente83b55d2014-11-14 10:06:21 -0800780 audio_attributes_t attributes;
781 if (attr != NULL) {
782 if (!isValidAttributes(attr)) {
783 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
784 attr->usage, attr->content_type, attr->flags,
785 attr->tags);
786 return BAD_VALUE;
787 }
788 attributes = *attr;
789 } else {
790 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
791 ALOGE("getOutputForAttr(): invalid stream type");
792 return BAD_VALUE;
793 }
794 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700795 }
Eric Laurent20b9ef02016-12-05 11:03:16 -0800796
797 // TODO: check for existing client for this port ID
798 if (*portId == AUDIO_PORT_HANDLE_NONE) {
799 *portId = AudioPort::getNextUniqueId();
800 }
801
Eric Laurentc75307b2015-03-17 15:29:32 -0700802 sp<SwAudioOutputDescriptor> desc;
Jean-Michel Trivie8deced2016-02-11 12:50:39 -0800803 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
François Gaffie036e1e92015-03-19 10:16:24 +0100804 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
Eric Laurent20b9ef02016-12-05 11:03:16 -0800805 if (!audio_has_proportional_frames(config->format)) {
François Gaffie036e1e92015-03-19 10:16:24 +0100806 return BAD_VALUE;
Eric Laurent275e8e92014-11-30 15:14:47 -0800807 }
François Gaffie036e1e92015-03-19 10:16:24 +0100808 *stream = streamTypefromAttributesInt(&attributes);
809 *output = desc->mIoHandle;
810 ALOGV("getOutputForAttr() returns output %d", *output);
811 return NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -0800812 }
813 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
814 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
815 return BAD_VALUE;
816 }
817
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700818 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
819 " session %d selectedDeviceId %d",
820 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700821 session, *selectedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700822
823 *stream = streamTypefromAttributesInt(&attributes);
824
825 // Explicit routing?
826 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -0700827 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
828 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
829 if (mAvailableOutputDevices[i]->getId() == *selectedDeviceId) {
830 deviceDesc = mAvailableOutputDevices[i];
831 break;
832 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700833 }
834 }
835 mOutputRoutes.addRoute(session, *stream, SessionRoute::SOURCE_TYPE_NA, deviceDesc, uid);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700836
Eric Laurente83b55d2014-11-14 10:06:21 -0800837 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700838 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700839
Eric Laurente83b55d2014-11-14 10:06:21 -0800840 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Eric Laurent93c3d412014-08-01 14:48:35 -0700841 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
842 }
843
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700844 ALOGV("getOutputForAttr() device 0x%x, samplingRate %d, format %x, channelMask %x, flags %x",
Eric Laurent20b9ef02016-12-05 11:03:16 -0800845 device, config->sample_rate, config->format, config->channel_mask, flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700846
Kevin Rocard169753c2017-03-06 14:18:23 -0800847 *output = getOutputForDevice(device, session, *stream,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800848 config->sample_rate, config->format, config->channel_mask,
849 flags, &config->offload_info);
Eric Laurente83b55d2014-11-14 10:06:21 -0800850 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700851 mOutputRoutes.removeRoute(session);
Eric Laurente83b55d2014-11-14 10:06:21 -0800852 return INVALID_OPERATION;
853 }
Paul McLeanaa981192015-03-21 09:55:15 -0700854
Eric Laurent2ac76942017-06-22 17:17:09 -0700855 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromType(device);
856 *selectedDeviceId = outputDevices.size() > 0 ? outputDevices.itemAt(0)->getId()
857 : AUDIO_PORT_HANDLE_NONE;
858
859 ALOGV(" getOutputForAttr() returns output %d selectedDeviceId %d", *output, *selectedDeviceId);
860
Eric Laurente83b55d2014-11-14 10:06:21 -0800861 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700862}
863
864audio_io_handle_t AudioPolicyManager::getOutputForDevice(
865 audio_devices_t device,
Kevin Rocard169753c2017-03-06 14:18:23 -0800866 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700867 audio_stream_type_t stream,
868 uint32_t samplingRate,
869 audio_format_t format,
870 audio_channel_mask_t channelMask,
871 audio_output_flags_t flags,
872 const audio_offload_info_t *offloadInfo)
873{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700874 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700875 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700876
Eric Laurente552edb2014-03-10 17:42:56 -0700877 // open a direct output if required by specified parameters
878 //force direct flag if offload flag is set: offloading implies a direct output stream
879 // and all common behaviors are driven by checking only the direct flag
880 // this should normally be set appropriately in the policy configuration file
881 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700882 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700883 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700884 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
885 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
886 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800887 // only allow deep buffering for music stream type
888 if (stream != AUDIO_STREAM_MUSIC) {
889 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700890 } else if (/* stream == AUDIO_STREAM_MUSIC && */
891 flags == AUDIO_OUTPUT_FLAG_NONE &&
892 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
893 // use DEEP_BUFFER as default output for music stream type
894 flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800895 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700896 if (stream == AUDIO_STREAM_TTS) {
897 flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700898 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700899 audio_is_linear_pcm(format)) {
900 flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
901 AUDIO_OUTPUT_FLAG_DIRECT);
902 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700903 }
Eric Laurente552edb2014-03-10 17:42:56 -0700904
Eric Laurentb732cf52014-09-24 19:08:21 -0700905 sp<IOProfile> profile;
906
907 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700908 // and not explicitly requested
909 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Glenn Kasten05ddca52016-02-11 08:17:12 -0800910 audio_is_linear_pcm(format) && samplingRate <= SAMPLE_RATE_HZ_MAX &&
Eric Laurentb732cf52014-09-24 19:08:21 -0700911 audio_channel_count_from_out_mask(channelMask) <= 2) {
912 goto non_direct_output;
913 }
914
Andy Hung2ddee192015-12-18 17:34:44 -0800915 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
916 // This prevents creating an offloaded track and tearing it down immediately after start
917 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700918 // FIXME: We should check the audio session here but we do not have it in this context.
919 // This may prevent offloading in rare situations where effects are left active by apps
920 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700921
Eric Laurente552edb2014-03-10 17:42:56 -0700922 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800923 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700924 profile = getProfileForDirectOutput(device,
925 samplingRate,
926 format,
927 channelMask,
928 (audio_output_flags_t)flags);
929 }
930
Eric Laurent1c333e22014-05-20 10:48:17 -0700931 if (profile != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700932 sp<SwAudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700933
934 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700935 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700936 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
937 outputDesc = desc;
Kevin Rocard551061a2017-02-06 15:59:29 -0800938 // reuse direct output if currently open by the same client
939 // and configured with same parameters
Eric Laurente552edb2014-03-10 17:42:56 -0700940 if ((samplingRate == outputDesc->mSamplingRate) &&
Kevin Rocard551061a2017-02-06 15:59:29 -0800941 audio_formats_match(format, outputDesc->mFormat) &&
942 (channelMask == outputDesc->mChannelMask)) {
Kevin Rocard169753c2017-03-06 14:18:23 -0800943 if (session == outputDesc->mDirectClientSession) {
Kevin Rocard551061a2017-02-06 15:59:29 -0800944 outputDesc->mDirectOpenCount++;
Kevin Rocard169753c2017-03-06 14:18:23 -0800945 ALOGV("getOutput() reusing direct output %d for session %d",
946 mOutputs.keyAt(i), session);
Kevin Rocard551061a2017-02-06 15:59:29 -0800947 return mOutputs.keyAt(i);
948 } else {
Kevin Rocard169753c2017-03-06 14:18:23 -0800949 ALOGV("getOutput() do not reuse direct output because current client (%d) "
950 "is not the same as requesting client (%d)",
951 outputDesc->mDirectClientSession, session);
Kevin Rocard551061a2017-02-06 15:59:29 -0800952 goto non_direct_output;
953 }
Eric Laurente552edb2014-03-10 17:42:56 -0700954 }
955 }
956 }
957 // close direct output if currently open and configured with different parameters
958 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700959 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700960 }
Eric Laurent861a6282015-05-18 15:40:16 -0700961
962 // if the selected profile is offloaded and no offload info was specified,
963 // create a default one
964 audio_offload_info_t defaultOffloadInfo = AUDIO_INFO_INITIALIZER;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100965 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) && !offloadInfo) {
Eric Laurent861a6282015-05-18 15:40:16 -0700966 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
967 defaultOffloadInfo.sample_rate = samplingRate;
968 defaultOffloadInfo.channel_mask = channelMask;
969 defaultOffloadInfo.format = format;
970 defaultOffloadInfo.stream_type = stream;
971 defaultOffloadInfo.bit_rate = 0;
972 defaultOffloadInfo.duration_us = -1;
973 defaultOffloadInfo.has_video = true; // conservative
974 defaultOffloadInfo.is_streaming = true; // likely
975 offloadInfo = &defaultOffloadInfo;
976 }
977
Eric Laurentc75307b2015-03-17 15:29:32 -0700978 outputDesc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -0700979 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -0700980 outputDesc->mLatency = 0;
Eric Laurent861a6282015-05-18 15:40:16 -0700981 outputDesc->mFlags = (audio_output_flags_t)(outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700982 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
983 config.sample_rate = samplingRate;
984 config.channel_mask = channelMask;
985 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -0700986 if (offloadInfo != NULL) {
987 config.offload_info = *offloadInfo;
988 }
Eric Laurente3014102017-05-03 11:15:43 -0700989 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromType(device);
990 String8 address = outputDevices.size() > 0 ? outputDevices.itemAt(0)->mAddress
991 : String8("");
Eric Laurent322b4d22015-04-03 15:57:54 -0700992 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -0700993 &output,
994 &config,
995 &outputDesc->mDevice,
Eric Laurente3014102017-05-03 11:15:43 -0700996 address,
Eric Laurentcf2c0212014-07-25 16:20:43 -0700997 &outputDesc->mLatency,
998 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -0700999
1000 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001001 if (status != NO_ERROR ||
1002 (samplingRate != 0 && samplingRate != config.sample_rate) ||
Eric Laurente6930022016-02-11 10:20:40 -08001003 (format != AUDIO_FORMAT_DEFAULT && !audio_formats_match(format, config.format)) ||
Eric Laurentcf2c0212014-07-25 16:20:43 -07001004 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001005 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
1006 "format %d %d, channelMask %04x %04x", output, samplingRate,
1007 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
1008 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001009 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001010 mpClientInterface->closeOutput(output);
1011 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001012 // fall back to mixer output if possible when the direct output could not be open
Glenn Kasten05ddca52016-02-11 08:17:12 -08001013 if (audio_is_linear_pcm(format) && samplingRate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -08001014 goto non_direct_output;
1015 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001016 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001017 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001018 outputDesc->mSamplingRate = config.sample_rate;
1019 outputDesc->mChannelMask = config.channel_mask;
1020 outputDesc->mFormat = config.format;
1021 outputDesc->mRefCount[stream] = 0;
1022 outputDesc->mStopTime[stream] = 0;
1023 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -08001024 outputDesc->mDirectClientSession = session;
1025
Eric Laurente552edb2014-03-10 17:42:56 -07001026 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001027 mPreviousOutputs = mOutputs;
1028 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001029 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001030 return output;
1031 }
1032
Eric Laurentb732cf52014-09-24 19:08:21 -07001033non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001034
1035 // A request for HW A/V sync cannot fallback to a mixed output because time
1036 // stamps are embedded in audio data
1037 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1038 return AUDIO_IO_HANDLE_NONE;
1039 }
1040
Eric Laurente552edb2014-03-10 17:42:56 -07001041 // ignoring channel mask due to downmix capability in mixer
1042
1043 // open a non direct output
1044
1045 // for non direct outputs, only PCM is supported
1046 if (audio_is_linear_pcm(format)) {
1047 // get which output is suitable for the specified stream. The actual
1048 // routing change will happen when startOutput() will be called
1049 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1050
Eric Laurent8838a382014-09-08 16:44:28 -07001051 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
1052 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1053 output = selectOutput(outputs, flags, format);
Eric Laurente552edb2014-03-10 17:42:56 -07001054 }
Glenn Kastenfaa10a62017-05-25 15:52:05 -07001055 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d, "
Eric Laurente552edb2014-03-10 17:42:56 -07001056 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
1057
Eric Laurente552edb2014-03-10 17:42:56 -07001058 return output;
1059}
1060
Eric Laurente0720872014-03-11 09:30:41 -07001061audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001062 audio_output_flags_t flags,
1063 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001064{
1065 // select one output among several that provide a path to a particular device or set of
1066 // devices (the list was previously build by getOutputsForDevice()).
1067 // The priority is as follows:
1068 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001069 // 2: the output with the bit depth the closest to the requested one
1070 // 3: the primary output
1071 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001072
1073 if (outputs.size() == 0) {
1074 return 0;
1075 }
1076 if (outputs.size() == 1) {
1077 return outputs[0];
1078 }
1079
1080 int maxCommonFlags = 0;
Eric Laurente6930022016-02-11 10:20:40 -08001081 audio_io_handle_t outputForFlags = 0;
1082 audio_io_handle_t outputForPrimary = 0;
1083 audio_io_handle_t outputForFormat = 0;
1084 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1085 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001086
1087 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001088 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001089 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001090 // if a valid format is specified, skip output if not compatible
1091 if (format != AUDIO_FORMAT_INVALID) {
1092 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente6930022016-02-11 10:20:40 -08001093 if (!audio_formats_match(format, outputDesc->mFormat)) {
Eric Laurent8838a382014-09-08 16:44:28 -07001094 continue;
1095 }
1096 } else if (!audio_is_linear_pcm(format)) {
1097 continue;
1098 }
Eric Laurente6930022016-02-11 10:20:40 -08001099 if (AudioPort::isBetterFormatMatch(
1100 outputDesc->mFormat, bestFormat, format)) {
1101 outputForFormat = outputs[i];
1102 bestFormat = outputDesc->mFormat;
1103 }
Eric Laurent8838a382014-09-08 16:44:28 -07001104 }
1105
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001106 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001107 if (commonFlags >= maxCommonFlags) {
1108 if (commonFlags == maxCommonFlags) {
1109 if (AudioPort::isBetterFormatMatch(
1110 outputDesc->mFormat, bestFormatForFlags, format)) {
1111 outputForFlags = outputs[i];
1112 bestFormatForFlags = outputDesc->mFormat;
1113 }
1114 } else {
1115 outputForFlags = outputs[i];
1116 maxCommonFlags = commonFlags;
1117 bestFormatForFlags = outputDesc->mFormat;
1118 }
Eric Laurente552edb2014-03-10 17:42:56 -07001119 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1120 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001121 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurente6930022016-02-11 10:20:40 -08001122 outputForPrimary = outputs[i];
Eric Laurente552edb2014-03-10 17:42:56 -07001123 }
1124 }
1125 }
1126
Eric Laurente6930022016-02-11 10:20:40 -08001127 if (outputForFlags != 0) {
1128 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001129 }
Eric Laurente6930022016-02-11 10:20:40 -08001130 if (outputForFormat != 0) {
1131 return outputForFormat;
1132 }
1133 if (outputForPrimary != 0) {
1134 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001135 }
1136
1137 return outputs[0];
1138}
1139
Eric Laurente0720872014-03-11 09:30:41 -07001140status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001141 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001142 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001143{
Paul McLeanaa981192015-03-21 09:55:15 -07001144 ALOGV("startOutput() output %d, stream %d, session %d",
1145 output, stream, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001146 ssize_t index = mOutputs.indexOfKey(output);
1147 if (index < 0) {
1148 ALOGW("startOutput() unknown output %d", output);
1149 return BAD_VALUE;
1150 }
1151
Eric Laurentc75307b2015-03-17 15:29:32 -07001152 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1153
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001154 // Routing?
1155 mOutputRoutes.incRouteActivity(session);
1156
Eric Laurentc75307b2015-03-17 15:29:32 -07001157 audio_devices_t newDevice;
Eric Laurentc40d9692016-04-13 19:14:13 -07001158 AudioMix *policyMix = NULL;
1159 const char *address = NULL;
Eric Laurentc75307b2015-03-17 15:29:32 -07001160 if (outputDesc->mPolicyMix != NULL) {
Eric Laurentc40d9692016-04-13 19:14:13 -07001161 policyMix = outputDesc->mPolicyMix;
1162 address = policyMix->mDeviceAddress.string();
1163 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1164 newDevice = policyMix->mDeviceType;
1165 } else {
1166 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1167 }
Eric Laurent493404d2015-04-21 15:07:36 -07001168 } else if (mOutputRoutes.hasRouteChanged(session)) {
1169 newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001170 checkStrategyRoute(getStrategy(stream), output);
Eric Laurentc75307b2015-03-17 15:29:32 -07001171 } else {
1172 newDevice = AUDIO_DEVICE_NONE;
1173 }
1174
1175 uint32_t delayMs = 0;
1176
Eric Laurentc40d9692016-04-13 19:14:13 -07001177 status_t status = startSource(outputDesc, stream, newDevice, address, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001178
1179 if (status != NO_ERROR) {
1180 mOutputRoutes.decRouteActivity(session);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001181 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001182 }
1183 // Automatically enable the remote submix input when output is started on a re routing mix
1184 // of type MIX_TYPE_RECORDERS
Eric Laurentc40d9692016-04-13 19:14:13 -07001185 if (audio_is_remote_submix_device(newDevice) && policyMix != NULL &&
1186 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001187 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1188 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Eric Laurentc40d9692016-04-13 19:14:13 -07001189 address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001190 "remote-submix");
1191 }
1192
1193 if (delayMs != 0) {
1194 usleep(delayMs * 1000);
1195 }
1196
1197 return status;
1198}
1199
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001200status_t AudioPolicyManager::startSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurentc75307b2015-03-17 15:29:32 -07001201 audio_stream_type_t stream,
1202 audio_devices_t device,
Eric Laurentc40d9692016-04-13 19:14:13 -07001203 const char *address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001204 uint32_t *delayMs)
1205{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001206 // cannot start playback of STREAM_TTS if any other output is being used
1207 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001208
1209 *delayMs = 0;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001210 if (stream == AUDIO_STREAM_TTS) {
1211 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001212 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001213 return INVALID_OPERATION;
1214 } else {
1215 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1216 }
1217 } else {
1218 // some playback other than beacon starts
1219 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1220 }
1221
Eric Laurent77305a62016-07-25 16:39:22 -07001222 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001223 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001224 bool force = !outputDesc->isActive() &&
1225 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001226
Eric Laurente552edb2014-03-10 17:42:56 -07001227 // increment usage count for this stream on the requested output:
1228 // NOTE that the usage count is the same for duplicated output and hardware output which is
1229 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1230 outputDesc->changeRefCount(stream, 1);
1231
Eric Laurent36829f92017-04-07 19:04:42 -07001232 if (stream == AUDIO_STREAM_MUSIC) {
1233 selectOutputForMusicEffects();
1234 }
1235
Eric Laurent493404d2015-04-21 15:07:36 -07001236 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001237 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001238 if (device == AUDIO_DEVICE_NONE) {
1239 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001240 }
Eric Laurent36829f92017-04-07 19:04:42 -07001241
Eric Laurente552edb2014-03-10 17:42:56 -07001242 routing_strategy strategy = getStrategy(stream);
1243 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001244 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1245 (beaconMuteLatency > 0);
1246 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001247 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001248 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001249 if (desc != outputDesc) {
Eric Laurent77305a62016-07-25 16:39:22 -07001250 // force a device change if any other output is:
1251 // - managed by the same hw module
1252 // - has a current device selection that differs from selected device.
1253 // - supports currently selected device
1254 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001255 // In this case, the audio HAL must receive the new device selection so that it can
1256 // change the device currently selected by the other active output.
1257 if (outputDesc->sharesHwModuleWith(desc) &&
Eric Laurent77305a62016-07-25 16:39:22 -07001258 desc->device() != device &&
1259 desc->supportedDevices() & device &&
1260 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001261 force = true;
1262 }
1263 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001264 // a notification so that audio focus effect can propagate, or that a mute/unmute
1265 // event occurred for beacon
Eric Laurente552edb2014-03-10 17:42:56 -07001266 uint32_t latency = desc->latency();
1267 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1268 waitMs = latency;
1269 }
1270 }
1271 }
Eric Laurentdc462862016-07-19 12:29:53 -07001272 uint32_t muteWaitMs = setOutputDevice(outputDesc, device, force, 0, NULL, address);
Eric Laurente552edb2014-03-10 17:42:56 -07001273
1274 // handle special case for sonification while in call
1275 if (isInCall()) {
1276 handleIncallSonification(stream, true, false);
1277 }
1278
1279 // apply volume rules for current stream and device if necessary
1280 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01001281 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07001282 outputDesc,
1283 device);
Eric Laurente552edb2014-03-10 17:42:56 -07001284
1285 // update the outputs if starting an output with a stream that can affect notification
1286 // routing
1287 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001288
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001289 // force reevaluating accessibility routing when ringtone or alarm starts
1290 if (strategy == STRATEGY_SONIFICATION) {
1291 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1292 }
Eric Laurentdc462862016-07-19 12:29:53 -07001293
1294 if (waitMs > muteWaitMs) {
1295 *delayMs = waitMs - muteWaitMs;
1296 }
Eric Laurente552edb2014-03-10 17:42:56 -07001297 }
Eric Laurentdc462862016-07-19 12:29:53 -07001298
Eric Laurente552edb2014-03-10 17:42:56 -07001299 return NO_ERROR;
1300}
1301
1302
Eric Laurente0720872014-03-11 09:30:41 -07001303status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001304 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001305 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001306{
1307 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1308 ssize_t index = mOutputs.indexOfKey(output);
1309 if (index < 0) {
1310 ALOGW("stopOutput() unknown output %d", output);
1311 return BAD_VALUE;
1312 }
1313
Eric Laurentc75307b2015-03-17 15:29:32 -07001314 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001315
Eric Laurentc75307b2015-03-17 15:29:32 -07001316 if (outputDesc->mRefCount[stream] == 1) {
1317 // Automatically disable the remote submix input when output is stopped on a
1318 // re routing mix of type MIX_TYPE_RECORDERS
1319 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1320 outputDesc->mPolicyMix != NULL &&
1321 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1322 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1323 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001324 outputDesc->mPolicyMix->mDeviceAddress,
Eric Laurentc75307b2015-03-17 15:29:32 -07001325 "remote-submix");
1326 }
1327 }
1328
1329 // Routing?
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001330 bool forceDeviceUpdate = false;
Eric Laurentc75307b2015-03-17 15:29:32 -07001331 if (outputDesc->mRefCount[stream] > 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001332 int activityCount = mOutputRoutes.decRouteActivity(session);
1333 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1334
1335 if (forceDeviceUpdate) {
1336 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1337 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001338 }
1339
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001340 return stopSource(outputDesc, stream, forceDeviceUpdate);
Eric Laurentc75307b2015-03-17 15:29:32 -07001341}
1342
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001343status_t AudioPolicyManager::stopSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001344 audio_stream_type_t stream,
1345 bool forceDeviceUpdate)
Eric Laurentc75307b2015-03-17 15:29:32 -07001346{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001347 // always handle stream stop, check which stream type is stopping
1348 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1349
Eric Laurente552edb2014-03-10 17:42:56 -07001350 // handle special case for sonification while in call
1351 if (isInCall()) {
1352 handleIncallSonification(stream, false, false);
1353 }
1354
1355 if (outputDesc->mRefCount[stream] > 0) {
1356 // decrement usage count of this stream on the output
1357 outputDesc->changeRefCount(stream, -1);
Paul McLeanaa981192015-03-21 09:55:15 -07001358
Eric Laurente552edb2014-03-10 17:42:56 -07001359 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001360 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001361 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001362 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001363 // delay the device switch by twice the latency because stopOutput() is executed when
1364 // the track stop() command is received and at that time the audio track buffer can
1365 // still contain data that needs to be drained. The latency only covers the audio HAL
1366 // and kernel buffers. Also the latency does not always include additional delay in the
1367 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001368 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001369
1370 // force restoring the device selection on other active outputs if it differs from the
1371 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001372 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001373 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001374 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001375 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001376 desc->isActive() &&
1377 outputDesc->sharesHwModuleWith(desc) &&
1378 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001379 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1380 bool force = desc->device() != newDevice2;
Eric Laurentc75307b2015-03-17 15:29:32 -07001381 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001382 newDevice2,
1383 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001384 delayMs);
1385 // re-apply device specific volume if not done by setOutputDevice()
1386 if (!force) {
1387 applyStreamVolumes(desc, newDevice2, delayMs);
1388 }
Eric Laurente552edb2014-03-10 17:42:56 -07001389 }
1390 }
1391 // update the outputs if stopping one with a stream that can affect notification routing
1392 handleNotificationRoutingForStream(stream);
1393 }
Eric Laurent36829f92017-04-07 19:04:42 -07001394 if (stream == AUDIO_STREAM_MUSIC) {
1395 selectOutputForMusicEffects();
1396 }
Eric Laurente552edb2014-03-10 17:42:56 -07001397 return NO_ERROR;
1398 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001399 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001400 return INVALID_OPERATION;
1401 }
1402}
1403
Eric Laurente83b55d2014-11-14 10:06:21 -08001404void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001405 audio_stream_type_t stream __unused,
1406 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001407{
1408 ALOGV("releaseOutput() %d", output);
1409 ssize_t index = mOutputs.indexOfKey(output);
1410 if (index < 0) {
1411 ALOGW("releaseOutput() releasing unknown output %d", output);
1412 return;
1413 }
1414
Paul McLeanaa981192015-03-21 09:55:15 -07001415 // Routing
1416 mOutputRoutes.removeRoute(session);
1417
Eric Laurentc75307b2015-03-17 15:29:32 -07001418 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001419 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001420 if (desc->mDirectOpenCount <= 0) {
1421 ALOGW("releaseOutput() invalid open count %d for output %d",
1422 desc->mDirectOpenCount, output);
1423 return;
1424 }
1425 if (--desc->mDirectOpenCount == 0) {
1426 closeOutput(output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001427 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001428 }
1429 }
1430}
1431
1432
Eric Laurentcaf7f482014-11-25 17:50:47 -08001433status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1434 audio_io_handle_t *input,
1435 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001436 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001437 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001438 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001439 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001440 input_type_t *inputType,
1441 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001442{
Eric Laurentcaf7f482014-11-25 17:50:47 -08001443 ALOGV("getInputForAttr() source %d, samplingRate %d, format %d, channelMask %x,"
1444 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001445 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001446
Eric Laurentcb4dae22017-07-01 19:39:32 -07001447 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1448 // possible
1449 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1450 *input != AUDIO_IO_HANDLE_NONE) {
1451 ssize_t index = mInputs.indexOfKey(*input);
1452 if (index < 0) {
1453 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1454 return BAD_VALUE;
1455 }
1456 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1457 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1458 if (audioSession == 0) {
1459 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1460 return BAD_VALUE;
1461 }
1462 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1463 // The second call is for the first active client and sets the UID. Any further call
1464 // corresponds to a new client and is only permitted from the same UId.
1465 if (audioSession->openCount() == 1) {
1466 audioSession->setUid(uid);
1467 } else if (audioSession->uid() != uid) {
1468 ALOGW("getInputForAttr() bad uid %d for session %d uid %d",
1469 uid, session, audioSession->uid());
1470 return INVALID_OPERATION;
1471 }
1472 audioSession->changeOpenCount(1);
1473 *inputType = API_INPUT_LEGACY;
1474 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1475 *portId = AudioPort::getNextUniqueId();
1476 }
1477 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(inputDesc->mDevice);
1478 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1479 : AUDIO_PORT_HANDLE_NONE;
1480 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
1481 return NO_ERROR;
1482 }
1483
Eric Laurentcaf7f482014-11-25 17:50:47 -08001484 *input = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001485 *inputType = API_INPUT_INVALID;
Eric Laurentfb66dd92016-01-28 18:32:03 -08001486
Eric Laurent275e8e92014-11-30 15:14:47 -08001487 audio_devices_t device;
1488 // handle legacy remote submix case where the address was not always specified
1489 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001490 audio_source_t inputSource = attr->source;
1491 audio_source_t halInputSource;
Eric Laurentc722f302014-12-10 11:21:49 -08001492 AudioMix *policyMix = NULL;
Eric Laurent275e8e92014-11-30 15:14:47 -08001493
Eric Laurentc447ded2015-01-06 08:47:05 -08001494 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1495 inputSource = AUDIO_SOURCE_MIC;
1496 }
1497 halInputSource = inputSource;
1498
Eric Laurent20b9ef02016-12-05 11:03:16 -08001499 // TODO: check for existing client for this port ID
1500 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1501 *portId = AudioPort::getNextUniqueId();
1502 }
1503
Paul McLean466dc8e2015-04-17 13:15:36 -06001504 // Explicit routing?
1505 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -07001506 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
1507 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
1508 if (mAvailableInputDevices[i]->getId() == *selectedDeviceId) {
1509 deviceDesc = mAvailableInputDevices[i];
1510 break;
1511 }
Paul McLean466dc8e2015-04-17 13:15:36 -06001512 }
1513 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001514 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
Paul McLean466dc8e2015-04-17 13:15:36 -06001515
Eric Laurentc447ded2015-01-06 08:47:05 -08001516 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001517 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07001518 status_t ret = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
François Gaffie036e1e92015-03-19 10:16:24 +01001519 if (ret != NO_ERROR) {
1520 return ret;
1521 }
1522 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001523 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1524 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001525 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001526 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001527 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001528 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurent275e8e92014-11-30 15:14:47 -08001529 return BAD_VALUE;
1530 }
Eric Laurentc722f302014-12-10 11:21:49 -08001531 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001532 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001533 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1534 // there is an external policy, but this input is attached to a mix of recorders,
1535 // meaning it receives audio injected into the framework, so the recorder doesn't
1536 // know about it and is therefore considered "legacy"
1537 *inputType = API_INPUT_LEGACY;
1538 } else {
1539 // recording a mix of players defined by an external policy, we're rerouting for
1540 // an external policy
1541 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1542 }
Eric Laurentc722f302014-12-10 11:21:49 -08001543 } else if (audio_is_remote_submix_device(device)) {
1544 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001545 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001546 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1547 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001548 } else {
1549 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001550 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001551
Eric Laurent599c7582015-12-07 18:05:55 -08001552 }
1553
1554 *input = getInputForDevice(device, address, session, uid, inputSource,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001555 config->sample_rate, config->format, config->channel_mask, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001556 policyMix);
1557 if (*input == AUDIO_IO_HANDLE_NONE) {
1558 mInputRoutes.removeRoute(session);
1559 return INVALID_OPERATION;
1560 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001561
Eric Laurent2ac76942017-06-22 17:17:09 -07001562 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(device);
1563 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1564 : AUDIO_PORT_HANDLE_NONE;
1565
1566 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d",
1567 *input, *inputType, *selectedDeviceId);
1568
Eric Laurent599c7582015-12-07 18:05:55 -08001569 return NO_ERROR;
1570}
1571
1572
1573audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1574 String8 address,
1575 audio_session_t session,
1576 uid_t uid,
1577 audio_source_t inputSource,
1578 uint32_t samplingRate,
1579 audio_format_t format,
1580 audio_channel_mask_t channelMask,
1581 audio_input_flags_t flags,
1582 AudioMix *policyMix)
1583{
1584 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1585 audio_source_t halInputSource = inputSource;
1586 bool isSoundTrigger = false;
1587
1588 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1589 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1590 if (index >= 0) {
1591 input = mSoundTriggerSessions.valueFor(session);
1592 isSoundTrigger = true;
1593 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1594 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1595 } else {
1596 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001597 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001598 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001599 audio_is_linear_pcm(format)) {
1600 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001601 }
1602
Andy Hungf129b032015-04-07 13:45:50 -07001603 // find a compatible input profile (not necessarily identical in parameters)
1604 sp<IOProfile> profile;
1605 // samplingRate and flags may be updated by getInputProfile
Glenn Kasten05ddca52016-02-11 08:17:12 -08001606 uint32_t profileSamplingRate = (samplingRate == 0) ? SAMPLE_RATE_HZ_DEFAULT : samplingRate;
Andy Hungf129b032015-04-07 13:45:50 -07001607 audio_format_t profileFormat = format;
1608 audio_channel_mask_t profileChannelMask = channelMask;
1609 audio_input_flags_t profileFlags = flags;
1610 for (;;) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001611 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001612 profileSamplingRate, profileFormat, profileChannelMask,
1613 profileFlags);
1614 if (profile != 0) {
1615 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001616 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1617 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001618 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1619 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1620 } else { // fail
Glenn Kastenfaa10a62017-05-25 15:52:05 -07001621 ALOGW("getInputForDevice() could not find profile for device 0x%X, "
Eric Laurent599c7582015-12-07 18:05:55 -08001622 "samplingRate %u, format %#x, channelMask 0x%X, flags %#x",
Andy Hungf129b032015-04-07 13:45:50 -07001623 device, samplingRate, format, channelMask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001624 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001625 }
Eric Laurente552edb2014-03-10 17:42:56 -07001626 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001627 // Pick input sampling rate if not specified by client
1628 if (samplingRate == 0) {
1629 samplingRate = profileSamplingRate;
1630 }
Eric Laurente552edb2014-03-10 17:42:56 -07001631
Eric Laurent322b4d22015-04-03 15:57:54 -07001632 if (profile->getModuleHandle() == 0) {
1633 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001634 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001635 }
1636
Eric Laurent599c7582015-12-07 18:05:55 -08001637 sp<AudioSession> audioSession = new AudioSession(session,
1638 inputSource,
1639 format,
1640 samplingRate,
1641 channelMask,
1642 flags,
1643 uid,
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001644 isSoundTrigger,
1645 policyMix, mpClientInterface);
Eric Laurent599c7582015-12-07 18:05:55 -08001646
Eric Laurent74708e72017-04-07 17:13:42 -07001647// FIXME: disable concurrent capture until UI is ready
1648#if 0
Eric Laurent599c7582015-12-07 18:05:55 -08001649 // reuse an open input if possible
Eric Laurent555530a2017-02-07 18:17:24 -08001650 sp<AudioInputDescriptor> reusedInputDesc;
Eric Laurent599c7582015-12-07 18:05:55 -08001651 for (size_t i = 0; i < mInputs.size(); i++) {
1652 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001653 // reuse input if:
1654 // - it shares the same profile
1655 // AND
1656 // - it is not a reroute submix input
1657 // AND
1658 // - it is: not used for sound trigger
1659 // OR
1660 // used for sound trigger and all clients use the same session ID
1661 //
1662 if ((profile == desc->mProfile) &&
1663 (isSoundTrigger == desc->isSoundTrigger()) &&
1664 !is_virtual_input_device(device)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001665
1666 sp<AudioSession> as = desc->getAudioSession(session);
1667 if (as != 0) {
1668 // do not allow unmatching properties on same session
1669 if (as->matches(audioSession)) {
1670 as->changeOpenCount(1);
1671 } else {
1672 ALOGW("getInputForDevice() record with different attributes"
1673 " exists for session %d", session);
Eric Laurent555530a2017-02-07 18:17:24 -08001674 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001675 }
Eric Laurentfb66dd92016-01-28 18:32:03 -08001676 } else if (isSoundTrigger) {
Eric Laurent555530a2017-02-07 18:17:24 -08001677 continue;
Eric Laurentfb66dd92016-01-28 18:32:03 -08001678 }
Eric Laurentbb948092017-01-23 18:33:30 -08001679
Eric Laurent555530a2017-02-07 18:17:24 -08001680 // Reuse the already opened input stream on this profile if:
1681 // - the new capture source is background OR
1682 // - the path requested configurations match OR
1683 // - the new source priority is less than the highest source priority on this input
1684 // If the input stream cannot be reused, close it before opening a new stream
1685 // on the same profile for the new client so that the requested path configuration
1686 // can be selected.
1687 if (!isConcurrentSource(inputSource) &&
Eric Laurentbb948092017-01-23 18:33:30 -08001688 ((desc->mSamplingRate != samplingRate ||
Eric Laurentfb66dd92016-01-28 18:32:03 -08001689 desc->mChannelMask != channelMask ||
Eric Laurente6930022016-02-11 10:20:40 -08001690 !audio_formats_match(desc->mFormat, format)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001691 (source_priority(desc->getHighestPrioritySource(false /*activeOnly*/)) <
Eric Laurentbb948092017-01-23 18:33:30 -08001692 source_priority(inputSource)))) {
Eric Laurent555530a2017-02-07 18:17:24 -08001693 reusedInputDesc = desc;
1694 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001695 } else {
1696 desc->addAudioSession(session, audioSession);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001697 ALOGV("%s: reusing input %d", __FUNCTION__, mInputs.keyAt(i));
1698 return mInputs.keyAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08001699 }
Eric Laurent599c7582015-12-07 18:05:55 -08001700 }
1701 }
Eric Laurent599c7582015-12-07 18:05:55 -08001702
Eric Laurent555530a2017-02-07 18:17:24 -08001703 if (reusedInputDesc != 0) {
1704 AudioSessionCollection sessions = reusedInputDesc->getAudioSessions(false /*activeOnly*/);
1705 for (size_t j = 0; j < sessions.size(); j++) {
1706 audio_session_t currentSession = sessions.keyAt(j);
1707 stopInput(reusedInputDesc->mIoHandle, currentSession);
1708 releaseInput(reusedInputDesc->mIoHandle, currentSession);
1709 }
1710 }
Eric Laurent74708e72017-04-07 17:13:42 -07001711#endif
Eric Laurent555530a2017-02-07 18:17:24 -08001712
Eric Laurentcf2c0212014-07-25 16:20:43 -07001713 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
Andy Hungf129b032015-04-07 13:45:50 -07001714 config.sample_rate = profileSamplingRate;
1715 config.channel_mask = profileChannelMask;
1716 config.format = profileFormat;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001717
Eric Laurente3014102017-05-03 11:15:43 -07001718 if (address == "") {
1719 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(device);
1720 // the inputs vector must be of size 1, but we don't want to crash here
1721 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress : String8("");
1722 }
1723
Eric Laurent322b4d22015-04-03 15:57:54 -07001724 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurent599c7582015-12-07 18:05:55 -08001725 &input,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001726 &config,
1727 &device,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001728 address,
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001729 halInputSource,
Andy Hungf129b032015-04-07 13:45:50 -07001730 profileFlags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001731
1732 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001733 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Andy Hungf129b032015-04-07 13:45:50 -07001734 (profileSamplingRate != config.sample_rate) ||
Eric Laurente6930022016-02-11 10:20:40 -08001735 !audio_formats_match(profileFormat, config.format) ||
Andy Hungf129b032015-04-07 13:45:50 -07001736 (profileChannelMask != config.channel_mask)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001737 ALOGW("getInputForAttr() failed opening input: samplingRate %d"
1738 ", format %d, channelMask %x",
Eric Laurentcf2c0212014-07-25 16:20:43 -07001739 samplingRate, format, channelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001740 if (input != AUDIO_IO_HANDLE_NONE) {
1741 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001742 }
Eric Laurent599c7582015-12-07 18:05:55 -08001743 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001744 }
1745
Eric Laurent1f2f2232014-06-02 12:01:23 -07001746 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Andy Hungf129b032015-04-07 13:45:50 -07001747 inputDesc->mSamplingRate = profileSamplingRate;
1748 inputDesc->mFormat = profileFormat;
1749 inputDesc->mChannelMask = profileChannelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001750 inputDesc->mDevice = device;
Eric Laurentc722f302014-12-10 11:21:49 -08001751 inputDesc->mPolicyMix = policyMix;
Eric Laurent599c7582015-12-07 18:05:55 -08001752 inputDesc->addAudioSession(session, audioSession);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001753
Eric Laurent599c7582015-12-07 18:05:55 -08001754 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001755 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001756
Eric Laurent599c7582015-12-07 18:05:55 -08001757 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001758}
1759
Eric Laurentbb948092017-01-23 18:33:30 -08001760//static
1761bool AudioPolicyManager::isConcurrentSource(audio_source_t source)
1762{
1763 return (source == AUDIO_SOURCE_HOTWORD) ||
1764 (source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
1765 (source == AUDIO_SOURCE_FM_TUNER);
1766}
1767
Eric Laurentfb66dd92016-01-28 18:32:03 -08001768bool AudioPolicyManager::isConcurentCaptureAllowed(const sp<AudioInputDescriptor>& inputDesc,
1769 const sp<AudioSession>& audioSession)
1770{
1771 // Do not allow capture if an active voice call is using a software patch and
1772 // the call TX source device is on the same HW module.
1773 // FIXME: would be better to refine to only inputs whose profile connects to the
1774 // call TX device but this information is not in the audio patch
1775 if (mCallTxPatch != 0 &&
1776 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1777 return false;
1778 }
1779
1780 // starting concurrent capture is enabled if:
1781 // 1) capturing for re-routing
1782 // 2) capturing for HOTWORD source
1783 // 3) capturing for FM TUNER source
1784 // 3) All other active captures are either for re-routing or HOTWORD
1785
1786 if (is_virtual_input_device(inputDesc->mDevice) ||
Eric Laurentbb948092017-01-23 18:33:30 -08001787 isConcurrentSource(audioSession->inputSource())) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001788 return true;
1789 }
1790
1791 Vector< sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
1792 for (size_t i = 0; i < activeInputs.size(); i++) {
1793 sp<AudioInputDescriptor> activeInput = activeInputs[i];
Eric Laurentbb948092017-01-23 18:33:30 -08001794 if (!isConcurrentSource(activeInput->inputSource(true)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001795 !is_virtual_input_device(activeInput->mDevice)) {
1796 return false;
1797 }
1798 }
1799
1800 return true;
1801}
1802
Chris Thornton2b864642017-06-27 21:26:07 -07001803// FIXME: remove when concurrent capture is ready. This is a hack to work around bug b/63083537.
1804bool AudioPolicyManager::soundTriggerSupportsConcurrentCapture() {
1805 if (!mHasComputedSoundTriggerSupportsConcurrentCapture) {
1806 bool soundTriggerSupportsConcurrentCapture = false;
1807 unsigned int numModules = 0;
1808 struct sound_trigger_module_descriptor* nModules = NULL;
1809
1810 status_t status = SoundTrigger::listModules(nModules, &numModules);
1811 if (status == NO_ERROR && numModules != 0) {
1812 nModules = (struct sound_trigger_module_descriptor*) calloc(
1813 numModules, sizeof(struct sound_trigger_module_descriptor));
1814 if (nModules == NULL) {
1815 // We failed to malloc the buffer, so just say no for now, and hope that we have more
1816 // ram the next time this function is called.
1817 ALOGE("Failed to allocate buffer for module descriptors");
1818 return false;
1819 }
1820
1821 status = SoundTrigger::listModules(nModules, &numModules);
1822 if (status == NO_ERROR) {
1823 soundTriggerSupportsConcurrentCapture = true;
1824 for (size_t i = 0; i < numModules; ++i) {
1825 soundTriggerSupportsConcurrentCapture &=
1826 nModules[i].properties.concurrent_capture;
1827 }
1828 }
1829 free(nModules);
1830 }
1831 mSoundTriggerSupportsConcurrentCapture = soundTriggerSupportsConcurrentCapture;
1832 mHasComputedSoundTriggerSupportsConcurrentCapture = true;
1833 }
1834 return mSoundTriggerSupportsConcurrentCapture;
1835}
1836
Eric Laurentfb66dd92016-01-28 18:32:03 -08001837
Eric Laurent4dc68062014-07-28 17:26:49 -07001838status_t AudioPolicyManager::startInput(audio_io_handle_t input,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001839 audio_session_t session,
1840 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07001841{
1842 ALOGV("startInput() input %d", input);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001843 *concurrency = API_INPUT_CONCURRENCY_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001844 ssize_t index = mInputs.indexOfKey(input);
1845 if (index < 0) {
1846 ALOGW("startInput() unknown input %d", input);
1847 return BAD_VALUE;
1848 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001849 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001850
Eric Laurent599c7582015-12-07 18:05:55 -08001851 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1852 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07001853 ALOGW("startInput() unknown session %d on input %d", session, input);
1854 return BAD_VALUE;
1855 }
1856
Eric Laurent74708e72017-04-07 17:13:42 -07001857// FIXME: disable concurrent capture until UI is ready
1858#if 0
Eric Laurentfb66dd92016-01-28 18:32:03 -08001859 if (!isConcurentCaptureAllowed(inputDesc, audioSession)) {
1860 ALOGW("startInput(%d) failed: other input already started", input);
1861 return INVALID_OPERATION;
1862 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001863
Eric Laurentfb66dd92016-01-28 18:32:03 -08001864 if (isInCall()) {
1865 *concurrency |= API_INPUT_CONCURRENCY_CALL;
1866 }
Eric Laurentf7c50102016-09-30 15:19:43 -07001867 if (mInputs.activeInputsCountOnDevices() != 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001868 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurente552edb2014-03-10 17:42:56 -07001869 }
Eric Laurent74708e72017-04-07 17:13:42 -07001870#else
1871 if (!is_virtual_input_device(inputDesc->mDevice)) {
1872 if (mCallTxPatch != 0 &&
1873 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1874 ALOGW("startInput(%d) failed: call in progress", input);
1875 return INVALID_OPERATION;
1876 }
1877
1878 Vector< sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
1879 for (size_t i = 0; i < activeInputs.size(); i++) {
1880 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
1881
1882 if (is_virtual_input_device(activeDesc->mDevice)) {
1883 continue;
1884 }
1885
Eric Laurentcb4dae22017-07-01 19:39:32 -07001886 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
1887 activeDesc->getId() == inputDesc->getId()) {
1888 continue;
1889 }
1890
Eric Laurent74708e72017-04-07 17:13:42 -07001891 audio_source_t activeSource = activeDesc->inputSource(true);
1892 if (audioSession->inputSource() == AUDIO_SOURCE_HOTWORD) {
1893 if (activeSource == AUDIO_SOURCE_HOTWORD) {
1894 if (activeDesc->hasPreemptedSession(session)) {
1895 ALOGW("startInput(%d) failed for HOTWORD: "
1896 "other input %d already started for HOTWORD",
1897 input, activeDesc->mIoHandle);
1898 return INVALID_OPERATION;
1899 }
1900 } else {
1901 ALOGV("startInput(%d) failed for HOTWORD: other input %d already started",
1902 input, activeDesc->mIoHandle);
1903 return INVALID_OPERATION;
1904 }
1905 } else {
1906 if (activeSource != AUDIO_SOURCE_HOTWORD) {
1907 ALOGW("startInput(%d) failed: other input %d already started",
1908 input, activeDesc->mIoHandle);
1909 return INVALID_OPERATION;
1910 }
1911 }
1912 }
1913
Chris Thornton2b864642017-06-27 21:26:07 -07001914 // We only need to check if the sound trigger session supports concurrent capture if the
1915 // input is also a sound trigger input. Otherwise, we should preempt any hotword stream
1916 // that's running.
1917 const bool allowConcurrentWithSoundTrigger =
1918 inputDesc->isSoundTrigger() ? soundTriggerSupportsConcurrentCapture() : false;
1919
Eric Laurent74708e72017-04-07 17:13:42 -07001920 // if capture is allowed, preempt currently active HOTWORD captures
1921 for (size_t i = 0; i < activeInputs.size(); i++) {
1922 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
1923
1924 if (is_virtual_input_device(activeDesc->mDevice)) {
1925 continue;
1926 }
1927
Chris Thornton2b864642017-06-27 21:26:07 -07001928 if (allowConcurrentWithSoundTrigger && activeDesc->isSoundTrigger()) {
1929 continue;
1930 }
1931
Eric Laurent74708e72017-04-07 17:13:42 -07001932 audio_source_t activeSource = activeDesc->inputSource(true);
1933 if (activeSource == AUDIO_SOURCE_HOTWORD) {
1934 AudioSessionCollection activeSessions =
1935 activeDesc->getAudioSessions(true /*activeOnly*/);
1936 audio_session_t activeSession = activeSessions.keyAt(0);
1937 audio_io_handle_t activeHandle = activeDesc->mIoHandle;
1938 SortedVector<audio_session_t> sessions = activeDesc->getPreemptedSessions();
1939 sessions.add(activeSession);
1940 inputDesc->setPreemptedSessions(sessions);
1941 stopInput(activeHandle, activeSession);
1942 releaseInput(activeHandle, activeSession);
1943 ALOGV("startInput(%d) for HOTWORD preempting HOTWORD input %d",
1944 input, activeDesc->mIoHandle);
1945 }
1946 }
1947 }
1948#endif
Eric Laurente552edb2014-03-10 17:42:56 -07001949
Eric Laurent313d1e72016-01-29 09:56:57 -08001950 // increment activity count before calling getNewInputDevice() below as only active sessions
1951 // are considered for device selection
1952 audioSession->changeActiveCount(1);
1953
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001954 // Routing?
1955 mInputRoutes.incRouteActivity(session);
1956
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001957 if (audioSession->activeCount() == 1 || mInputRoutes.hasRouteChanged(session)) {
Eric Laurent271a93e2016-09-29 14:47:06 -07001958 // indicate active capture to sound trigger service if starting capture from a mic on
1959 // primary HW module
Eric Laurentf7c50102016-09-30 15:19:43 -07001960 audio_devices_t device = getNewInputDevice(inputDesc);
Eric Laurent271a93e2016-09-29 14:47:06 -07001961 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001962
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001963 if (inputDesc->getAudioSessionCount(true/*activeOnly*/) == 1) {
1964 // if input maps to a dynamic policy with an activity listener, notify of state change
1965 if ((inputDesc->mPolicyMix != NULL)
1966 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
1967 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
1968 MIX_STATE_MIXING);
Eric Laurentc722f302014-12-10 11:21:49 -08001969 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001970
Eric Laurentf7c50102016-09-30 15:19:43 -07001971 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
1972 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Eric Laurent05b345e2016-11-18 12:36:27 -08001973 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001974 SoundTrigger::setCaptureState(true);
1975 }
1976
1977 // automatically enable the remote submix output when input is started if not
1978 // used by a policy mix of type MIX_TYPE_RECORDERS
1979 // For remote submix (a virtual device), we open only one input per capture request.
1980 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1981 String8 address = String8("");
1982 if (inputDesc->mPolicyMix == NULL) {
1983 address = String8("0");
1984 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1985 address = inputDesc->mPolicyMix->mDeviceAddress;
1986 }
1987 if (address != "") {
1988 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1989 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1990 address, "remote-submix");
1991 }
Eric Laurentc722f302014-12-10 11:21:49 -08001992 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001993 }
Eric Laurente552edb2014-03-10 17:42:56 -07001994 }
1995
Eric Laurent599c7582015-12-07 18:05:55 -08001996 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
Eric Laurente552edb2014-03-10 17:42:56 -07001997
Eric Laurente552edb2014-03-10 17:42:56 -07001998 return NO_ERROR;
1999}
2000
Eric Laurent4dc68062014-07-28 17:26:49 -07002001status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
2002 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07002003{
2004 ALOGV("stopInput() input %d", input);
2005 ssize_t index = mInputs.indexOfKey(input);
2006 if (index < 0) {
2007 ALOGW("stopInput() unknown input %d", input);
2008 return BAD_VALUE;
2009 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002010 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07002011
Eric Laurent599c7582015-12-07 18:05:55 -08002012 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07002013 if (index < 0) {
2014 ALOGW("stopInput() unknown session %d on input %d", session, input);
2015 return BAD_VALUE;
2016 }
2017
Eric Laurent599c7582015-12-07 18:05:55 -08002018 if (audioSession->activeCount() == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002019 ALOGW("stopInput() input %d already stopped", input);
2020 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002021 }
2022
Eric Laurent599c7582015-12-07 18:05:55 -08002023 audioSession->changeActiveCount(-1);
Paul McLean466dc8e2015-04-17 13:15:36 -06002024
2025 // Routing?
2026 mInputRoutes.decRouteActivity(session);
2027
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002028 if (audioSession->activeCount() == 0) {
Eric Laurent84332aa2016-01-28 22:19:18 +00002029
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002030 if (inputDesc->isActive()) {
2031 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2032 } else {
2033 // if input maps to a dynamic policy with an activity listener, notify of state change
2034 if ((inputDesc->mPolicyMix != NULL)
2035 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2036 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2037 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002038 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002039
2040 // automatically disable the remote submix output when input is stopped if not
2041 // used by a policy mix of type MIX_TYPE_RECORDERS
2042 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2043 String8 address = String8("");
2044 if (inputDesc->mPolicyMix == NULL) {
2045 address = String8("0");
2046 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2047 address = inputDesc->mPolicyMix->mDeviceAddress;
2048 }
2049 if (address != "") {
2050 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2051 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2052 address, "remote-submix");
2053 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002054 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002055
Eric Laurentf7c50102016-09-30 15:19:43 -07002056 audio_devices_t device = inputDesc->mDevice;
Eric Laurentfb66dd92016-01-28 18:32:03 -08002057 resetInputDevice(input);
Eric Laurent84332aa2016-01-28 22:19:18 +00002058
Eric Laurentf7c50102016-09-30 15:19:43 -07002059 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2060 // primary HW module
2061 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2062 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2063 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08002064 SoundTrigger::setCaptureState(false);
2065 }
2066 inputDesc->clearPreemptedSessions();
Eric Laurent84332aa2016-01-28 22:19:18 +00002067 }
Eric Laurente552edb2014-03-10 17:42:56 -07002068 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002069 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002070}
2071
Eric Laurent4dc68062014-07-28 17:26:49 -07002072void AudioPolicyManager::releaseInput(audio_io_handle_t input,
2073 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07002074{
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002075
Eric Laurente552edb2014-03-10 17:42:56 -07002076 ALOGV("releaseInput() %d", input);
2077 ssize_t index = mInputs.indexOfKey(input);
2078 if (index < 0) {
2079 ALOGW("releaseInput() releasing unknown input %d", input);
2080 return;
2081 }
Paul McLean466dc8e2015-04-17 13:15:36 -06002082
2083 // Routing
2084 mInputRoutes.removeRoute(session);
2085
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002086 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
2087 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07002088
Eric Laurent599c7582015-12-07 18:05:55 -08002089 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
vivek mehta587b8df2017-01-31 14:58:44 -08002090 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07002091 ALOGW("releaseInput() unknown session %d on input %d", session, input);
2092 return;
2093 }
Eric Laurent599c7582015-12-07 18:05:55 -08002094
2095 if (audioSession->openCount() == 0) {
2096 ALOGW("releaseInput() invalid open count %d on session %d",
2097 audioSession->openCount(), session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002098 return;
2099 }
Eric Laurent599c7582015-12-07 18:05:55 -08002100
2101 if (audioSession->changeOpenCount(-1) == 0) {
2102 inputDesc->removeAudioSession(session);
2103 }
2104
Jean-Michel Trivi65bfe912015-12-04 15:56:47 -08002105 if (inputDesc->getOpenRefCount() > 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002106 ALOGV("releaseInput() exit > 0");
2107 return;
2108 }
2109
Eric Laurent05b90f82014-08-27 15:32:29 -07002110 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002111 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002112 ALOGV("releaseInput() exit");
2113}
2114
Eric Laurentd4692962014-05-05 18:13:44 -07002115void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002116 bool patchRemoved = false;
2117
Eric Laurentd4692962014-05-05 18:13:44 -07002118 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002119 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002120 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002121 if (patch_index >= 0) {
2122 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002123 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002124 mAudioPatches.removeItemsAt(patch_index);
2125 patchRemoved = true;
2126 }
Eric Laurentd4692962014-05-05 18:13:44 -07002127 mpClientInterface->closeInput(mInputs.keyAt(input_index));
2128 }
2129 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002130 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002131 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002132
2133 if (patchRemoved) {
2134 mpClientInterface->onAudioPatchListUpdate();
2135 }
Eric Laurentd4692962014-05-05 18:13:44 -07002136}
2137
Eric Laurente0720872014-03-11 09:30:41 -07002138void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002139 int indexMin,
2140 int indexMax)
2141{
2142 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002143 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002144
2145 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002146 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2147 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002148 continue;
2149 }
2150 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002151 }
Eric Laurente552edb2014-03-10 17:42:56 -07002152}
2153
Eric Laurente0720872014-03-11 09:30:41 -07002154status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002155 int index,
2156 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002157{
2158
François Gaffied1ab2bd2015-12-02 18:20:06 +01002159 if ((index < mVolumeCurves->getVolumeIndexMin(stream)) ||
2160 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002161 return BAD_VALUE;
2162 }
2163 if (!audio_is_output_device(device)) {
2164 return BAD_VALUE;
2165 }
2166
2167 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002168 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002169
Eric Laurent1fd372e2016-04-06 14:23:53 -07002170 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002171 stream, device, index);
2172
Eric Laurent28d09f02016-03-08 10:43:05 -08002173 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002174 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2175 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002176 continue;
2177 }
2178 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2179 }
Eric Laurente552edb2014-03-10 17:42:56 -07002180
Eric Laurent1fd372e2016-04-06 14:23:53 -07002181 // update volume on all outputs and streams matching the following:
2182 // - The requested stream (or a stream matching for volume control) is active on the output
2183 // - The device (or devices) selected by the strategy corresponding to this stream includes
2184 // the requested device
2185 // - For non default requested device, currently selected device on the output is either the
2186 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002187 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2188 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002189 status_t status = NO_ERROR;
2190 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002191 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2192 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08002193 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2194 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002195 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002196 }
Eric Laurentd3926fe2016-04-15 18:10:07 -07002197 if (!(desc->isStreamActive((audio_stream_type_t)curStream) ||
2198 (isInCall() && (curStream == AUDIO_STREAM_VOICE_CALL)))) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002199 continue;
2200 }
Eric Laurent794fde22016-03-11 09:50:45 -08002201 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002202 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2203 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002204 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2205 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002206 continue;
2207 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002208 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002209 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002210 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07002211 applyVolume = (curDevice & curStreamDevice) != 0;
2212 } else {
2213 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002214 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002215 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002216
Eric Laurente76f29c2016-09-14 17:17:53 -07002217 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002218 //FIXME: workaround for truncated touch sounds
2219 // delayed volume change for system stream to be removed when the problem is
2220 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002221 status_t volStatus =
Eric Laurentdc462862016-07-19 12:29:53 -07002222 checkAndSetVolume((audio_stream_type_t)curStream, index, desc, curDevice,
2223 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002224 if (volStatus != NO_ERROR) {
2225 status = volStatus;
2226 }
2227 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002228 }
Eric Laurente552edb2014-03-10 17:42:56 -07002229 }
2230 return status;
2231}
2232
Eric Laurente0720872014-03-11 09:30:41 -07002233status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002234 int *index,
2235 audio_devices_t device)
2236{
2237 if (index == NULL) {
2238 return BAD_VALUE;
2239 }
2240 if (!audio_is_output_device(device)) {
2241 return BAD_VALUE;
2242 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002243 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002244 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002245 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002246 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2247 }
François Gaffiedfd74092015-03-19 12:10:59 +01002248 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002249
François Gaffied1ab2bd2015-12-02 18:20:06 +01002250 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002251 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2252 return NO_ERROR;
2253}
2254
Eric Laurent36829f92017-04-07 19:04:42 -07002255audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002256{
2257 // select one output among several suitable for global effects.
2258 // The priority is as follows:
2259 // 1: An offloaded output. If the effect ends up not being offloadable,
2260 // AudioFlinger will invalidate the track and the offloaded output
2261 // will be closed causing the effect to be moved to a PCM output.
2262 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002263 // 3: The primary output
2264 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002265
Eric Laurent3b73df72014-03-11 09:06:29 -07002266 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002267 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent36829f92017-04-07 19:04:42 -07002268 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002269
Eric Laurent36829f92017-04-07 19:04:42 -07002270 if (outputs.size() == 0) {
2271 return AUDIO_IO_HANDLE_NONE;
2272 }
Eric Laurente552edb2014-03-10 17:42:56 -07002273
Eric Laurent36829f92017-04-07 19:04:42 -07002274 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2275 bool activeOnly = true;
2276
2277 while (output == AUDIO_IO_HANDLE_NONE) {
2278 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2279 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2280 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2281
2282 for (size_t i = 0; i < outputs.size(); i++) {
2283 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
2284 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2285 continue;
2286 }
2287 ALOGV("selectOutputForMusicEffects activeOnly %d outputs[%zu] flags 0x%08x",
2288 activeOnly, i, desc->mFlags);
2289 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
2290 outputOffloaded = outputs[i];
2291 }
2292 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
2293 outputDeepBuffer = outputs[i];
2294 }
2295 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
2296 outputPrimary = outputs[i];
2297 }
2298 }
2299 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2300 output = outputOffloaded;
2301 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2302 output = outputDeepBuffer;
2303 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2304 output = outputPrimary;
2305 } else {
2306 output = outputs[0];
2307 }
2308 activeOnly = false;
2309 }
2310
2311 if (output != mMusicEffectOutput) {
2312 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2313 mMusicEffectOutput = output;
2314 }
2315
2316 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002317 return output;
2318}
2319
Eric Laurent36829f92017-04-07 19:04:42 -07002320audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2321{
2322 return selectOutputForMusicEffects();
2323}
2324
Eric Laurente0720872014-03-11 09:30:41 -07002325status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002326 audio_io_handle_t io,
2327 uint32_t strategy,
2328 int session,
2329 int id)
2330{
2331 ssize_t index = mOutputs.indexOfKey(io);
2332 if (index < 0) {
2333 index = mInputs.indexOfKey(io);
2334 if (index < 0) {
2335 ALOGW("registerEffect() unknown io %d", io);
2336 return INVALID_OPERATION;
2337 }
2338 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002339 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002340}
2341
Eric Laurentc75307b2015-03-17 15:29:32 -07002342bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2343{
Eric Laurent28d09f02016-03-08 10:43:05 -08002344 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002345 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2346 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002347 continue;
2348 }
2349 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2350 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002351 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002352}
2353
2354bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2355{
2356 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2357}
2358
Eric Laurente0720872014-03-11 09:30:41 -07002359bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002360{
2361 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002362 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002363 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002364 return true;
2365 }
2366 }
2367 return false;
2368}
2369
Eric Laurent275e8e92014-11-30 15:14:47 -08002370// Register a list of custom mixes with their attributes and format.
2371// When a mix is registered, corresponding input and output profiles are
2372// added to the remote submix hw module. The profile contains only the
2373// parameters (sampling rate, format...) specified by the mix.
2374// The corresponding input remote submix device is also connected.
2375//
2376// When a remote submix device is connected, the address is checked to select the
2377// appropriate profile and the corresponding input or output stream is opened.
2378//
2379// When capture starts, getInputForAttr() will:
2380// - 1 look for a mix matching the address passed in attribtutes tags if any
2381// - 2 if none found, getDeviceForInputSource() will:
2382// - 2.1 look for a mix matching the attributes source
2383// - 2.2 if none found, default to device selection by policy rules
2384// At this time, the corresponding output remote submix device is also connected
2385// and active playback use cases can be transferred to this mix if needed when reconnecting
2386// after AudioTracks are invalidated
2387//
2388// When playback starts, getOutputForAttr() will:
2389// - 1 look for a mix matching the address passed in attribtutes tags if any
2390// - 2 if none found, look for a mix matching the attributes usage
2391// - 3 if none found, default to device and output selection by policy rules.
2392
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002393status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002394{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002395 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2396 status_t res = NO_ERROR;
2397
2398 sp<HwModule> rSubmixModule;
2399 // examine each mix's route type
2400 for (size_t i = 0; i < mixes.size(); i++) {
2401 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
2402 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
2403 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002404 break;
2405 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002406 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
2407 // Loop back through "remote submix"
2408 if (rSubmixModule == 0) {
2409 for (size_t j = 0; i < mHwModules.size(); j++) {
2410 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
2411 && mHwModules[j]->mHandle != 0) {
2412 rSubmixModule = mHwModules[j];
2413 break;
2414 }
2415 }
2416 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002417
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002418 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Eric Laurent275e8e92014-11-30 15:14:47 -08002419
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002420 if (rSubmixModule == 0) {
2421 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration", i);
2422 res = INVALID_OPERATION;
2423 break;
2424 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002425
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002426 String8 address = mixes[i].mDeviceAddress;
François Gaffie036e1e92015-03-19 10:16:24 +01002427
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002428 if (mPolicyMixes.registerMix(address, mixes[i], 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002429 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002430 res = INVALID_OPERATION;
2431 break;
2432 }
2433 audio_config_t outputConfig = mixes[i].mFormat;
2434 audio_config_t inputConfig = mixes[i].mFormat;
2435 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2436 // stereo and let audio flinger do the channel conversion if needed.
2437 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2438 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2439 rSubmixModule->addOutputProfile(address, &outputConfig,
2440 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2441 rSubmixModule->addInputProfile(address, &inputConfig,
2442 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002443
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002444 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
2445 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2446 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2447 address.string(), "remote-submix");
2448 } else {
2449 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2450 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2451 address.string(), "remote-submix");
2452 }
2453 } else if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002454 String8 address = mixes[i].mDeviceAddress;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002455 audio_devices_t device = mixes[i].mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002456 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2457 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002458
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002459 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002460 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2461 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2462 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2463 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2464 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2465 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002466 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2467 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002468 if (mPolicyMixes.registerMix(address, mixes[i], desc) != NO_ERROR) {
2469 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002470 } else {
2471 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002472 }
2473 break;
2474 }
2475 }
2476
2477 if (res != NO_ERROR) {
2478 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002479 i, device, address.string());
2480 res = INVALID_OPERATION;
2481 break;
2482 } else if (!foundOutput) {
2483 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2484 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002485 res = INVALID_OPERATION;
2486 break;
2487 }
Eric Laurentc722f302014-12-10 11:21:49 -08002488 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002489 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002490 if (res != NO_ERROR) {
2491 unregisterPolicyMixes(mixes);
2492 }
2493 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002494}
2495
2496status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2497{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002498 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002499 status_t res = NO_ERROR;
2500 sp<HwModule> rSubmixModule;
2501 // examine each mix's route type
Eric Laurent275e8e92014-11-30 15:14:47 -08002502 for (size_t i = 0; i < mixes.size(); i++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002503 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002504
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002505 if (rSubmixModule == 0) {
2506 for (size_t j = 0; i < mHwModules.size(); j++) {
2507 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
2508 && mHwModules[j]->mHandle != 0) {
2509 rSubmixModule = mHwModules[j];
2510 break;
2511 }
2512 }
2513 }
2514 if (rSubmixModule == 0) {
2515 res = INVALID_OPERATION;
2516 continue;
2517 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002518
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002519 String8 address = mixes[i].mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002520
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002521 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2522 res = INVALID_OPERATION;
2523 continue;
2524 }
2525
2526 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2527 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2528 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2529 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2530 address.string(), "remote-submix");
2531 }
2532 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2533 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2534 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2535 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2536 address.string(), "remote-submix");
2537 }
2538 rSubmixModule->removeOutputProfile(address);
2539 rSubmixModule->removeInputProfile(address);
2540
2541 } if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2542 if (mPolicyMixes.unregisterMix(mixes[i].mDeviceAddress) != NO_ERROR) {
2543 res = INVALID_OPERATION;
2544 continue;
2545 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002546 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002547 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002548 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002549}
2550
Eric Laurente552edb2014-03-10 17:42:56 -07002551
Eric Laurente0720872014-03-11 09:30:41 -07002552status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002553{
2554 const size_t SIZE = 256;
2555 char buffer[SIZE];
2556 String8 result;
2557
2558 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2559 result.append(buffer);
2560
Eric Laurent87ffa392015-05-22 10:32:38 -07002561 snprintf(buffer, SIZE, " Primary Output: %d\n",
2562 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Eric Laurente552edb2014-03-10 17:42:56 -07002563 result.append(buffer);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002564 std::string stateLiteral;
2565 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
2566 snprintf(buffer, SIZE, " Phone state: %s\n", stateLiteral.c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002567 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002568 snprintf(buffer, SIZE, " Force use for communications %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002569 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07002570 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002571 snprintf(buffer, SIZE, " Force use for media %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA));
Eric Laurente552edb2014-03-10 17:42:56 -07002572 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002573 snprintf(buffer, SIZE, " Force use for record %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD));
Eric Laurente552edb2014-03-10 17:42:56 -07002574 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002575 snprintf(buffer, SIZE, " Force use for dock %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_DOCK));
Eric Laurente552edb2014-03-10 17:42:56 -07002576 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002577 snprintf(buffer, SIZE, " Force use for system %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM));
Eric Laurente552edb2014-03-10 17:42:56 -07002578 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002579 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002580 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO));
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002581 result.append(buffer);
Phil Burk09bc4612016-02-24 15:58:15 -08002582 snprintf(buffer, SIZE, " Force use for encoded surround output %d\n",
2583 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND));
2584 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002585 snprintf(buffer, SIZE, " TTS output %s\n", mTtsOutputAvailable ? "available" : "not available");
2586 result.append(buffer);
Andy Hung2ddee192015-12-18 17:34:44 -08002587 snprintf(buffer, SIZE, " Master mono: %s\n", mMasterMono ? "on" : "off");
2588 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002589
François Gaffie2110e042015-03-24 08:41:51 +01002590 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002591
François Gaffie112b0af2015-11-19 16:13:25 +01002592 mAvailableOutputDevices.dump(fd, String8("Available output"));
2593 mAvailableInputDevices.dump(fd, String8("Available input"));
François Gaffie53615e22015-03-19 09:24:12 +01002594 mHwModules.dump(fd);
2595 mOutputs.dump(fd);
2596 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002597 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002598 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002599 mAudioPatches.dump(fd);
Mikhail Naganov44344b02016-12-13 11:21:02 -08002600 mPolicyMixes.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002601
2602 return NO_ERROR;
2603}
2604
2605// This function checks for the parameters which can be offloaded.
2606// This can be enhanced depending on the capability of the DSP and policy
2607// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002608bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002609{
2610 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002611 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002612 offloadInfo.sample_rate, offloadInfo.channel_mask,
2613 offloadInfo.format,
2614 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2615 offloadInfo.has_video);
2616
Andy Hung2ddee192015-12-18 17:34:44 -08002617 if (mMasterMono) {
2618 return false; // no offloading if mono is set.
2619 }
2620
Eric Laurente552edb2014-03-10 17:42:56 -07002621 // Check if offload has been disabled
2622 char propValue[PROPERTY_VALUE_MAX];
2623 if (property_get("audio.offload.disable", propValue, "0")) {
2624 if (atoi(propValue) != 0) {
2625 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2626 return false;
2627 }
2628 }
2629
2630 // Check if stream type is music, then only allow offload as of now.
2631 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2632 {
2633 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2634 return false;
2635 }
2636
2637 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002638 const bool allowOffloadWithVideo =
2639 property_get_bool("audio.offload.video", false /* default_value */);
2640 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002641 ALOGV("isOffloadSupported: has_video == true, returning false");
2642 return false;
2643 }
2644
2645 //If duration is less than minimum value defined in property, return false
2646 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2647 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2648 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2649 return false;
2650 }
2651 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2652 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2653 return false;
2654 }
2655
2656 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2657 // creating an offloaded track and tearing it down immediately after start when audioflinger
2658 // detects there is an active non offloadable effect.
2659 // FIXME: We should check the audio session here but we do not have it in this context.
2660 // This may prevent offloading in rare situations where effects are left active by apps
2661 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002662 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002663 return false;
2664 }
2665
2666 // See if there is a profile to support this.
2667 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002668 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002669 offloadInfo.sample_rate,
2670 offloadInfo.format,
2671 offloadInfo.channel_mask,
2672 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002673 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2674 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002675}
2676
Eric Laurent6a94d692014-05-20 11:18:06 -07002677status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2678 audio_port_type_t type,
2679 unsigned int *num_ports,
2680 struct audio_port *ports,
2681 unsigned int *generation)
2682{
2683 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2684 generation == NULL) {
2685 return BAD_VALUE;
2686 }
2687 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2688 if (ports == NULL) {
2689 *num_ports = 0;
2690 }
2691
2692 size_t portsWritten = 0;
2693 size_t portsMax = *num_ports;
2694 *num_ports = 0;
2695 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002696 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2697 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002698 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002699 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
2700 if (mAvailableOutputDevices[i]->type() == AUDIO_DEVICE_OUT_STUB) {
2701 continue;
2702 }
2703 if (portsWritten < portsMax) {
2704 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2705 }
2706 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002707 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002708 }
2709 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002710 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2711 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_STUB) {
2712 continue;
2713 }
2714 if (portsWritten < portsMax) {
2715 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2716 }
2717 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002718 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002719 }
2720 }
2721 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2722 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2723 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2724 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2725 }
2726 *num_ports += mInputs.size();
2727 }
2728 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002729 size_t numOutputs = 0;
2730 for (size_t i = 0; i < mOutputs.size(); i++) {
2731 if (!mOutputs[i]->isDuplicated()) {
2732 numOutputs++;
2733 if (portsWritten < portsMax) {
2734 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2735 }
2736 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002737 }
Eric Laurent84c70242014-06-23 08:46:27 -07002738 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002739 }
2740 }
2741 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002742 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002743 return NO_ERROR;
2744}
2745
2746status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2747{
2748 return NO_ERROR;
2749}
2750
Eric Laurent6a94d692014-05-20 11:18:06 -07002751status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2752 audio_patch_handle_t *handle,
2753 uid_t uid)
2754{
2755 ALOGV("createAudioPatch()");
2756
2757 if (handle == NULL || patch == NULL) {
2758 return BAD_VALUE;
2759 }
2760 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2761
Eric Laurent874c42872014-08-08 15:13:39 -07002762 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2763 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2764 return BAD_VALUE;
2765 }
2766 // only one source per audio patch supported for now
2767 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002768 return INVALID_OPERATION;
2769 }
Eric Laurent874c42872014-08-08 15:13:39 -07002770
2771 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002772 return INVALID_OPERATION;
2773 }
Eric Laurent874c42872014-08-08 15:13:39 -07002774 for (size_t i = 0; i < patch->num_sinks; i++) {
2775 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2776 return INVALID_OPERATION;
2777 }
2778 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002779
2780 sp<AudioPatch> patchDesc;
2781 ssize_t index = mAudioPatches.indexOfKey(*handle);
2782
Eric Laurent6a94d692014-05-20 11:18:06 -07002783 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2784 patch->sources[0].role,
2785 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002786#if LOG_NDEBUG == 0
2787 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002788 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002789 patch->sinks[i].role,
2790 patch->sinks[i].type);
2791 }
2792#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002793
2794 if (index >= 0) {
2795 patchDesc = mAudioPatches.valueAt(index);
2796 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2797 mUidCached, patchDesc->mUid, uid);
2798 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2799 return INVALID_OPERATION;
2800 }
2801 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002802 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002803 }
2804
2805 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002806 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002807 if (outputDesc == NULL) {
2808 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2809 return BAD_VALUE;
2810 }
Eric Laurent84c70242014-06-23 08:46:27 -07002811 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2812 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002813 if (patchDesc != 0) {
2814 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2815 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2816 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2817 return BAD_VALUE;
2818 }
2819 }
Eric Laurent874c42872014-08-08 15:13:39 -07002820 DeviceVector devices;
2821 for (size_t i = 0; i < patch->num_sinks; i++) {
2822 // Only support mix to devices connection
2823 // TODO add support for mix to mix connection
2824 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2825 ALOGV("createAudioPatch() source mix but sink is not a device");
2826 return INVALID_OPERATION;
2827 }
2828 sp<DeviceDescriptor> devDesc =
2829 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2830 if (devDesc == 0) {
2831 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2832 return BAD_VALUE;
2833 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002834
François Gaffie53615e22015-03-19 09:24:12 +01002835 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002836 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002837 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002838 NULL, // updatedSamplingRate
2839 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002840 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002841 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002842 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002843 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002844 ALOGV("createAudioPatch() profile not supported for device %08x",
2845 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002846 return INVALID_OPERATION;
2847 }
2848 devices.add(devDesc);
2849 }
2850 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002851 return INVALID_OPERATION;
2852 }
Eric Laurent874c42872014-08-08 15:13:39 -07002853
Eric Laurent6a94d692014-05-20 11:18:06 -07002854 // TODO: reconfigure output format and channels here
2855 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002856 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002857 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002858 index = mAudioPatches.indexOfKey(*handle);
2859 if (index >= 0) {
2860 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2861 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2862 }
2863 patchDesc = mAudioPatches.valueAt(index);
2864 patchDesc->mUid = uid;
2865 ALOGV("createAudioPatch() success");
2866 } else {
2867 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2868 return INVALID_OPERATION;
2869 }
2870 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2871 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2872 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002873 // only one sink supported when connecting an input device to a mix
2874 if (patch->num_sinks > 1) {
2875 return INVALID_OPERATION;
2876 }
François Gaffie53615e22015-03-19 09:24:12 +01002877 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002878 if (inputDesc == NULL) {
2879 return BAD_VALUE;
2880 }
2881 if (patchDesc != 0) {
2882 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2883 return BAD_VALUE;
2884 }
2885 }
2886 sp<DeviceDescriptor> devDesc =
2887 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2888 if (devDesc == 0) {
2889 return BAD_VALUE;
2890 }
2891
François Gaffie53615e22015-03-19 09:24:12 +01002892 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002893 devDesc->mAddress,
2894 patch->sinks[0].sample_rate,
2895 NULL, /*updatedSampleRate*/
2896 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002897 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002898 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002899 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002900 // FIXME for the parameter type,
2901 // and the NONE
2902 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002903 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002904 return INVALID_OPERATION;
2905 }
2906 // TODO: reconfigure output format and channels here
2907 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01002908 devDesc->type(), inputDesc->mIoHandle);
2909 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002910 index = mAudioPatches.indexOfKey(*handle);
2911 if (index >= 0) {
2912 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2913 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2914 }
2915 patchDesc = mAudioPatches.valueAt(index);
2916 patchDesc->mUid = uid;
2917 ALOGV("createAudioPatch() success");
2918 } else {
2919 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2920 return INVALID_OPERATION;
2921 }
2922 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2923 // device to device connection
2924 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002925 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002926 return BAD_VALUE;
2927 }
2928 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002929 sp<DeviceDescriptor> srcDeviceDesc =
2930 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002931 if (srcDeviceDesc == 0) {
2932 return BAD_VALUE;
2933 }
Eric Laurent874c42872014-08-08 15:13:39 -07002934
Eric Laurent6a94d692014-05-20 11:18:06 -07002935 //update source and sink with our own data as the data passed in the patch may
2936 // be incomplete.
2937 struct audio_patch newPatch = *patch;
2938 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002939
Eric Laurent874c42872014-08-08 15:13:39 -07002940 for (size_t i = 0; i < patch->num_sinks; i++) {
2941 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2942 ALOGV("createAudioPatch() source device but one sink is not a device");
2943 return INVALID_OPERATION;
2944 }
2945
2946 sp<DeviceDescriptor> sinkDeviceDesc =
2947 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2948 if (sinkDeviceDesc == 0) {
2949 return BAD_VALUE;
2950 }
2951 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2952
Eric Laurent3bcf8592015-04-03 12:13:24 -07002953 // create a software bridge in PatchPanel if:
2954 // - source and sink devices are on differnt HW modules OR
2955 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08002956 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07002957 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07002958 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07002959 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002960 return INVALID_OPERATION;
2961 }
Eric Laurent874c42872014-08-08 15:13:39 -07002962 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01002963 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07002964 // if the sink device is reachable via an opened output stream, request to go via
2965 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002966 audio_io_handle_t output = selectOutput(outputs,
2967 AUDIO_OUTPUT_FLAG_NONE,
2968 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002969 if (output != AUDIO_IO_HANDLE_NONE) {
2970 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2971 if (outputDesc->isDuplicated()) {
2972 return INVALID_OPERATION;
2973 }
2974 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07002975 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07002976 newPatch.num_sources = 2;
2977 }
Eric Laurent83b88082014-06-20 18:31:16 -07002978 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002979 }
2980 // TODO: check from routing capabilities in config file and other conflicting patches
2981
2982 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2983 if (index >= 0) {
2984 afPatchHandle = patchDesc->mAfPatchHandle;
2985 }
2986
2987 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2988 &afPatchHandle,
2989 0);
2990 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2991 status, afPatchHandle);
2992 if (status == NO_ERROR) {
2993 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01002994 patchDesc = new AudioPatch(&newPatch, uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002995 addAudioPatch(patchDesc->mHandle, patchDesc);
2996 } else {
2997 patchDesc->mPatch = newPatch;
2998 }
2999 patchDesc->mAfPatchHandle = afPatchHandle;
3000 *handle = patchDesc->mHandle;
3001 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003002 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003003 } else {
3004 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3005 status);
3006 return INVALID_OPERATION;
3007 }
3008 } else {
3009 return BAD_VALUE;
3010 }
3011 } else {
3012 return BAD_VALUE;
3013 }
3014 return NO_ERROR;
3015}
3016
3017status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3018 uid_t uid)
3019{
3020 ALOGV("releaseAudioPatch() patch %d", handle);
3021
3022 ssize_t index = mAudioPatches.indexOfKey(handle);
3023
3024 if (index < 0) {
3025 return BAD_VALUE;
3026 }
3027 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3028 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3029 mUidCached, patchDesc->mUid, uid);
3030 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3031 return INVALID_OPERATION;
3032 }
3033
3034 struct audio_patch *patch = &patchDesc->mPatch;
3035 patchDesc->mUid = mUidCached;
3036 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003037 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003038 if (outputDesc == NULL) {
3039 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3040 return BAD_VALUE;
3041 }
3042
Eric Laurentc75307b2015-03-17 15:29:32 -07003043 setOutputDevice(outputDesc,
3044 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07003045 true,
3046 0,
3047 NULL);
3048 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3049 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003050 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003051 if (inputDesc == NULL) {
3052 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3053 return BAD_VALUE;
3054 }
3055 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003056 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003057 true,
3058 NULL);
3059 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003060 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3061 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3062 status, patchDesc->mAfPatchHandle);
3063 removeAudioPatch(patchDesc->mHandle);
3064 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003065 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003066 } else {
3067 return BAD_VALUE;
3068 }
3069 } else {
3070 return BAD_VALUE;
3071 }
3072 return NO_ERROR;
3073}
3074
3075status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3076 struct audio_patch *patches,
3077 unsigned int *generation)
3078{
François Gaffie53615e22015-03-19 09:24:12 +01003079 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003080 return BAD_VALUE;
3081 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003082 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003083 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003084}
3085
Eric Laurente1715a42014-05-20 11:30:42 -07003086status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003087{
Eric Laurente1715a42014-05-20 11:30:42 -07003088 ALOGV("setAudioPortConfig()");
3089
3090 if (config == NULL) {
3091 return BAD_VALUE;
3092 }
3093 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3094 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003095 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3096 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003097 }
3098
Eric Laurenta121f902014-06-03 13:32:54 -07003099 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003100 if (config->type == AUDIO_PORT_TYPE_MIX) {
3101 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003102 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003103 if (outputDesc == NULL) {
3104 return BAD_VALUE;
3105 }
Eric Laurent84c70242014-06-23 08:46:27 -07003106 ALOG_ASSERT(!outputDesc->isDuplicated(),
3107 "setAudioPortConfig() called on duplicated output %d",
3108 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003109 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003110 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003111 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003112 if (inputDesc == NULL) {
3113 return BAD_VALUE;
3114 }
Eric Laurenta121f902014-06-03 13:32:54 -07003115 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003116 } else {
3117 return BAD_VALUE;
3118 }
3119 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3120 sp<DeviceDescriptor> deviceDesc;
3121 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3122 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3123 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3124 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3125 } else {
3126 return BAD_VALUE;
3127 }
3128 if (deviceDesc == NULL) {
3129 return BAD_VALUE;
3130 }
Eric Laurenta121f902014-06-03 13:32:54 -07003131 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003132 } else {
3133 return BAD_VALUE;
3134 }
3135
Eric Laurenta121f902014-06-03 13:32:54 -07003136 struct audio_port_config backupConfig;
3137 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3138 if (status == NO_ERROR) {
3139 struct audio_port_config newConfig;
3140 audioPortConfig->toAudioPortConfig(&newConfig, config);
3141 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003142 }
Eric Laurenta121f902014-06-03 13:32:54 -07003143 if (status != NO_ERROR) {
3144 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003145 }
Eric Laurente1715a42014-05-20 11:30:42 -07003146
3147 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003148}
3149
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003150void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3151{
Eric Laurentd60560a2015-04-10 11:31:20 -07003152 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003153 clearAudioPatches(uid);
3154 clearSessionRoutes(uid);
3155}
3156
Eric Laurent6a94d692014-05-20 11:18:06 -07003157void AudioPolicyManager::clearAudioPatches(uid_t uid)
3158{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003159 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003160 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3161 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003162 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003163 }
3164 }
3165}
3166
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003167void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3168 audio_io_handle_t ouptutToSkip)
3169{
3170 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3171 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3172 for (size_t j = 0; j < mOutputs.size(); j++) {
3173 if (mOutputs.keyAt(j) == ouptutToSkip) {
3174 continue;
3175 }
3176 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3177 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3178 continue;
3179 }
3180 // If the default device for this strategy is on another output mix,
3181 // invalidate all tracks in this strategy to force re connection.
3182 // Otherwise select new device on the output mix.
3183 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003184 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003185 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3186 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3187 }
3188 }
3189 } else {
3190 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3191 setOutputDevice(outputDesc, newDevice, false);
3192 }
3193 }
3194}
3195
3196void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3197{
3198 // remove output routes associated with this uid
3199 SortedVector<routing_strategy> affectedStrategies;
3200 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
3201 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
3202 if (route->mUid == uid) {
3203 mOutputRoutes.removeItemsAt(i);
3204 if (route->mDeviceDescriptor != 0) {
3205 affectedStrategies.add(getStrategy(route->mStreamType));
3206 }
3207 }
3208 }
3209 // reroute outputs if necessary
3210 for (size_t i = 0; i < affectedStrategies.size(); i++) {
3211 checkStrategyRoute(affectedStrategies[i], AUDIO_IO_HANDLE_NONE);
3212 }
3213
3214 // remove input routes associated with this uid
3215 SortedVector<audio_source_t> affectedSources;
3216 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
3217 sp<SessionRoute> route = mInputRoutes.valueAt(i);
3218 if (route->mUid == uid) {
3219 mInputRoutes.removeItemsAt(i);
3220 if (route->mDeviceDescriptor != 0) {
3221 affectedSources.add(route->mSource);
3222 }
3223 }
3224 }
3225 // reroute inputs if necessary
3226 SortedVector<audio_io_handle_t> inputsToClose;
3227 for (size_t i = 0; i < mInputs.size(); i++) {
3228 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003229 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003230 inputsToClose.add(inputDesc->mIoHandle);
3231 }
3232 }
3233 for (size_t i = 0; i < inputsToClose.size(); i++) {
3234 closeInput(inputsToClose[i]);
3235 }
3236}
3237
Eric Laurentd60560a2015-04-10 11:31:20 -07003238void AudioPolicyManager::clearAudioSources(uid_t uid)
3239{
3240 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
3241 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3242 if (sourceDesc->mUid == uid) {
3243 stopAudioSource(mAudioSources.keyAt(i));
3244 }
3245 }
3246}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003247
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003248status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3249 audio_io_handle_t *ioHandle,
3250 audio_devices_t *device)
3251{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003252 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3253 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003254 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003255
François Gaffiedf372692015-03-19 10:43:27 +01003256 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003257}
3258
Eric Laurentd60560a2015-04-10 11:31:20 -07003259status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
3260 const audio_attributes_t *attributes,
Glenn Kasten559d4392016-03-29 13:42:57 -07003261 audio_patch_handle_t *handle,
Eric Laurentd60560a2015-04-10 11:31:20 -07003262 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003263{
Eric Laurentd60560a2015-04-10 11:31:20 -07003264 ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle);
3265 if (source == NULL || attributes == NULL || handle == NULL) {
3266 return BAD_VALUE;
3267 }
3268
Glenn Kasten559d4392016-03-29 13:42:57 -07003269 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003270
3271 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3272 source->type != AUDIO_PORT_TYPE_DEVICE) {
3273 ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type);
3274 return INVALID_OPERATION;
3275 }
3276
3277 sp<DeviceDescriptor> srcDeviceDesc =
3278 mAvailableInputDevices.getDevice(source->ext.device.type,
3279 String8(source->ext.device.address));
3280 if (srcDeviceDesc == 0) {
3281 ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
3282 return BAD_VALUE;
3283 }
3284 sp<AudioSourceDescriptor> sourceDesc =
3285 new AudioSourceDescriptor(srcDeviceDesc, attributes, uid);
3286
3287 struct audio_patch dummyPatch;
3288 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
3289 sourceDesc->mPatchDesc = patchDesc;
3290
3291 status_t status = connectAudioSource(sourceDesc);
3292 if (status == NO_ERROR) {
3293 mAudioSources.add(sourceDesc->getHandle(), sourceDesc);
3294 *handle = sourceDesc->getHandle();
3295 }
3296 return status;
3297}
3298
3299status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3300{
3301 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3302
3303 // make sure we only have one patch per source.
3304 disconnectAudioSource(sourceDesc);
3305
3306 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
Eric Laurent28d09f02016-03-08 10:43:05 -08003307 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003308 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice;
3309
3310 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3311 sp<DeviceDescriptor> sinkDeviceDesc =
3312 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3313
3314 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3315 struct audio_patch *patch = &sourceDesc->mPatchDesc->mPatch;
3316
3317 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3318 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003319 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003320 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3321 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3322 // create patch between src device and output device
3323 // create Hwoutput and add to mHwOutputs
3324 } else {
3325 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3326 audio_io_handle_t output =
3327 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3328 if (output == AUDIO_IO_HANDLE_NONE) {
3329 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3330 return INVALID_OPERATION;
3331 }
3332 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3333 if (outputDesc->isDuplicated()) {
3334 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3335 return INVALID_OPERATION;
3336 }
3337 // create a special patch with no sink and two sources:
3338 // - the second source indicates to PatchPanel through which output mix this patch should
3339 // be connected as well as the stream type for volume control
3340 // - the sink is defined by whatever output device is currently selected for the output
3341 // though which this patch is routed.
3342 patch->num_sinks = 0;
3343 patch->num_sources = 2;
3344 srcDeviceDesc->toAudioPortConfig(&patch->sources[0], NULL);
3345 outputDesc->toAudioPortConfig(&patch->sources[1], NULL);
3346 patch->sources[1].ext.mix.usecase.stream = stream;
3347 status_t status = mpClientInterface->createAudioPatch(patch,
3348 &afPatchHandle,
3349 0);
3350 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3351 status, afPatchHandle);
3352 if (status != NO_ERROR) {
3353 ALOGW("%s patch panel could not connect device patch, error %d",
3354 __FUNCTION__, status);
3355 return INVALID_OPERATION;
3356 }
3357 uint32_t delayMs = 0;
Eric Laurentc40d9692016-04-13 19:14:13 -07003358 status = startSource(outputDesc, stream, sinkDevice, NULL, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003359
3360 if (status != NO_ERROR) {
3361 mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0);
3362 return status;
3363 }
3364 sourceDesc->mSwOutput = outputDesc;
3365 if (delayMs != 0) {
3366 usleep(delayMs * 1000);
3367 }
3368 }
3369
3370 sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle;
3371 addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc);
3372
3373 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003374}
3375
Glenn Kasten559d4392016-03-29 13:42:57 -07003376status_t AudioPolicyManager::stopAudioSource(audio_patch_handle_t handle __unused)
Eric Laurent554a2772015-04-10 11:29:24 -07003377{
Eric Laurentd60560a2015-04-10 11:31:20 -07003378 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle);
3379 ALOGV("%s handle %d", __FUNCTION__, handle);
3380 if (sourceDesc == 0) {
3381 ALOGW("%s unknown source for handle %d", __FUNCTION__, handle);
3382 return BAD_VALUE;
3383 }
3384 status_t status = disconnectAudioSource(sourceDesc);
3385
3386 mAudioSources.removeItem(handle);
3387 return status;
3388}
3389
Andy Hung2ddee192015-12-18 17:34:44 -08003390status_t AudioPolicyManager::setMasterMono(bool mono)
3391{
3392 if (mMasterMono == mono) {
3393 return NO_ERROR;
3394 }
3395 mMasterMono = mono;
3396 // if enabling mono we close all offloaded devices, which will invalidate the
3397 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3398 // for recreating the new AudioTrack as non-offloaded PCM.
3399 //
3400 // If disabling mono, we leave all tracks as is: we don't know which clients
3401 // and tracks are able to be recreated as offloaded. The next "song" should
3402 // play back offloaded.
3403 if (mMasterMono) {
3404 Vector<audio_io_handle_t> offloaded;
3405 for (size_t i = 0; i < mOutputs.size(); ++i) {
3406 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3407 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3408 offloaded.push(desc->mIoHandle);
3409 }
3410 }
3411 for (size_t i = 0; i < offloaded.size(); ++i) {
3412 closeOutput(offloaded[i]);
3413 }
3414 }
3415 // update master mono for all remaining outputs
3416 for (size_t i = 0; i < mOutputs.size(); ++i) {
3417 updateMono(mOutputs.keyAt(i));
3418 }
3419 return NO_ERROR;
3420}
3421
3422status_t AudioPolicyManager::getMasterMono(bool *mono)
3423{
3424 *mono = mMasterMono;
3425 return NO_ERROR;
3426}
3427
Eric Laurentac9cef52017-06-09 15:46:26 -07003428float AudioPolicyManager::getStreamVolumeDB(
3429 audio_stream_type_t stream, int index, audio_devices_t device)
3430{
3431 return computeVolume(stream, index, device);
3432}
3433
Eric Laurentd60560a2015-04-10 11:31:20 -07003434status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3435{
3436 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3437
3438 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle);
3439 if (patchDesc == 0) {
3440 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
3441 sourceDesc->mPatchDesc->mHandle);
3442 return BAD_VALUE;
3443 }
3444 removeAudioPatch(sourceDesc->mPatchDesc->mHandle);
3445
Eric Laurent28d09f02016-03-08 10:43:05 -08003446 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003447 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote();
3448 if (swOutputDesc != 0) {
3449 stopSource(swOutputDesc, stream, false);
3450 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3451 } else {
3452 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote();
3453 if (hwOutputDesc != 0) {
3454 // release patch between src device and output device
3455 // close Hwoutput and remove from mHwOutputs
3456 } else {
3457 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3458 }
3459 }
3460 return NO_ERROR;
3461}
3462
3463sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
3464 audio_io_handle_t output, routing_strategy strategy)
3465{
3466 sp<AudioSourceDescriptor> source;
3467 for (size_t i = 0; i < mAudioSources.size(); i++) {
3468 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3469 routing_strategy sourceStrategy =
3470 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
3471 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote();
3472 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3473 source = sourceDesc;
3474 break;
3475 }
3476 }
3477 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003478}
3479
Eric Laurente552edb2014-03-10 17:42:56 -07003480// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003481// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003482// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003483uint32_t AudioPolicyManager::nextAudioPortGeneration()
3484{
3485 return android_atomic_inc(&mAudioPortGeneration);
3486}
3487
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003488#ifdef USE_XML_AUDIO_POLICY_CONF
3489// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3490static const char *kConfigLocationList[] =
3491 {"/odm/etc", "/vendor/etc", "/system/etc"};
3492static const int kConfigLocationListSize =
3493 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3494
3495static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3496 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
3497 status_t ret;
3498
3499 for (int i = 0; i < kConfigLocationListSize; i++) {
3500 PolicySerializer serializer;
3501 snprintf(audioPolicyXmlConfigFile,
3502 sizeof(audioPolicyXmlConfigFile),
3503 "%s/%s",
3504 kConfigLocationList[i],
3505 AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3506 ret = serializer.deserialize(audioPolicyXmlConfigFile, config);
3507 if (ret == NO_ERROR) {
3508 break;
3509 }
3510 }
3511 return ret;
3512}
3513#endif
3514
Eric Laurente0720872014-03-11 09:30:41 -07003515AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07003516 :
Eric Laurente552edb2014-03-10 17:42:56 -07003517 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003518 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003519 mAudioPortGeneration(1),
3520 mBeaconMuteRefCount(0),
3521 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003522 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003523 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003524 mMasterMono(false),
Chris Thornton2b864642017-06-27 21:26:07 -07003525 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE),
3526 mHasComputedSoundTriggerSupportsConcurrentCapture(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003527{
François Gaffied1ab2bd2015-12-02 18:20:06 +01003528 mUidCached = getuid();
3529 mpClientInterface = clientInterface;
3530
3531 // TODO: remove when legacy conf file is removed. true on devices that use DRC on the
3532 // DEVICE_CATEGORY_SPEAKER path to boost soft sounds, used to adjust volume curves accordingly.
3533 // Note: remove also speaker_drc_enabled from global configuration of XML config file.
3534 bool speakerDrcEnabled = false;
3535
3536#ifdef USE_XML_AUDIO_POLICY_CONF
3537 mVolumeCurves = new VolumeCurvesCollection();
3538 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3539 mDefaultOutputDevice, speakerDrcEnabled,
3540 static_cast<VolumeCurvesCollection *>(mVolumeCurves));
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003541 if (deserializeAudioPolicyXmlConfig(config) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003542#else
3543 mVolumeCurves = new StreamDescriptorCollection();
3544 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3545 mDefaultOutputDevice, speakerDrcEnabled);
3546 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, config) != NO_ERROR) &&
3547 (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, config) != NO_ERROR)) {
3548#endif
3549 ALOGE("could not load audio policy configuration file, setting defaults");
3550 config.setDefault();
3551 }
3552 // must be done after reading the policy (since conditionned by Speaker Drc Enabling)
3553 mVolumeCurves->initializeVolumeCurves(speakerDrcEnabled);
3554
3555 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003556 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3557 if (!engineInstance) {
3558 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
3559 return;
3560 }
3561 // Retrieve the Policy Manager Interface
3562 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3563 if (mEngine == NULL) {
3564 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
3565 return;
3566 }
3567 mEngine->setObserver(this);
3568 status_t status = mEngine->initCheck();
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07003569 (void) status;
François Gaffie2110e042015-03-24 08:41:51 +01003570 ALOG_ASSERT(status == NO_ERROR, "Policy engine not initialized(err=%d)", status);
3571
Eric Laurent3a4311c2014-03-17 12:00:47 -07003572 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003573 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003574 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3575 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003576 for (size_t i = 0; i < mHwModules.size(); i++) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003577 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003578 if (mHwModules[i]->mHandle == 0) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003579 ALOGW("could not open HW module %s", mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003580 continue;
3581 }
3582 // open all output streams needed to access attached devices
3583 // except for direct output streams that are only opened when they are actually
3584 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003585 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07003586 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3587 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003588 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003589
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003590 if (!outProfile->hasSupportedDevices()) {
3591 ALOGW("Output profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003592 continue;
3593 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003594 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003595 mTtsOutputAvailable = true;
3596 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003597
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003598 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003599 continue;
3600 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003601 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003602 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3603 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003604 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003605 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003606 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003607 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003608 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003609 if ((profileType & outputDeviceTypes) == 0) {
3610 continue;
3611 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003612 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3613 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003614 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
3615 const DeviceVector &devicesForType = supportedDevices.getDevicesFromType(profileType);
3616 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3617 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003618
3619 outputDesc->mDevice = profileType;
3620 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3621 config.sample_rate = outputDesc->mSamplingRate;
3622 config.channel_mask = outputDesc->mChannelMask;
3623 config.format = outputDesc->mFormat;
3624 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003625 status_t status = mpClientInterface->openOutput(outProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003626 &output,
3627 &config,
3628 &outputDesc->mDevice,
Eric Laurentc40d9692016-04-13 19:14:13 -07003629 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003630 &outputDesc->mLatency,
3631 outputDesc->mFlags);
3632
3633 if (status != NO_ERROR) {
3634 ALOGW("Cannot open output stream for device %08x on hw module %s",
3635 outputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003636 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003637 } else {
3638 outputDesc->mSamplingRate = config.sample_rate;
3639 outputDesc->mChannelMask = config.channel_mask;
3640 outputDesc->mFormat = config.format;
3641
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003642 for (size_t k = 0; k < supportedDevices.size(); k++) {
3643 ssize_t index = mAvailableOutputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003644 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003645 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
3646 mAvailableOutputDevices[index]->attach(mHwModules[i]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003647 }
3648 }
3649 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003650 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003651 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003652 }
3653 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003654 setOutputDevice(outputDesc,
Eric Laurentd78f1532014-09-16 16:38:20 -07003655 outputDesc->mDevice,
Eric Laurentc40d9692016-04-13 19:14:13 -07003656 true,
3657 0,
3658 NULL,
3659 address.string());
Eric Laurentd78f1532014-09-16 16:38:20 -07003660 }
Eric Laurente552edb2014-03-10 17:42:56 -07003661 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003662 // open input streams needed to access attached devices to validate
3663 // mAvailableInputDevices list
3664 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3665 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003666 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003667
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003668 if (!inProfile->hasSupportedDevices()) {
3669 ALOGW("Input profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003670 continue;
3671 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003672 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003673 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003674 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
3675
Eric Laurentd78f1532014-09-16 16:38:20 -07003676 if ((profileType & inputDeviceTypes) == 0) {
3677 continue;
3678 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08003679 sp<AudioInputDescriptor> inputDesc =
3680 new AudioInputDescriptor(inProfile);
Eric Laurentd78f1532014-09-16 16:38:20 -07003681
Eric Laurentd78f1532014-09-16 16:38:20 -07003682 inputDesc->mDevice = profileType;
3683
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003684 // find the address
3685 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
3686 // the inputs vector must be of size 1, but we don't want to crash here
3687 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3688 : String8("");
3689 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
3690 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
3691
Eric Laurentd78f1532014-09-16 16:38:20 -07003692 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3693 config.sample_rate = inputDesc->mSamplingRate;
3694 config.channel_mask = inputDesc->mChannelMask;
3695 config.format = inputDesc->mFormat;
3696 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003697 status_t status = mpClientInterface->openInput(inProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003698 &input,
3699 &config,
3700 &inputDesc->mDevice,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003701 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003702 AUDIO_SOURCE_MIC,
3703 AUDIO_INPUT_FLAG_NONE);
3704
3705 if (status == NO_ERROR) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003706 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
3707 for (size_t k = 0; k < supportedDevices.size(); k++) {
3708 ssize_t index = mAvailableInputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003709 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07003710 if (index >= 0) {
3711 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
3712 if (!devDesc->isAttached()) {
3713 devDesc->attach(mHwModules[i]);
Eric Laurent83efe1c2017-07-09 16:51:08 -07003714 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07003715 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003716 }
3717 }
3718 mpClientInterface->closeInput(input);
3719 } else {
3720 ALOGW("Cannot open input stream for device %08x on hw module %s",
3721 inputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003722 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003723 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003724 }
3725 }
3726 // make sure all attached devices have been allocated a unique ID
3727 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003728 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003729 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003730 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
3731 continue;
3732 }
François Gaffie2110e042015-03-24 08:41:51 +01003733 // The device is now validated and can be appended to the available devices of the engine
3734 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
3735 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003736 i++;
3737 }
3738 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003739 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01003740 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003741 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
3742 continue;
3743 }
François Gaffie2110e042015-03-24 08:41:51 +01003744 // The device is now validated and can be appended to the available devices of the engine
3745 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
3746 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003747 i++;
3748 }
3749 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003750 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01003751 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003752 }
Eric Laurente552edb2014-03-10 17:42:56 -07003753
3754 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
3755
3756 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -07003757}
3758
Eric Laurente0720872014-03-11 09:30:41 -07003759AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07003760{
Eric Laurente552edb2014-03-10 17:42:56 -07003761 for (size_t i = 0; i < mOutputs.size(); i++) {
3762 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003763 }
3764 for (size_t i = 0; i < mInputs.size(); i++) {
3765 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003766 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003767 mAvailableOutputDevices.clear();
3768 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003769 mOutputs.clear();
3770 mInputs.clear();
3771 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07003772}
3773
Eric Laurente0720872014-03-11 09:30:41 -07003774status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07003775{
Eric Laurent87ffa392015-05-22 10:32:38 -07003776 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003777}
3778
Eric Laurente552edb2014-03-10 17:42:56 -07003779// ---
3780
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003781void AudioPolicyManager::addOutput(audio_io_handle_t output, const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003782{
François Gaffie98cc1912015-03-18 17:52:40 +01003783 outputDesc->setIoHandle(output);
Eric Laurent1c333e22014-05-20 10:48:17 -07003784 mOutputs.add(output, outputDesc);
Andy Hung2ddee192015-12-18 17:34:44 -08003785 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07003786 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07003787 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003788}
3789
François Gaffie53615e22015-03-19 09:24:12 +01003790void AudioPolicyManager::removeOutput(audio_io_handle_t output)
3791{
3792 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07003793 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01003794}
3795
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003796void AudioPolicyManager::addInput(audio_io_handle_t input, const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003797{
François Gaffie98cc1912015-03-18 17:52:40 +01003798 inputDesc->setIoHandle(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07003799 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003800 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003801}
Eric Laurente552edb2014-03-10 17:42:56 -07003802
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003803void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08003804 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003805 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003806 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08003807 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003808 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08003809 if (devDesc != 0) {
3810 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
3811 desc->mIoHandle, address.string());
3812 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003813 }
3814}
3815
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003816status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01003817 audio_policy_dev_state_t state,
3818 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003819 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07003820{
François Gaffie53615e22015-03-19 09:24:12 +01003821 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07003822 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07003823
3824 if (audio_device_is_digital(device)) {
3825 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08003826 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07003827 }
Eric Laurente552edb2014-03-10 17:42:56 -07003828
Eric Laurent3b73df72014-03-11 09:06:29 -07003829 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003830 // first list already open outputs that can be routed to this device
3831 for (size_t i = 0; i < mOutputs.size(); i++) {
3832 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07003833 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003834 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003835 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3836 outputs.add(mOutputs.keyAt(i));
3837 } else {
3838 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08003839 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003840 }
Eric Laurente552edb2014-03-10 17:42:56 -07003841 }
3842 }
3843 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003844 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003845 for (size_t i = 0; i < mHwModules.size(); i++)
3846 {
3847 if (mHwModules[i]->mHandle == 0) {
3848 continue;
3849 }
3850 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3851 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003852 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003853 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003854 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003855 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003856 profiles.add(profile);
3857 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
3858 }
Eric Laurente552edb2014-03-10 17:42:56 -07003859 }
3860 }
3861 }
3862
Eric Laurent7b279bb2015-12-14 10:18:23 -08003863 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003864
Eric Laurente552edb2014-03-10 17:42:56 -07003865 if (profiles.isEmpty() && outputs.isEmpty()) {
3866 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3867 return BAD_VALUE;
3868 }
3869
3870 // open outputs for matching profiles if needed. Direct outputs are also opened to
3871 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3872 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003873 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003874
3875 // nothing to do if one output is already opened for this profile
3876 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003877 for (j = 0; j < outputs.size(); j++) {
3878 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003879 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003880 // matching profile: save the sample rates, format and channel masks supported
3881 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07003882 if (audio_device_is_digital(device)) {
3883 devDesc->importAudioPort(profile);
3884 }
Eric Laurente552edb2014-03-10 17:42:56 -07003885 break;
3886 }
3887 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003888 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003889 continue;
3890 }
3891
Eric Laurent83efe1c2017-07-09 16:51:08 -07003892 ALOGV("opening output for device %08x with params %s profile %p name %s",
3893 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07003894 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07003895 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003896 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3897 config.sample_rate = desc->mSamplingRate;
3898 config.channel_mask = desc->mChannelMask;
3899 config.format = desc->mFormat;
3900 config.offload_info.sample_rate = desc->mSamplingRate;
3901 config.offload_info.channel_mask = desc->mChannelMask;
3902 config.offload_info.format = desc->mFormat;
3903 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003904 status_t status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003905 &output,
3906 &config,
3907 &desc->mDevice,
3908 address,
3909 &desc->mLatency,
3910 desc->mFlags);
3911 if (status == NO_ERROR) {
3912 desc->mSamplingRate = config.sample_rate;
3913 desc->mChannelMask = config.channel_mask;
3914 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003915
Eric Laurentd4692962014-05-05 18:13:44 -07003916 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003917 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003918 char *param = audio_device_address_to_parameter(device, address);
3919 mpClientInterface->setParameters(output, String8(param));
3920 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003921 }
Phil Burk00eeb322016-03-31 12:41:00 -07003922 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01003923 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003924 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003925 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003926 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01003927 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07003928 mpClientInterface->closeOutput(output);
Phil Burk702b1052016-03-02 16:38:26 -08003929 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01003930 profile->pickAudioProfile(config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003931 config.offload_info.sample_rate = config.sample_rate;
3932 config.offload_info.channel_mask = config.channel_mask;
3933 config.offload_info.format = config.format;
Eric Laurent322b4d22015-04-03 15:57:54 -07003934 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003935 &output,
3936 &config,
3937 &desc->mDevice,
3938 address,
3939 &desc->mLatency,
3940 desc->mFlags);
3941 if (status == NO_ERROR) {
3942 desc->mSamplingRate = config.sample_rate;
3943 desc->mChannelMask = config.channel_mask;
3944 desc->mFormat = config.format;
3945 } else {
3946 output = AUDIO_IO_HANDLE_NONE;
3947 }
Eric Laurentd4692962014-05-05 18:13:44 -07003948 }
3949
Eric Laurentcf2c0212014-07-25 16:20:43 -07003950 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003951 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01003952 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01003953 sp<AudioPolicyMix> policyMix;
3954 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003955 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
3956 address.string());
3957 }
François Gaffie036e1e92015-03-19 10:16:24 +01003958 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07003959 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01003960
Eric Laurent87ffa392015-05-22 10:32:38 -07003961 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
3962 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08003963 // no duplicated output for direct outputs and
3964 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07003965 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003966
Eric Laurentd4692962014-05-05 18:13:44 -07003967 // set initial stream volume for device
Eric Laurentc75307b2015-03-17 15:29:32 -07003968 applyStreamVolumes(desc, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003969
Eric Laurentd4692962014-05-05 18:13:44 -07003970 //TODO: configure audio effect output stage here
3971
3972 // open a duplicating output thread for the new output and the primary output
Eric Laurentc75307b2015-03-17 15:29:32 -07003973 duplicatedOutput =
3974 mpClientInterface->openDuplicateOutput(output,
3975 mPrimaryOutput->mIoHandle);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003976 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003977 // add duplicated output descriptor
Eric Laurentc75307b2015-03-17 15:29:32 -07003978 sp<SwAudioOutputDescriptor> dupOutputDesc =
3979 new SwAudioOutputDescriptor(NULL, mpClientInterface);
3980 dupOutputDesc->mOutput1 = mPrimaryOutput;
3981 dupOutputDesc->mOutput2 = desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003982 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3983 dupOutputDesc->mFormat = desc->mFormat;
3984 dupOutputDesc->mChannelMask = desc->mChannelMask;
3985 dupOutputDesc->mLatency = desc->mLatency;
3986 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003987 applyStreamVolumes(dupOutputDesc, device, 0, true);
Eric Laurentd4692962014-05-05 18:13:44 -07003988 } else {
3989 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07003990 mPrimaryOutput->mIoHandle, output);
Eric Laurentd4692962014-05-05 18:13:44 -07003991 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01003992 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003993 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003994 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003995 }
Eric Laurente552edb2014-03-10 17:42:56 -07003996 }
3997 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003998 } else {
3999 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004000 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004001 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004002 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004003 profiles.removeAt(profile_index);
4004 profile_index--;
4005 } else {
4006 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004007 // Load digital format info only for digital devices
4008 if (audio_device_is_digital(device)) {
4009 devDesc->importAudioPort(profile);
4010 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004011
François Gaffie53615e22015-03-19 09:24:12 +01004012 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004013 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4014 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004015 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004016 NULL/*patch handle*/, address.string());
4017 }
Eric Laurente552edb2014-03-10 17:42:56 -07004018 ALOGV("checkOutputsForDevice(): adding output %d", output);
4019 }
4020 }
4021
4022 if (profiles.isEmpty()) {
4023 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4024 return BAD_VALUE;
4025 }
Eric Laurentd4692962014-05-05 18:13:44 -07004026 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004027 // check if one opened output is not needed any more after disconnecting one device
4028 for (size_t i = 0; i < mOutputs.size(); i++) {
4029 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004030 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004031 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004032 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004033 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004034 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004035 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004036 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4037 mOutputs.keyAt(i));
4038 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004039 }
Eric Laurente552edb2014-03-10 17:42:56 -07004040 }
4041 }
Eric Laurentd4692962014-05-05 18:13:44 -07004042 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07004043 for (size_t i = 0; i < mHwModules.size(); i++)
4044 {
4045 if (mHwModules[i]->mHandle == 0) {
4046 continue;
4047 }
4048 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
4049 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004050 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004051 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004052 ALOGV("checkOutputsForDevice(): "
4053 "clearing direct output profile %zu on module %zu", j, i);
François Gaffie112b0af2015-11-19 16:13:25 +01004054 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004055 }
4056 }
4057 }
4058 }
4059 return NO_ERROR;
4060}
4061
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004062status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004063 audio_policy_dev_state_t state,
4064 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004065 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004066{
Paul McLean9080a4c2015-06-18 08:24:02 -07004067 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004068 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004069
4070 if (audio_device_is_digital(device)) {
4071 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004072 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004073 }
4074
Eric Laurentd4692962014-05-05 18:13:44 -07004075 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4076 // first list already open inputs that can be routed to this device
4077 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4078 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004079 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004080 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4081 inputs.add(mInputs.keyAt(input_index));
4082 }
4083 }
4084
4085 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004086 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07004087 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
4088 {
4089 if (mHwModules[module_idx]->mHandle == 0) {
4090 continue;
4091 }
4092 for (size_t profile_index = 0;
4093 profile_index < mHwModules[module_idx]->mInputProfiles.size();
4094 profile_index++)
4095 {
Eric Laurent275e8e92014-11-30 15:14:47 -08004096 sp<IOProfile> profile = mHwModules[module_idx]->mInputProfiles[profile_index];
4097
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004098 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004099 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004100 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004101 profiles.add(profile);
4102 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
4103 profile_index, module_idx);
4104 }
Eric Laurentd4692962014-05-05 18:13:44 -07004105 }
4106 }
4107 }
4108
4109 if (profiles.isEmpty() && inputs.isEmpty()) {
4110 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4111 return BAD_VALUE;
4112 }
4113
4114 // open inputs for matching profiles if needed. Direct inputs are also opened to
4115 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4116 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4117
Eric Laurent1c333e22014-05-20 10:48:17 -07004118 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07004119 // nothing to do if one input is already opened for this profile
4120 size_t input_index;
4121 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4122 desc = mInputs.valueAt(input_index);
4123 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004124 if (audio_device_is_digital(device)) {
4125 devDesc->importAudioPort(profile);
4126 }
Eric Laurentd4692962014-05-05 18:13:44 -07004127 break;
4128 }
4129 }
4130 if (input_index != mInputs.size()) {
4131 continue;
4132 }
4133
4134 ALOGV("opening input for device 0x%X with params %s", device, address.string());
4135 desc = new AudioInputDescriptor(profile);
4136 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07004137 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4138 config.sample_rate = desc->mSamplingRate;
4139 config.channel_mask = desc->mChannelMask;
4140 config.format = desc->mFormat;
4141 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent83efe1c2017-07-09 16:51:08 -07004142
4143 ALOGV("opening inputput for device %08x with params %s profile %p name %s",
4144 desc->mDevice, address.string(), profile.get(), profile->getName().string());
4145
Eric Laurent322b4d22015-04-03 15:57:54 -07004146 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07004147 &input,
4148 &config,
4149 &desc->mDevice,
4150 address,
4151 AUDIO_SOURCE_MIC,
4152 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07004153
Eric Laurentcf2c0212014-07-25 16:20:43 -07004154 if (status == NO_ERROR) {
4155 desc->mSamplingRate = config.sample_rate;
4156 desc->mChannelMask = config.channel_mask;
4157 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07004158
Eric Laurentd4692962014-05-05 18:13:44 -07004159 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004160 char *param = audio_device_address_to_parameter(device, address);
4161 mpClientInterface->setParameters(input, String8(param));
4162 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004163 }
Phil Burk00eeb322016-03-31 12:41:00 -07004164 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004165 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004166 ALOGW("checkInputsForDevice() direct input missing param");
4167 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004168 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004169 }
4170
4171 if (input != 0) {
4172 addInput(input, desc);
4173 }
4174 } // endif input != 0
4175
Eric Laurentcf2c0212014-07-25 16:20:43 -07004176 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004177 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004178 profiles.removeAt(profile_index);
4179 profile_index--;
4180 } else {
4181 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004182 if (audio_device_is_digital(device)) {
4183 devDesc->importAudioPort(profile);
4184 }
Eric Laurentd4692962014-05-05 18:13:44 -07004185 ALOGV("checkInputsForDevice(): adding input %d", input);
4186 }
4187 } // end scan profiles
4188
4189 if (profiles.isEmpty()) {
4190 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4191 return BAD_VALUE;
4192 }
4193 } else {
4194 // Disconnect
4195 // check if one opened input is not needed any more after disconnecting one device
4196 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4197 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004198 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004199 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4200 mInputs.keyAt(input_index));
4201 inputs.add(mInputs.keyAt(input_index));
4202 }
4203 }
4204 // Clear any profiles associated with the disconnected device.
4205 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
4206 if (mHwModules[module_index]->mHandle == 0) {
4207 continue;
4208 }
4209 for (size_t profile_index = 0;
4210 profile_index < mHwModules[module_index]->mInputProfiles.size();
4211 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004212 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004213 if (profile->supportDevice(device)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004214 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07004215 profile_index, module_index);
François Gaffie112b0af2015-11-19 16:13:25 +01004216 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004217 }
4218 }
4219 }
4220 } // end disconnect
4221
4222 return NO_ERROR;
4223}
4224
4225
Eric Laurente0720872014-03-11 09:30:41 -07004226void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004227{
4228 ALOGV("closeOutput(%d)", output);
4229
Eric Laurentc75307b2015-03-17 15:29:32 -07004230 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004231 if (outputDesc == NULL) {
4232 ALOGW("closeOutput() unknown output %d", output);
4233 return;
4234 }
François Gaffie036e1e92015-03-19 10:16:24 +01004235 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004236
Eric Laurente552edb2014-03-10 17:42:56 -07004237 // look for duplicated outputs connected to the output being removed.
4238 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004239 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004240 if (dupOutputDesc->isDuplicated() &&
4241 (dupOutputDesc->mOutput1 == outputDesc ||
4242 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004243 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004244 if (dupOutputDesc->mOutput1 == outputDesc) {
4245 outputDesc2 = dupOutputDesc->mOutput2;
4246 } else {
4247 outputDesc2 = dupOutputDesc->mOutput1;
4248 }
4249 // As all active tracks on duplicated output will be deleted,
4250 // and as they were also referenced on the other output, the reference
4251 // count for their stream type must be adjusted accordingly on
4252 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07004253 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004254 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07004255 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004256 }
4257 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4258 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4259
4260 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004261 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004262 }
4263 }
4264
Eric Laurent05b90f82014-08-27 15:32:29 -07004265 nextAudioPortGeneration();
4266
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004267 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004268 if (index >= 0) {
4269 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004270 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004271 mAudioPatches.removeItemsAt(index);
4272 mpClientInterface->onAudioPatchListUpdate();
4273 }
4274
Eric Laurente552edb2014-03-10 17:42:56 -07004275 AudioParameter param;
4276 param.add(String8("closing"), String8("true"));
4277 mpClientInterface->setParameters(output, param.toString());
4278
4279 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01004280 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004281 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004282}
4283
4284void AudioPolicyManager::closeInput(audio_io_handle_t input)
4285{
4286 ALOGV("closeInput(%d)", input);
4287
4288 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4289 if (inputDesc == NULL) {
4290 ALOGW("closeInput() unknown input %d", input);
4291 return;
4292 }
4293
Eric Laurent6a94d692014-05-20 11:18:06 -07004294 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004295
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004296 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004297 if (index >= 0) {
4298 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004299 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004300 mAudioPatches.removeItemsAt(index);
4301 mpClientInterface->onAudioPatchListUpdate();
4302 }
4303
4304 mpClientInterface->closeInput(input);
4305 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004306}
4307
Eric Laurentc75307b2015-03-17 15:29:32 -07004308SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4309 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004310 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004311{
4312 SortedVector<audio_io_handle_t> outputs;
4313
4314 ALOGVV("getOutputsForDevice() device %04x", device);
4315 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004316 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004317 i, openOutputs.valueAt(i)->isDuplicated(),
4318 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004319 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4320 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4321 outputs.add(openOutputs.keyAt(i));
4322 }
4323 }
4324 return outputs;
4325}
4326
Eric Laurente0720872014-03-11 09:30:41 -07004327bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
François Gaffie53615e22015-03-19 09:24:12 +01004328 SortedVector<audio_io_handle_t>& outputs2)
Eric Laurente552edb2014-03-10 17:42:56 -07004329{
4330 if (outputs1.size() != outputs2.size()) {
4331 return false;
4332 }
4333 for (size_t i = 0; i < outputs1.size(); i++) {
4334 if (outputs1[i] != outputs2[i]) {
4335 return false;
4336 }
4337 }
4338 return true;
4339}
4340
Eric Laurente0720872014-03-11 09:30:41 -07004341void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004342{
4343 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4344 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4345 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4346 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4347
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004348 // also take into account external policy-related changes: add all outputs which are
4349 // associated with policies in the "before" and "after" output vectors
4350 ALOGVV("checkOutputForStrategy(): policy related outputs");
4351 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004352 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004353 if (desc != 0 && desc->mPolicyMix != NULL) {
4354 srcOutputs.add(desc->mIoHandle);
4355 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4356 }
4357 }
4358 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004359 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004360 if (desc != 0 && desc->mPolicyMix != NULL) {
4361 dstOutputs.add(desc->mIoHandle);
4362 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4363 }
4364 }
4365
Eric Laurente552edb2014-03-10 17:42:56 -07004366 if (!vectorsEqual(srcOutputs,dstOutputs)) {
4367 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4368 strategy, srcOutputs[0], dstOutputs[0]);
4369 // mute strategy while moving tracks from one output to another
4370 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004371 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
François Gaffiead3183e2015-03-18 16:55:35 +01004372 if (isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004373 setStrategyMute(strategy, true, desc);
4374 setStrategyMute(strategy, false, desc, MUTE_TIME_MS, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004375 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004376 sp<AudioSourceDescriptor> source =
4377 getSourceForStrategyOnOutput(srcOutputs[i], strategy);
4378 if (source != 0){
4379 connectAudioSource(source);
4380 }
Eric Laurente552edb2014-03-10 17:42:56 -07004381 }
4382
4383 // Move effects associated to this strategy from previous output to new output
4384 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004385 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004386 }
4387 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004388 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004389 if (getStrategy((audio_stream_type_t)i) == strategy) {
4390 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004391 }
4392 }
4393 }
4394}
4395
Eric Laurente0720872014-03-11 09:30:41 -07004396void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004397{
François Gaffie2110e042015-03-24 08:41:51 +01004398 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004399 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004400 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004401 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004402 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004403 checkOutputForStrategy(STRATEGY_SONIFICATION);
4404 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004405 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004406 checkOutputForStrategy(STRATEGY_MEDIA);
4407 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004408 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004409}
4410
Eric Laurente0720872014-03-11 09:30:41 -07004411void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004412{
François Gaffie53615e22015-03-19 09:24:12 +01004413 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Eric Laurente552edb2014-03-10 17:42:56 -07004414 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004415 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004416 return;
4417 }
4418
Eric Laurent3a4311c2014-03-17 12:00:47 -07004419 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004420 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4421 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4422 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004423
4424 // if suspended, restore A2DP output if:
4425 // ((SCO device is NOT connected) ||
4426 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4427 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004428 //
Eric Laurentf732e072016-08-03 19:30:28 -07004429 // if not suspended, suspend A2DP output if:
4430 // (SCO device is connected) &&
4431 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4432 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004433 //
4434 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004435 if (!isScoConnected ||
4436 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4437 AUDIO_POLICY_FORCE_BT_SCO) &&
4438 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4439 AUDIO_POLICY_FORCE_BT_SCO) &&
4440 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004441 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004442
4443 mpClientInterface->restoreOutput(a2dpOutput);
4444 mA2dpSuspended = false;
4445 }
4446 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004447 if (isScoConnected &&
4448 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4449 AUDIO_POLICY_FORCE_BT_SCO) ||
4450 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4451 AUDIO_POLICY_FORCE_BT_SCO) ||
4452 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004453 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004454
4455 mpClientInterface->suspendOutput(a2dpOutput);
4456 mA2dpSuspended = true;
4457 }
4458 }
4459}
4460
Eric Laurentc75307b2015-03-17 15:29:32 -07004461audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4462 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004463{
4464 audio_devices_t device = AUDIO_DEVICE_NONE;
4465
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004466 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004467 if (index >= 0) {
4468 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4469 if (patchDesc->mUid != mUidCached) {
4470 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004471 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004472 return outputDesc->device();
4473 }
4474 }
4475
Eric Laurente552edb2014-03-10 17:42:56 -07004476 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004477 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004478 // use device for strategy enforced audible
4479 // 2: we are in call or the strategy phone is active on the output:
4480 // use device for strategy phone
Jon Eklund966095e2014-09-09 15:39:49 -05004481 // 3: the strategy for enforced audible is active but not enforced on the output:
4482 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004483 // 4: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004484 // use device for strategy sonification
Eric Laurent28d09f02016-03-08 10:43:05 -08004485 // 5: the strategy accessibility is active on the output:
4486 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004487 // 6: the strategy "respectful" sonification is active on the output:
4488 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004489 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004490 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004491 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004492 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004493 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004494 // use device for strategy t-t-s
François Gaffiead3183e2015-03-18 16:55:35 +01004495 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004496 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004497 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4498 } else if (isInCall() ||
François Gaffiead3183e2015-03-18 16:55:35 +01004499 isStrategyActive(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004500 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004501 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
Jon Eklund966095e2014-09-09 15:39:49 -05004502 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004503 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004504 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004505 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4506 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004507 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004508 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004509 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004510 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004511 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004512 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004513 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004514 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004515 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004516 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004517 }
4518
Eric Laurent1c333e22014-05-20 10:48:17 -07004519 ALOGV("getNewOutputDevice() selected device %x", device);
4520 return device;
4521}
4522
Eric Laurentfb66dd92016-01-28 18:32:03 -08004523audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004524{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004525 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004526
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004527 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004528 if (index >= 0) {
4529 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4530 if (patchDesc->mUid != mUidCached) {
4531 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004532 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004533 return inputDesc->mDevice;
4534 }
4535 }
4536
Eric Laurentfb66dd92016-01-28 18:32:03 -08004537 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
4538 if (isInCall()) {
4539 device = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
4540 } else if (source != AUDIO_SOURCE_DEFAULT) {
4541 device = getDeviceAndMixForInputSource(source);
4542 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004543
Eric Laurente552edb2014-03-10 17:42:56 -07004544 return device;
4545}
4546
Eric Laurent794fde22016-03-11 09:50:45 -08004547bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4548 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004549 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004550}
4551
Eric Laurente0720872014-03-11 09:30:41 -07004552uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004553 return (uint32_t)getStrategy(stream);
4554}
4555
Eric Laurente0720872014-03-11 09:30:41 -07004556audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004557 // By checking the range of stream before calling getStrategy, we avoid
4558 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4559 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004560 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004561 return AUDIO_DEVICE_NONE;
4562 }
Eric Laurent28d09f02016-03-08 10:43:05 -08004563 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004564 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4565 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004566 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004567 }
Eric Laurent794fde22016-03-11 09:50:45 -08004568 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004569 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004570 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Eric Laurent28d09f02016-03-08 10:43:05 -08004571 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(curDevices, mOutputs);
4572 for (size_t i = 0; i < outputs.size(); i++) {
4573 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent794fde22016-03-11 09:50:45 -08004574 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004575 curDevices |= outputDesc->device();
4576 }
4577 }
4578 devices |= curDevices;
Eric Laurente552edb2014-03-10 17:42:56 -07004579 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004580
4581 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4582 and doesn't really need to.*/
4583 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4584 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4585 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4586 }
Eric Laurente552edb2014-03-10 17:42:56 -07004587 return devices;
4588}
4589
François Gaffie2110e042015-03-24 08:41:51 +01004590routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4591{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004592 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004593 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004594}
4595
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004596uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4597 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004598 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4599 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4600 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004601 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4602 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4603 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004604 // usage to strategy mapping
François Gaffie2110e042015-03-24 08:41:51 +01004605 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004606}
4607
Eric Laurente0720872014-03-11 09:30:41 -07004608void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004609 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004610 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004611 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4612 updateDevicesAndOutputs();
4613 break;
4614 default:
4615 break;
4616 }
4617}
4618
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004619uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004620
4621 // skip beacon mute management if a dedicated TTS output is available
4622 if (mTtsOutputAvailable) {
4623 return 0;
4624 }
4625
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004626 switch(event) {
4627 case STARTING_OUTPUT:
4628 mBeaconMuteRefCount++;
4629 break;
4630 case STOPPING_OUTPUT:
4631 if (mBeaconMuteRefCount > 0) {
4632 mBeaconMuteRefCount--;
4633 }
4634 break;
4635 case STARTING_BEACON:
4636 mBeaconPlayingRefCount++;
4637 break;
4638 case STOPPING_BEACON:
4639 if (mBeaconPlayingRefCount > 0) {
4640 mBeaconPlayingRefCount--;
4641 }
4642 break;
4643 }
4644
4645 if (mBeaconMuteRefCount > 0) {
4646 // any playback causes beacon to be muted
4647 return setBeaconMute(true);
4648 } else {
4649 // no other playback: unmute when beacon starts playing, mute when it stops
4650 return setBeaconMute(mBeaconPlayingRefCount == 0);
4651 }
4652}
4653
4654uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4655 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4656 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4657 // keep track of muted state to avoid repeating mute/unmute operations
4658 if (mBeaconMuted != mute) {
4659 // mute/unmute AUDIO_STREAM_TTS on all outputs
4660 ALOGV("\t muting %d", mute);
4661 uint32_t maxLatency = 0;
4662 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004663 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004664 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07004665 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004666 0 /*delay*/, AUDIO_DEVICE_NONE);
4667 const uint32_t latency = desc->latency() * 2;
4668 if (latency > maxLatency) {
4669 maxLatency = latency;
4670 }
4671 }
4672 mBeaconMuted = mute;
4673 return maxLatency;
4674 }
4675 return 0;
4676}
4677
Eric Laurente0720872014-03-11 09:30:41 -07004678audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01004679 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004680{
Paul McLeanaa981192015-03-21 09:55:15 -07004681 // Routing
4682 // see if we have an explicit route
4683 // scan the whole RouteMap, for each entry, convert the stream type to a strategy
4684 // (getStrategy(stream)).
4685 // if the strategy from the stream type in the RouteMap is the same as the argument above,
4686 // and activity count is non-zero
4687 // the device = the device from the descriptor in the RouteMap, and exit.
4688 for (size_t routeIndex = 0; routeIndex < mOutputRoutes.size(); routeIndex++) {
4689 sp<SessionRoute> route = mOutputRoutes.valueAt(routeIndex);
Eric Laurent28d09f02016-03-08 10:43:05 -08004690 routing_strategy routeStrategy = getStrategy(route->mStreamType);
4691 if ((routeStrategy == strategy) && route->isActive()) {
Paul McLeanaa981192015-03-21 09:55:15 -07004692 return route->mDeviceDescriptor->type();
4693 }
4694 }
4695
Eric Laurente552edb2014-03-10 17:42:56 -07004696 if (fromCache) {
4697 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4698 strategy, mDeviceForStrategy[strategy]);
4699 return mDeviceForStrategy[strategy];
4700 }
François Gaffie2110e042015-03-24 08:41:51 +01004701 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07004702}
4703
Eric Laurente0720872014-03-11 09:30:41 -07004704void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004705{
4706 for (int i = 0; i < NUM_STRATEGIES; i++) {
4707 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4708 }
4709 mPreviousOutputs = mOutputs;
4710}
4711
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004712uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004713 audio_devices_t prevDevice,
4714 uint32_t delayMs)
4715{
4716 // mute/unmute strategies using an incompatible device combination
4717 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4718 // if unmuting, unmute only after the specified delay
4719 if (outputDesc->isDuplicated()) {
4720 return 0;
4721 }
4722
4723 uint32_t muteWaitMs = 0;
4724 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004725 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004726
4727 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4728 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07004729 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07004730 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4731 bool doMute = false;
4732
4733 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4734 doMute = true;
4735 outputDesc->mStrategyMutedByDevice[i] = true;
4736 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4737 doMute = true;
4738 outputDesc->mStrategyMutedByDevice[i] = false;
4739 }
Eric Laurent99401132014-05-07 19:48:15 -07004740 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004741 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004742 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004743 // skip output if it does not share any device with current output
4744 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4745 == AUDIO_DEVICE_NONE) {
4746 continue;
4747 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07004748 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07004749 mute ? "muting" : "unmuting", i, curDevice);
4750 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01004751 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004752 if (mute) {
4753 // FIXME: should not need to double latency if volume could be applied
4754 // immediately by the audioflinger mixer. We must account for the delay
4755 // between now and the next time the audioflinger thread for this output
4756 // will process a buffer (which corresponds to one buffer size,
4757 // usually 1/2 or 1/4 of the latency).
4758 if (muteWaitMs < desc->latency() * 2) {
4759 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004760 }
4761 }
4762 }
4763 }
4764 }
4765 }
4766
Eric Laurent99401132014-05-07 19:48:15 -07004767 // temporary mute output if device selection changes to avoid volume bursts due to
4768 // different per device volumes
4769 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07004770 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
4771 // temporary mute duration is conservatively set to 4 times the reported latency
4772 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
4773 if (muteWaitMs < tempMuteWaitMs) {
4774 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07004775 }
Eric Laurentdc462862016-07-19 12:29:53 -07004776
Eric Laurent99401132014-05-07 19:48:15 -07004777 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01004778 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07004779 // make sure that we do not start the temporary mute period too early in case of
4780 // delayed device change
4781 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004782 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07004783 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07004784 }
4785 }
4786 }
4787
Eric Laurente552edb2014-03-10 17:42:56 -07004788 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4789 if (muteWaitMs > delayMs) {
4790 muteWaitMs -= delayMs;
4791 usleep(muteWaitMs * 1000);
4792 return muteWaitMs;
4793 }
4794 return 0;
4795}
4796
Eric Laurentc75307b2015-03-17 15:29:32 -07004797uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004798 audio_devices_t device,
4799 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004800 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004801 audio_patch_handle_t *patchHandle,
4802 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004803{
Eric Laurentc75307b2015-03-17 15:29:32 -07004804 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004805 AudioParameter param;
4806 uint32_t muteWaitMs;
4807
4808 if (outputDesc->isDuplicated()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004809 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs);
4810 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004811 return muteWaitMs;
4812 }
4813 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4814 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07004815 if ((device != AUDIO_DEVICE_NONE) &&
4816 ((device & outputDesc->supportedDevices()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004817 return 0;
4818 }
4819
4820 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07004821 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004822
4823 audio_devices_t prevDevice = outputDesc->mDevice;
4824
Paul McLeanaa981192015-03-21 09:55:15 -07004825 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004826
4827 if (device != AUDIO_DEVICE_NONE) {
4828 outputDesc->mDevice = device;
4829 }
4830 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4831
4832 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07004833 // the requested device is AUDIO_DEVICE_NONE
4834 // OR the requested device is the same as current device
4835 // AND force is not specified
4836 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07004837 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07004838 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
4839 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004840 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004841 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004842 return muteWaitMs;
4843 }
4844
4845 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004846
Eric Laurente552edb2014-03-10 17:42:56 -07004847 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004848 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004849 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004850 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07004851 DeviceVector deviceList;
4852 if ((address == NULL) || (strlen(address) == 0)) {
4853 deviceList = mAvailableOutputDevices.getDevicesFromType(device);
4854 } else {
4855 deviceList = mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
4856 }
4857
Eric Laurent1c333e22014-05-20 10:48:17 -07004858 if (!deviceList.isEmpty()) {
4859 struct audio_patch patch;
4860 outputDesc->toAudioPortConfig(&patch.sources[0]);
4861 patch.num_sources = 1;
4862 patch.num_sinks = 0;
4863 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4864 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004865 patch.num_sinks++;
4866 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004867 ssize_t index;
4868 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4869 index = mAudioPatches.indexOfKey(*patchHandle);
4870 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004871 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004872 }
4873 sp< AudioPatch> patchDesc;
4874 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4875 if (index >= 0) {
4876 patchDesc = mAudioPatches.valueAt(index);
4877 afPatchHandle = patchDesc->mAfPatchHandle;
4878 }
4879
Eric Laurent1c333e22014-05-20 10:48:17 -07004880 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004881 &afPatchHandle,
4882 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004883 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4884 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004885 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004886 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004887 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01004888 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004889 addAudioPatch(patchDesc->mHandle, patchDesc);
4890 } else {
4891 patchDesc->mPatch = patch;
4892 }
4893 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07004894 if (patchHandle) {
4895 *patchHandle = patchDesc->mHandle;
4896 }
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004897 outputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004898 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004899 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004900 }
4901 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004902
4903 // inform all input as well
4904 for (size_t i = 0; i < mInputs.size(); i++) {
4905 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01004906 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08004907 AudioParameter inputCmd = AudioParameter();
4908 ALOGV("%s: inform input %d of device:%d", __func__,
4909 inputDescriptor->mIoHandle, device);
4910 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4911 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4912 inputCmd.toString(),
4913 delayMs);
4914 }
4915 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004916 }
Eric Laurente552edb2014-03-10 17:42:56 -07004917
4918 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07004919 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004920
4921 return muteWaitMs;
4922}
4923
Eric Laurentc75307b2015-03-17 15:29:32 -07004924status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07004925 int delayMs,
4926 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004927{
Eric Laurent6a94d692014-05-20 11:18:06 -07004928 ssize_t index;
4929 if (patchHandle) {
4930 index = mAudioPatches.indexOfKey(*patchHandle);
4931 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004932 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004933 }
4934 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004935 return INVALID_OPERATION;
4936 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004937 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4938 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004939 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07004940 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07004941 removeAudioPatch(patchDesc->mHandle);
4942 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004943 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004944 return status;
4945}
4946
4947status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4948 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004949 bool force,
4950 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004951{
4952 status_t status = NO_ERROR;
4953
Eric Laurent1f2f2232014-06-02 12:01:23 -07004954 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004955 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4956 inputDesc->mDevice = device;
4957
4958 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4959 if (!deviceList.isEmpty()) {
4960 struct audio_patch patch;
4961 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004962 // AUDIO_SOURCE_HOTWORD is for internal use only:
4963 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004964 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
Eric Laurent599c7582015-12-07 18:05:55 -08004965 !inputDesc->isSoundTrigger()) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004966 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4967 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004968 patch.num_sinks = 1;
4969 //only one input device for now
4970 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004971 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004972 ssize_t index;
4973 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4974 index = mAudioPatches.indexOfKey(*patchHandle);
4975 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004976 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004977 }
4978 sp< AudioPatch> patchDesc;
4979 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4980 if (index >= 0) {
4981 patchDesc = mAudioPatches.valueAt(index);
4982 afPatchHandle = patchDesc->mAfPatchHandle;
4983 }
4984
Eric Laurent1c333e22014-05-20 10:48:17 -07004985 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004986 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004987 0);
4988 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004989 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004990 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004991 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01004992 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004993 addAudioPatch(patchDesc->mHandle, patchDesc);
4994 } else {
4995 patchDesc->mPatch = patch;
4996 }
4997 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07004998 if (patchHandle) {
4999 *patchHandle = patchDesc->mHandle;
5000 }
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005001 inputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005002 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005003 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005004 }
5005 }
5006 }
5007 return status;
5008}
5009
Eric Laurent6a94d692014-05-20 11:18:06 -07005010status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5011 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005012{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005013 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005014 ssize_t index;
5015 if (patchHandle) {
5016 index = mAudioPatches.indexOfKey(*patchHandle);
5017 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005018 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005019 }
5020 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005021 return INVALID_OPERATION;
5022 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005023 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5024 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005025 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005026 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005027 removeAudioPatch(patchDesc->mHandle);
5028 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005029 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005030 return status;
5031}
5032
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005033sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005034 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005035 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005036 audio_format_t& format,
5037 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005038 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005039{
5040 // Choose an input profile based on the requested capture parameters: select the first available
5041 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005042 //
5043 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5044 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005045
5046 for (size_t i = 0; i < mHwModules.size(); i++)
5047 {
5048 if (mHwModules[i]->mHandle == 0) {
5049 continue;
5050 }
5051 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
5052 {
Eric Laurent1c333e22014-05-20 10:48:17 -07005053 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07005054 // profile->log();
Eric Laurent275e8e92014-11-30 15:14:47 -08005055 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07005056 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005057 format,
5058 &format /*updatedFormat*/,
5059 channelMask,
5060 &channelMask /*updatedChannelMask*/,
5061 (audio_output_flags_t) flags)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005062
Eric Laurente552edb2014-03-10 17:42:56 -07005063 return profile;
5064 }
5065 }
5066 }
5067 return NULL;
5068}
5069
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005070
5071audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005072 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005073{
François Gaffie036e1e92015-03-19 10:16:24 +01005074 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5075 audio_devices_t selectedDeviceFromMix =
5076 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005077
François Gaffie036e1e92015-03-19 10:16:24 +01005078 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5079 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005080 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005081 return getDeviceForInputSource(inputSource);
5082}
5083
5084audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5085{
Paul McLean466dc8e2015-04-17 13:15:36 -06005086 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
5087 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005088 if (inputSource == route->mSource && route->isActive()) {
Paul McLean466dc8e2015-04-17 13:15:36 -06005089 return route->mDeviceDescriptor->type();
5090 }
5091 }
5092
5093 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005094}
5095
Eric Laurente0720872014-03-11 09:30:41 -07005096float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005097 int index,
5098 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005099{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005100 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005101
5102 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5103 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5104 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5105 // the ringtone volume
5106 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5107 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5108 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5109 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5110 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5111 }
5112
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005113 // in-call: always cap earpiece volume by voice volume + some low headroom
5114 if ((stream != AUDIO_STREAM_VOICE_CALL) && (device & AUDIO_DEVICE_OUT_EARPIECE) && isInCall()) {
5115 switch (stream) {
5116 case AUDIO_STREAM_SYSTEM:
5117 case AUDIO_STREAM_RING:
5118 case AUDIO_STREAM_MUSIC:
5119 case AUDIO_STREAM_ALARM:
5120 case AUDIO_STREAM_NOTIFICATION:
5121 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5122 case AUDIO_STREAM_DTMF:
5123 case AUDIO_STREAM_ACCESSIBILITY: {
5124 const float maxVoiceVolDb = computeVolume(AUDIO_STREAM_VOICE_CALL, index, device)
5125 + IN_CALL_EARPIECE_HEADROOM_DB;
5126 if (volumeDB > maxVoiceVolDb) {
5127 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5128 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5129 volumeDB = maxVoiceVolDb;
5130 }
5131 } break;
5132 default:
5133 break;
5134 }
5135 }
5136
Eric Laurente552edb2014-03-10 17:42:56 -07005137 // if a headset is connected, apply the following rules to ring tones and notifications
5138 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005139 // - always attenuate notifications volume by 6dB
5140 // - attenuate ring tones volume by 6dB unless music is not playing and
5141 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005142 // - if music is playing, always limit the volume to current music volume,
5143 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005144 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005145 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5146 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5147 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005148 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
5149 AUDIO_DEVICE_OUT_USB_HEADSET)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005150 ((stream_strategy == STRATEGY_SONIFICATION)
5151 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005152 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005153 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005154 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005155 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005156 // when the phone is ringing we must consider that music could have been paused just before
5157 // by the music application and behave as if music was active if the last music track was
5158 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005159 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005160 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005161 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005162 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005163 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005164 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5165 musicDevice),
5166 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005167 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5168 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005169 if (volumeDB > minVolDB) {
5170 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005171 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005172 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005173 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5174 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5175 // on A2DP, also ensure notification volume is not too low compared to media when
5176 // intended to be played
5177 if ((volumeDB > -96.0f) &&
5178 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5179 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5180 stream, device,
5181 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5182 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5183 }
5184 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005185 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5186 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005187 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005188 }
5189 }
5190
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005191 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005192}
5193
Eric Laurente0720872014-03-11 09:30:41 -07005194status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005195 int index,
5196 const sp<AudioOutputDescriptor>& outputDesc,
5197 audio_devices_t device,
5198 int delayMs,
5199 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005200{
Eric Laurente552edb2014-03-10 17:42:56 -07005201 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005202 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005203 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005204 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005205 return NO_ERROR;
5206 }
François Gaffie2110e042015-03-24 08:41:51 +01005207 audio_policy_forced_cfg_t forceUseForComm =
5208 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005209 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005210 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5211 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005212 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005213 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005214 return INVALID_OPERATION;
5215 }
5216
Eric Laurentc75307b2015-03-17 15:29:32 -07005217 if (device == AUDIO_DEVICE_NONE) {
5218 device = outputDesc->device();
5219 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005220
Eric Laurentffbc80f2015-03-18 18:30:19 -07005221 float volumeDb = computeVolume(stream, index, device);
Eric Laurentc75307b2015-03-17 15:29:32 -07005222 if (outputDesc->isFixedVolume(device)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005223 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005224 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005225
Eric Laurentffbc80f2015-03-18 18:30:19 -07005226 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005227
Eric Laurent3b73df72014-03-11 09:06:29 -07005228 if (stream == AUDIO_STREAM_VOICE_CALL ||
5229 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005230 float voiceVolume;
5231 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005232 if (stream == AUDIO_STREAM_VOICE_CALL) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005233 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005234 } else {
5235 voiceVolume = 1.0;
5236 }
5237
Eric Laurent18fba842016-03-31 14:41:26 -07005238 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005239 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5240 mLastVoiceVolume = voiceVolume;
5241 }
5242 }
5243
5244 return NO_ERROR;
5245}
5246
Eric Laurentc75307b2015-03-17 15:29:32 -07005247void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5248 audio_devices_t device,
5249 int delayMs,
5250 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005251{
Eric Laurentc75307b2015-03-17 15:29:32 -07005252 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005253
Eric Laurent794fde22016-03-11 09:50:45 -08005254 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005255 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005256 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005257 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005258 device,
5259 delayMs,
5260 force);
5261 }
5262}
5263
Eric Laurente0720872014-03-11 09:30:41 -07005264void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005265 bool on,
5266 const sp<AudioOutputDescriptor>& outputDesc,
5267 int delayMs,
5268 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005269{
Eric Laurent72249d52015-06-08 11:12:15 -07005270 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5271 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005272 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005273 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005274 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005275 }
5276 }
5277}
5278
Eric Laurente0720872014-03-11 09:30:41 -07005279void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005280 bool on,
5281 const sp<AudioOutputDescriptor>& outputDesc,
5282 int delayMs,
5283 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005284{
Eric Laurente552edb2014-03-10 17:42:56 -07005285 if (device == AUDIO_DEVICE_NONE) {
5286 device = outputDesc->device();
5287 }
5288
Eric Laurentc75307b2015-03-17 15:29:32 -07005289 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5290 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005291
5292 if (on) {
5293 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005294 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005295 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005296 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005297 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005298 }
5299 }
5300 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5301 outputDesc->mMuteCount[stream]++;
5302 } else {
5303 if (outputDesc->mMuteCount[stream] == 0) {
5304 ALOGV("setStreamMute() unmuting non muted stream!");
5305 return;
5306 }
5307 if (--outputDesc->mMuteCount[stream] == 0) {
5308 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005309 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005310 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005311 device,
5312 delayMs);
5313 }
5314 }
5315}
5316
Eric Laurente0720872014-03-11 09:30:41 -07005317void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005318 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005319{
Eric Laurent87ffa392015-05-22 10:32:38 -07005320 if(!hasPrimaryOutput()) {
5321 return;
5322 }
5323
Eric Laurente552edb2014-03-10 17:42:56 -07005324 // if the stream pertains to sonification strategy and we are in call we must
5325 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5326 // in the device used for phone strategy and play the tone if the selected device does not
5327 // interfere with the device used for phone strategy
5328 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5329 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005330 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005331 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5332 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005333 sp<SwAudioOutputDescriptor> outputDesc = mPrimaryOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07005334 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5335 stream, starting, outputDesc->mDevice, stateChange);
5336 if (outputDesc->mRefCount[stream]) {
5337 int muteCount = 1;
5338 if (stateChange) {
5339 muteCount = outputDesc->mRefCount[stream];
5340 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005341 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005342 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5343 for (int i = 0; i < muteCount; i++) {
5344 setStreamMute(stream, starting, mPrimaryOutput);
5345 }
5346 } else {
5347 ALOGV("handleIncallSonification() high visibility");
5348 if (outputDesc->device() &
5349 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5350 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5351 for (int i = 0; i < muteCount; i++) {
5352 setStreamMute(stream, starting, mPrimaryOutput);
5353 }
5354 }
5355 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005356 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5357 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005358 } else {
5359 mpClientInterface->stopTone();
5360 }
5361 }
5362 }
5363 }
5364}
5365
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005366audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5367{
5368 // flags to stream type mapping
5369 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5370 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5371 }
5372 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5373 return AUDIO_STREAM_BLUETOOTH_SCO;
5374 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005375 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5376 return AUDIO_STREAM_TTS;
5377 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005378
5379 // usage to stream type mapping
5380 switch (attr->usage) {
5381 case AUDIO_USAGE_MEDIA:
5382 case AUDIO_USAGE_GAME:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005383 case AUDIO_USAGE_ASSISTANT:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005384 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5385 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005386 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5387 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005388 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5389 return AUDIO_STREAM_SYSTEM;
5390 case AUDIO_USAGE_VOICE_COMMUNICATION:
5391 return AUDIO_STREAM_VOICE_CALL;
5392
5393 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5394 return AUDIO_STREAM_DTMF;
5395
5396 case AUDIO_USAGE_ALARM:
5397 return AUDIO_STREAM_ALARM;
5398 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5399 return AUDIO_STREAM_RING;
5400
5401 case AUDIO_USAGE_NOTIFICATION:
5402 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5403 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5404 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5405 case AUDIO_USAGE_NOTIFICATION_EVENT:
5406 return AUDIO_STREAM_NOTIFICATION;
5407
5408 case AUDIO_USAGE_UNKNOWN:
5409 default:
5410 return AUDIO_STREAM_MUSIC;
5411 }
5412}
Eric Laurente83b55d2014-11-14 10:06:21 -08005413
François Gaffie53615e22015-03-19 09:24:12 +01005414bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5415{
Eric Laurente83b55d2014-11-14 10:06:21 -08005416 // has flags that map to a strategy?
5417 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5418 return true;
5419 }
5420
5421 // has known usage?
5422 switch (paa->usage) {
5423 case AUDIO_USAGE_UNKNOWN:
5424 case AUDIO_USAGE_MEDIA:
5425 case AUDIO_USAGE_VOICE_COMMUNICATION:
5426 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5427 case AUDIO_USAGE_ALARM:
5428 case AUDIO_USAGE_NOTIFICATION:
5429 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5430 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5431 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5432 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5433 case AUDIO_USAGE_NOTIFICATION_EVENT:
5434 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5435 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5436 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5437 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005438 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005439 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005440 break;
5441 default:
5442 return false;
5443 }
5444 return true;
5445}
5446
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005447bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005448 routing_strategy strategy, uint32_t inPastMs,
5449 nsecs_t sysTime) const
5450{
5451 if ((sysTime == 0) && (inPastMs != 0)) {
5452 sysTime = systemTime();
5453 }
Eric Laurent794fde22016-03-11 09:50:45 -08005454 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005455 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5456 (NUM_STRATEGIES == strategy)) &&
5457 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5458 return true;
5459 }
5460 }
5461 return false;
5462}
5463
François Gaffie2110e042015-03-24 08:41:51 +01005464audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5465{
5466 return mEngine->getForceUse(usage);
5467}
5468
5469bool AudioPolicyManager::isInCall()
5470{
5471 return isStateInCall(mEngine->getPhoneState());
5472}
5473
5474bool AudioPolicyManager::isStateInCall(int state)
5475{
5476 return is_state_in_call(state);
5477}
5478
Eric Laurentd60560a2015-04-10 11:31:20 -07005479void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5480{
5481 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5482 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
5483 if (sourceDesc->mDevice->equals(deviceDesc)) {
5484 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle());
5485 stopAudioSource(sourceDesc->getHandle());
5486 }
5487 }
5488
5489 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5490 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5491 bool release = false;
5492 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5493 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5494 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5495 source->ext.device.type == deviceDesc->type()) {
5496 release = true;
5497 }
5498 }
5499 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5500 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5501 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5502 sink->ext.device.type == deviceDesc->type()) {
5503 release = true;
5504 }
5505 }
5506 if (release) {
5507 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5508 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5509 }
5510 }
5511}
5512
Phil Burk09bc4612016-02-24 15:58:15 -08005513// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005514void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5515 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005516 // TODO Set this based on Config properties.
5517 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005518
5519 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5520 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005521 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005522
5523 // Analyze original support for various formats.
Phil Burk07ac1142016-03-25 13:39:29 -07005524 bool supportsAC3 = false;
5525 bool supportsOtherSurround = false;
Phil Burk09bc4612016-02-24 15:58:15 -08005526 bool supportsIEC61937 = false;
5527 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
5528 audio_format_t format = formats[formatIndex];
Phil Burk09bc4612016-02-24 15:58:15 -08005529 switch (format) {
5530 case AUDIO_FORMAT_AC3:
Phil Burk07ac1142016-03-25 13:39:29 -07005531 supportsAC3 = true;
5532 break;
Phil Burk09bc4612016-02-24 15:58:15 -08005533 case AUDIO_FORMAT_E_AC3:
5534 case AUDIO_FORMAT_DTS:
5535 case AUDIO_FORMAT_DTS_HD:
Phil Burk07ac1142016-03-25 13:39:29 -07005536 supportsOtherSurround = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005537 break;
5538 case AUDIO_FORMAT_IEC61937:
5539 supportsIEC61937 = true;
5540 break;
5541 default:
5542 break;
5543 }
5544 }
Phil Burk09bc4612016-02-24 15:58:15 -08005545
5546 // Modify formats based on surround preferences.
5547 // If NEVER, remove support for surround formats.
Phil Burk07ac1142016-03-25 13:39:29 -07005548 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5549 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5550 // Remove surround sound related formats.
5551 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5552 audio_format_t format = formats[formatIndex];
5553 switch(format) {
5554 case AUDIO_FORMAT_AC3:
5555 case AUDIO_FORMAT_E_AC3:
5556 case AUDIO_FORMAT_DTS:
5557 case AUDIO_FORMAT_DTS_HD:
5558 case AUDIO_FORMAT_IEC61937:
Phil Burk07ac1142016-03-25 13:39:29 -07005559 formats.removeAt(formatIndex);
5560 break;
5561 default:
5562 formatIndex++; // keep it
5563 break;
5564 }
Phil Burk09bc4612016-02-24 15:58:15 -08005565 }
Phil Burk07ac1142016-03-25 13:39:29 -07005566 supportsAC3 = false;
5567 supportsOtherSurround = false;
5568 supportsIEC61937 = false;
Phil Burk09bc4612016-02-24 15:58:15 -08005569 }
Phil Burk07ac1142016-03-25 13:39:29 -07005570 } else { // AUTO or ALWAYS
5571 // Most TVs support AC3 even if they do not report it in the EDID.
5572 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
5573 && !supportsAC3) {
5574 formats.add(AUDIO_FORMAT_AC3);
5575 supportsAC3 = true;
5576 }
5577
5578 // If ALWAYS, add support for raw surround formats if all are missing.
5579 // This assumes that if any of these formats are reported by the HAL
5580 // then the report is valid and should not be modified.
5581 if ((forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS)
5582 && !supportsOtherSurround) {
5583 formats.add(AUDIO_FORMAT_E_AC3);
5584 formats.add(AUDIO_FORMAT_DTS);
5585 formats.add(AUDIO_FORMAT_DTS_HD);
5586 supportsOtherSurround = true;
5587 }
5588
5589 // Add support for IEC61937 if any raw surround supported.
5590 // The HAL could do this but add it here, just in case.
5591 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
5592 formats.add(AUDIO_FORMAT_IEC61937);
5593 supportsIEC61937 = true;
5594 }
Phil Burk09bc4612016-02-24 15:58:15 -08005595 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005596}
5597
5598// Modify the list of channel masks supported.
5599void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
5600 ChannelsVector &channelMasks = *channelMasksPtr;
5601 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5602 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5603
5604 // If NEVER, then remove support for channelMasks > stereo.
5605 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5606 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5607 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5608 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5609 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5610 channelMasks.removeAt(maskIndex);
5611 } else {
5612 maskIndex++;
5613 }
5614 }
5615 // If ALWAYS, then make sure we at least support 5.1
5616 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5617 bool supports5dot1 = false;
5618 // Are there any channel masks that can be considered "surround"?
5619 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); maskIndex++) {
5620 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5621 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5622 supports5dot1 = true;
5623 break;
5624 }
5625 }
5626 // If not then add 5.1 support.
5627 if (!supports5dot1) {
5628 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
5629 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
5630 }
Phil Burk09bc4612016-02-24 15:58:15 -08005631 }
5632}
5633
Phil Burk00eeb322016-03-31 12:41:00 -07005634void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
5635 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005636 AudioProfileVector &profiles)
5637{
5638 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07005639
François Gaffie112b0af2015-11-19 16:13:25 +01005640 // Format MUST be checked first to update the list of AudioProfile
5641 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005642 reply = mpClientInterface->getParameters(
5643 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
Phil Burk0709b0a2016-03-31 12:54:57 -07005644 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005645 AudioParameter repliedParameters(reply);
5646 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005647 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005648 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5649 return;
5650 }
Phil Burk09bc4612016-02-24 15:58:15 -08005651 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07005652 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005653 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005654 }
Phil Burk09bc4612016-02-24 15:58:15 -08005655 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005656 }
5657 const FormatVector &supportedFormats = profiles.getSupportedFormats();
5658
Eric Laurent20eb3a42016-01-26 18:39:17 -08005659 for (size_t formatIndex = 0; formatIndex < supportedFormats.size(); formatIndex++) {
François Gaffie112b0af2015-11-19 16:13:25 +01005660 audio_format_t format = supportedFormats[formatIndex];
Eric Laurent20eb3a42016-01-26 18:39:17 -08005661 ChannelsVector channelMasks;
5662 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005663 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07005664 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01005665
5666 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005667 reply = mpClientInterface->getParameters(
5668 ioHandle,
5669 requestedParameters.toString() + ";" +
5670 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01005671 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005672 AudioParameter repliedParameters(reply);
5673 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005674 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005675 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005676 }
5677 }
5678 if (profiles.hasDynamicChannelsFor(format)) {
5679 reply = mpClientInterface->getParameters(ioHandle,
5680 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07005681 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01005682 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005683 AudioParameter repliedParameters(reply);
5684 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005685 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005686 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07005687 if (device == AUDIO_DEVICE_OUT_HDMI) {
5688 filterSurroundChannelMasks(&channelMasks);
5689 }
François Gaffie112b0af2015-11-19 16:13:25 +01005690 }
5691 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08005692 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01005693 }
5694}
Eric Laurentd60560a2015-04-10 11:31:20 -07005695
Eric Laurente552edb2014-03-10 17:42:56 -07005696}; // namespace android