blob: 906e05a70f49dbdc1d3a536eea36ca12d6577120 [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
Andy Hung7c7124e2017-10-20 12:03:34 -07001252 // - has a current device selection that differs from selected device.
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001253 // - supports currently selected device
Eric Laurent77305a62016-07-25 16:39:22 -07001254 // - 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
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001256 // 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 &&
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001259 desc->supportedDevices() & device &&
Eric Laurent77305a62016-07-25 16:39:22 -07001260 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
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001266 uint32_t latency = desc->latency();
1267 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1268 waitMs = latency;
Eric Laurente552edb2014-03-10 17:42:56 -07001269 }
1270 }
1271 }
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001272 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,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001281 mVolumeCurves->getVolumeIndex(stream, outputDesc->device()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001282 outputDesc,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001283 outputDesc->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 Laurentad2e7b92017-09-14 20:06:42 -07001447 status_t status = NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -08001448 // handle legacy remote submix case where the address was not always specified
1449 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001450 audio_source_t halInputSource;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001451 audio_source_t inputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001452 AudioMix *policyMix = NULL;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001453 DeviceVector inputDevices;
Eric Laurent20b9ef02016-12-05 11:03:16 -08001454
Paul McLean466dc8e2015-04-17 13:15:36 -06001455 // Explicit routing?
1456 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -07001457 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
1458 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
1459 if (mAvailableInputDevices[i]->getId() == *selectedDeviceId) {
1460 deviceDesc = mAvailableInputDevices[i];
1461 break;
1462 }
Paul McLean466dc8e2015-04-17 13:15:36 -06001463 }
1464 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001465 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
Paul McLean466dc8e2015-04-17 13:15:36 -06001466
Eric Laurentad2e7b92017-09-14 20:06:42 -07001467 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1468 // possible
1469 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1470 *input != AUDIO_IO_HANDLE_NONE) {
1471 ssize_t index = mInputs.indexOfKey(*input);
1472 if (index < 0) {
1473 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1474 status = BAD_VALUE;
1475 goto error;
1476 }
1477 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1478 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1479 if (audioSession == 0) {
1480 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1481 status = BAD_VALUE;
1482 goto error;
1483 }
1484 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1485 // The second call is for the first active client and sets the UID. Any further call
1486 // corresponds to a new client and is only permitted from the same UId.
1487 if (audioSession->openCount() == 1) {
1488 audioSession->setUid(uid);
1489 } else if (audioSession->uid() != uid) {
1490 ALOGW("getInputForAttr() bad uid %d for session %d uid %d",
1491 uid, session, audioSession->uid());
1492 status = INVALID_OPERATION;
1493 goto error;
1494 }
1495 audioSession->changeOpenCount(1);
1496 *inputType = API_INPUT_LEGACY;
1497 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1498 *portId = AudioPort::getNextUniqueId();
1499 }
1500 inputDevices = mAvailableInputDevices.getDevicesFromType(inputDesc->mDevice);
1501 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1502 : AUDIO_PORT_HANDLE_NONE;
1503 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
1504
1505 return NO_ERROR;
1506 }
1507
1508 *input = AUDIO_IO_HANDLE_NONE;
1509 *inputType = API_INPUT_INVALID;
1510
1511 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1512 inputSource = AUDIO_SOURCE_MIC;
1513 }
1514 halInputSource = inputSource;
1515
1516 // TODO: check for existing client for this port ID
1517 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1518 *portId = AudioPort::getNextUniqueId();
1519 }
1520
1521 audio_devices_t device;
1522
Eric Laurentc447ded2015-01-06 08:47:05 -08001523 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001524 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001525 status = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
1526 if (status != NO_ERROR) {
1527 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001528 }
1529 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001530 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1531 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001532 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001533 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001534 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001535 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001536 status = BAD_VALUE;
1537 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001538 }
Eric Laurentc722f302014-12-10 11:21:49 -08001539 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001540 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001541 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1542 // there is an external policy, but this input is attached to a mix of recorders,
1543 // meaning it receives audio injected into the framework, so the recorder doesn't
1544 // know about it and is therefore considered "legacy"
1545 *inputType = API_INPUT_LEGACY;
1546 } else {
1547 // recording a mix of players defined by an external policy, we're rerouting for
1548 // an external policy
1549 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1550 }
Eric Laurentc722f302014-12-10 11:21:49 -08001551 } else if (audio_is_remote_submix_device(device)) {
1552 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001553 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001554 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1555 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001556 } else {
1557 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001558 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001559
Eric Laurent599c7582015-12-07 18:05:55 -08001560 }
1561
1562 *input = getInputForDevice(device, address, session, uid, inputSource,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001563 config->sample_rate, config->format, config->channel_mask, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001564 policyMix);
1565 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001566 status = INVALID_OPERATION;
1567 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001568 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001569
Eric Laurentad2e7b92017-09-14 20:06:42 -07001570 inputDevices = mAvailableInputDevices.getDevicesFromType(device);
Eric Laurent2ac76942017-06-22 17:17:09 -07001571 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1572 : AUDIO_PORT_HANDLE_NONE;
1573
1574 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d",
1575 *input, *inputType, *selectedDeviceId);
1576
Eric Laurent599c7582015-12-07 18:05:55 -08001577 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001578
1579error:
1580 mInputRoutes.removeRoute(session);
1581 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001582}
1583
1584
1585audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1586 String8 address,
1587 audio_session_t session,
1588 uid_t uid,
1589 audio_source_t inputSource,
1590 uint32_t samplingRate,
1591 audio_format_t format,
1592 audio_channel_mask_t channelMask,
1593 audio_input_flags_t flags,
1594 AudioMix *policyMix)
1595{
1596 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1597 audio_source_t halInputSource = inputSource;
1598 bool isSoundTrigger = false;
1599
1600 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1601 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1602 if (index >= 0) {
1603 input = mSoundTriggerSessions.valueFor(session);
1604 isSoundTrigger = true;
1605 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1606 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1607 } else {
1608 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001609 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001610 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001611 audio_is_linear_pcm(format)) {
1612 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001613 }
1614
Andy Hungf129b032015-04-07 13:45:50 -07001615 // find a compatible input profile (not necessarily identical in parameters)
1616 sp<IOProfile> profile;
1617 // samplingRate and flags may be updated by getInputProfile
Glenn Kasten05ddca52016-02-11 08:17:12 -08001618 uint32_t profileSamplingRate = (samplingRate == 0) ? SAMPLE_RATE_HZ_DEFAULT : samplingRate;
Andy Hungf129b032015-04-07 13:45:50 -07001619 audio_format_t profileFormat = format;
1620 audio_channel_mask_t profileChannelMask = channelMask;
1621 audio_input_flags_t profileFlags = flags;
1622 for (;;) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001623 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001624 profileSamplingRate, profileFormat, profileChannelMask,
1625 profileFlags);
1626 if (profile != 0) {
1627 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001628 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1629 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001630 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1631 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1632 } else { // fail
Glenn Kastenfaa10a62017-05-25 15:52:05 -07001633 ALOGW("getInputForDevice() could not find profile for device 0x%X, "
Eric Laurent599c7582015-12-07 18:05:55 -08001634 "samplingRate %u, format %#x, channelMask 0x%X, flags %#x",
Andy Hungf129b032015-04-07 13:45:50 -07001635 device, samplingRate, format, channelMask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001636 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001637 }
Eric Laurente552edb2014-03-10 17:42:56 -07001638 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001639 // Pick input sampling rate if not specified by client
1640 if (samplingRate == 0) {
1641 samplingRate = profileSamplingRate;
1642 }
Eric Laurente552edb2014-03-10 17:42:56 -07001643
Eric Laurent322b4d22015-04-03 15:57:54 -07001644 if (profile->getModuleHandle() == 0) {
1645 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001646 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001647 }
1648
Eric Laurent599c7582015-12-07 18:05:55 -08001649 sp<AudioSession> audioSession = new AudioSession(session,
1650 inputSource,
1651 format,
1652 samplingRate,
1653 channelMask,
1654 flags,
1655 uid,
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001656 isSoundTrigger,
1657 policyMix, mpClientInterface);
Eric Laurent599c7582015-12-07 18:05:55 -08001658
Eric Laurent74708e72017-04-07 17:13:42 -07001659// FIXME: disable concurrent capture until UI is ready
1660#if 0
Eric Laurent599c7582015-12-07 18:05:55 -08001661 // reuse an open input if possible
Eric Laurent555530a2017-02-07 18:17:24 -08001662 sp<AudioInputDescriptor> reusedInputDesc;
Eric Laurent599c7582015-12-07 18:05:55 -08001663 for (size_t i = 0; i < mInputs.size(); i++) {
1664 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001665 // reuse input if:
1666 // - it shares the same profile
1667 // AND
1668 // - it is not a reroute submix input
1669 // AND
1670 // - it is: not used for sound trigger
1671 // OR
1672 // used for sound trigger and all clients use the same session ID
1673 //
1674 if ((profile == desc->mProfile) &&
1675 (isSoundTrigger == desc->isSoundTrigger()) &&
1676 !is_virtual_input_device(device)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001677
1678 sp<AudioSession> as = desc->getAudioSession(session);
1679 if (as != 0) {
1680 // do not allow unmatching properties on same session
1681 if (as->matches(audioSession)) {
1682 as->changeOpenCount(1);
1683 } else {
1684 ALOGW("getInputForDevice() record with different attributes"
1685 " exists for session %d", session);
Eric Laurent555530a2017-02-07 18:17:24 -08001686 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001687 }
Eric Laurentfb66dd92016-01-28 18:32:03 -08001688 } else if (isSoundTrigger) {
Eric Laurent555530a2017-02-07 18:17:24 -08001689 continue;
Eric Laurentfb66dd92016-01-28 18:32:03 -08001690 }
Eric Laurentbb948092017-01-23 18:33:30 -08001691
Eric Laurent555530a2017-02-07 18:17:24 -08001692 // Reuse the already opened input stream on this profile if:
1693 // - the new capture source is background OR
1694 // - the path requested configurations match OR
1695 // - the new source priority is less than the highest source priority on this input
1696 // If the input stream cannot be reused, close it before opening a new stream
1697 // on the same profile for the new client so that the requested path configuration
1698 // can be selected.
1699 if (!isConcurrentSource(inputSource) &&
Eric Laurentbb948092017-01-23 18:33:30 -08001700 ((desc->mSamplingRate != samplingRate ||
Eric Laurentfb66dd92016-01-28 18:32:03 -08001701 desc->mChannelMask != channelMask ||
Eric Laurente6930022016-02-11 10:20:40 -08001702 !audio_formats_match(desc->mFormat, format)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001703 (source_priority(desc->getHighestPrioritySource(false /*activeOnly*/)) <
Eric Laurentbb948092017-01-23 18:33:30 -08001704 source_priority(inputSource)))) {
Eric Laurent555530a2017-02-07 18:17:24 -08001705 reusedInputDesc = desc;
1706 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001707 } else {
1708 desc->addAudioSession(session, audioSession);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001709 ALOGV("%s: reusing input %d", __FUNCTION__, mInputs.keyAt(i));
1710 return mInputs.keyAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08001711 }
Eric Laurent599c7582015-12-07 18:05:55 -08001712 }
1713 }
Eric Laurent599c7582015-12-07 18:05:55 -08001714
Eric Laurent555530a2017-02-07 18:17:24 -08001715 if (reusedInputDesc != 0) {
1716 AudioSessionCollection sessions = reusedInputDesc->getAudioSessions(false /*activeOnly*/);
1717 for (size_t j = 0; j < sessions.size(); j++) {
1718 audio_session_t currentSession = sessions.keyAt(j);
1719 stopInput(reusedInputDesc->mIoHandle, currentSession);
1720 releaseInput(reusedInputDesc->mIoHandle, currentSession);
1721 }
1722 }
Eric Laurent74708e72017-04-07 17:13:42 -07001723#endif
Eric Laurent555530a2017-02-07 18:17:24 -08001724
Eric Laurentcf2c0212014-07-25 16:20:43 -07001725 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
Andy Hungf129b032015-04-07 13:45:50 -07001726 config.sample_rate = profileSamplingRate;
1727 config.channel_mask = profileChannelMask;
1728 config.format = profileFormat;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001729
Eric Laurente3014102017-05-03 11:15:43 -07001730 if (address == "") {
1731 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(device);
1732 // the inputs vector must be of size 1, but we don't want to crash here
1733 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress : String8("");
1734 }
1735
Eric Laurent322b4d22015-04-03 15:57:54 -07001736 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurent599c7582015-12-07 18:05:55 -08001737 &input,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001738 &config,
1739 &device,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001740 address,
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001741 halInputSource,
Andy Hungf129b032015-04-07 13:45:50 -07001742 profileFlags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001743
1744 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001745 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Andy Hungf129b032015-04-07 13:45:50 -07001746 (profileSamplingRate != config.sample_rate) ||
Eric Laurente6930022016-02-11 10:20:40 -08001747 !audio_formats_match(profileFormat, config.format) ||
Andy Hungf129b032015-04-07 13:45:50 -07001748 (profileChannelMask != config.channel_mask)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001749 ALOGW("getInputForAttr() failed opening input: samplingRate %d"
1750 ", format %d, channelMask %x",
Eric Laurentcf2c0212014-07-25 16:20:43 -07001751 samplingRate, format, channelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001752 if (input != AUDIO_IO_HANDLE_NONE) {
1753 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001754 }
Eric Laurent599c7582015-12-07 18:05:55 -08001755 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001756 }
1757
Eric Laurent1f2f2232014-06-02 12:01:23 -07001758 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Andy Hungf129b032015-04-07 13:45:50 -07001759 inputDesc->mSamplingRate = profileSamplingRate;
1760 inputDesc->mFormat = profileFormat;
1761 inputDesc->mChannelMask = profileChannelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001762 inputDesc->mDevice = device;
Eric Laurentc722f302014-12-10 11:21:49 -08001763 inputDesc->mPolicyMix = policyMix;
Eric Laurent599c7582015-12-07 18:05:55 -08001764 inputDesc->addAudioSession(session, audioSession);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001765
Eric Laurent599c7582015-12-07 18:05:55 -08001766 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001767 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001768
Eric Laurent599c7582015-12-07 18:05:55 -08001769 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001770}
1771
Eric Laurentbb948092017-01-23 18:33:30 -08001772//static
1773bool AudioPolicyManager::isConcurrentSource(audio_source_t source)
1774{
1775 return (source == AUDIO_SOURCE_HOTWORD) ||
1776 (source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
1777 (source == AUDIO_SOURCE_FM_TUNER);
1778}
1779
Eric Laurentfb66dd92016-01-28 18:32:03 -08001780bool AudioPolicyManager::isConcurentCaptureAllowed(const sp<AudioInputDescriptor>& inputDesc,
1781 const sp<AudioSession>& audioSession)
1782{
1783 // Do not allow capture if an active voice call is using a software patch and
1784 // the call TX source device is on the same HW module.
1785 // FIXME: would be better to refine to only inputs whose profile connects to the
1786 // call TX device but this information is not in the audio patch
1787 if (mCallTxPatch != 0 &&
1788 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1789 return false;
1790 }
1791
1792 // starting concurrent capture is enabled if:
1793 // 1) capturing for re-routing
1794 // 2) capturing for HOTWORD source
1795 // 3) capturing for FM TUNER source
1796 // 3) All other active captures are either for re-routing or HOTWORD
1797
1798 if (is_virtual_input_device(inputDesc->mDevice) ||
Eric Laurentbb948092017-01-23 18:33:30 -08001799 isConcurrentSource(audioSession->inputSource())) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001800 return true;
1801 }
1802
1803 Vector< sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
1804 for (size_t i = 0; i < activeInputs.size(); i++) {
1805 sp<AudioInputDescriptor> activeInput = activeInputs[i];
Eric Laurentbb948092017-01-23 18:33:30 -08001806 if (!isConcurrentSource(activeInput->inputSource(true)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001807 !is_virtual_input_device(activeInput->mDevice)) {
1808 return false;
1809 }
1810 }
1811
1812 return true;
1813}
1814
Chris Thornton2b864642017-06-27 21:26:07 -07001815// FIXME: remove when concurrent capture is ready. This is a hack to work around bug b/63083537.
1816bool AudioPolicyManager::soundTriggerSupportsConcurrentCapture() {
1817 if (!mHasComputedSoundTriggerSupportsConcurrentCapture) {
1818 bool soundTriggerSupportsConcurrentCapture = false;
1819 unsigned int numModules = 0;
1820 struct sound_trigger_module_descriptor* nModules = NULL;
1821
1822 status_t status = SoundTrigger::listModules(nModules, &numModules);
1823 if (status == NO_ERROR && numModules != 0) {
1824 nModules = (struct sound_trigger_module_descriptor*) calloc(
1825 numModules, sizeof(struct sound_trigger_module_descriptor));
1826 if (nModules == NULL) {
1827 // We failed to malloc the buffer, so just say no for now, and hope that we have more
1828 // ram the next time this function is called.
1829 ALOGE("Failed to allocate buffer for module descriptors");
1830 return false;
1831 }
1832
1833 status = SoundTrigger::listModules(nModules, &numModules);
1834 if (status == NO_ERROR) {
1835 soundTriggerSupportsConcurrentCapture = true;
1836 for (size_t i = 0; i < numModules; ++i) {
1837 soundTriggerSupportsConcurrentCapture &=
1838 nModules[i].properties.concurrent_capture;
1839 }
1840 }
1841 free(nModules);
1842 }
1843 mSoundTriggerSupportsConcurrentCapture = soundTriggerSupportsConcurrentCapture;
1844 mHasComputedSoundTriggerSupportsConcurrentCapture = true;
1845 }
1846 return mSoundTriggerSupportsConcurrentCapture;
1847}
1848
Eric Laurentfb66dd92016-01-28 18:32:03 -08001849
Eric Laurent4dc68062014-07-28 17:26:49 -07001850status_t AudioPolicyManager::startInput(audio_io_handle_t input,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001851 audio_session_t session,
1852 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07001853{
1854 ALOGV("startInput() input %d", input);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001855 *concurrency = API_INPUT_CONCURRENCY_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001856 ssize_t index = mInputs.indexOfKey(input);
1857 if (index < 0) {
1858 ALOGW("startInput() unknown input %d", input);
1859 return BAD_VALUE;
1860 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001861 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001862
Eric Laurent599c7582015-12-07 18:05:55 -08001863 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1864 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07001865 ALOGW("startInput() unknown session %d on input %d", session, input);
1866 return BAD_VALUE;
1867 }
1868
Eric Laurent74708e72017-04-07 17:13:42 -07001869// FIXME: disable concurrent capture until UI is ready
1870#if 0
Eric Laurentfb66dd92016-01-28 18:32:03 -08001871 if (!isConcurentCaptureAllowed(inputDesc, audioSession)) {
1872 ALOGW("startInput(%d) failed: other input already started", input);
1873 return INVALID_OPERATION;
1874 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001875
Eric Laurentfb66dd92016-01-28 18:32:03 -08001876 if (isInCall()) {
1877 *concurrency |= API_INPUT_CONCURRENCY_CALL;
1878 }
Eric Laurentf7c50102016-09-30 15:19:43 -07001879 if (mInputs.activeInputsCountOnDevices() != 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001880 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurente552edb2014-03-10 17:42:56 -07001881 }
Eric Laurent74708e72017-04-07 17:13:42 -07001882#else
1883 if (!is_virtual_input_device(inputDesc->mDevice)) {
1884 if (mCallTxPatch != 0 &&
1885 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1886 ALOGW("startInput(%d) failed: call in progress", input);
1887 return INVALID_OPERATION;
1888 }
1889
1890 Vector< sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
1891 for (size_t i = 0; i < activeInputs.size(); i++) {
1892 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
1893
1894 if (is_virtual_input_device(activeDesc->mDevice)) {
1895 continue;
1896 }
1897
Eric Laurentcb4dae22017-07-01 19:39:32 -07001898 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
1899 activeDesc->getId() == inputDesc->getId()) {
1900 continue;
1901 }
1902
Eric Laurent74708e72017-04-07 17:13:42 -07001903 audio_source_t activeSource = activeDesc->inputSource(true);
1904 if (audioSession->inputSource() == AUDIO_SOURCE_HOTWORD) {
1905 if (activeSource == AUDIO_SOURCE_HOTWORD) {
1906 if (activeDesc->hasPreemptedSession(session)) {
1907 ALOGW("startInput(%d) failed for HOTWORD: "
1908 "other input %d already started for HOTWORD",
1909 input, activeDesc->mIoHandle);
1910 return INVALID_OPERATION;
1911 }
1912 } else {
1913 ALOGV("startInput(%d) failed for HOTWORD: other input %d already started",
1914 input, activeDesc->mIoHandle);
1915 return INVALID_OPERATION;
1916 }
1917 } else {
1918 if (activeSource != AUDIO_SOURCE_HOTWORD) {
1919 ALOGW("startInput(%d) failed: other input %d already started",
1920 input, activeDesc->mIoHandle);
1921 return INVALID_OPERATION;
1922 }
1923 }
1924 }
1925
Chris Thornton2b864642017-06-27 21:26:07 -07001926 // We only need to check if the sound trigger session supports concurrent capture if the
1927 // input is also a sound trigger input. Otherwise, we should preempt any hotword stream
1928 // that's running.
1929 const bool allowConcurrentWithSoundTrigger =
1930 inputDesc->isSoundTrigger() ? soundTriggerSupportsConcurrentCapture() : false;
1931
Eric Laurent74708e72017-04-07 17:13:42 -07001932 // if capture is allowed, preempt currently active HOTWORD captures
1933 for (size_t i = 0; i < activeInputs.size(); i++) {
1934 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
1935
1936 if (is_virtual_input_device(activeDesc->mDevice)) {
1937 continue;
1938 }
1939
Chris Thornton2b864642017-06-27 21:26:07 -07001940 if (allowConcurrentWithSoundTrigger && activeDesc->isSoundTrigger()) {
1941 continue;
1942 }
1943
Eric Laurent74708e72017-04-07 17:13:42 -07001944 audio_source_t activeSource = activeDesc->inputSource(true);
1945 if (activeSource == AUDIO_SOURCE_HOTWORD) {
1946 AudioSessionCollection activeSessions =
1947 activeDesc->getAudioSessions(true /*activeOnly*/);
1948 audio_session_t activeSession = activeSessions.keyAt(0);
1949 audio_io_handle_t activeHandle = activeDesc->mIoHandle;
1950 SortedVector<audio_session_t> sessions = activeDesc->getPreemptedSessions();
1951 sessions.add(activeSession);
1952 inputDesc->setPreemptedSessions(sessions);
1953 stopInput(activeHandle, activeSession);
1954 releaseInput(activeHandle, activeSession);
1955 ALOGV("startInput(%d) for HOTWORD preempting HOTWORD input %d",
1956 input, activeDesc->mIoHandle);
1957 }
1958 }
1959 }
1960#endif
Eric Laurente552edb2014-03-10 17:42:56 -07001961
Eric Laurent313d1e72016-01-29 09:56:57 -08001962 // increment activity count before calling getNewInputDevice() below as only active sessions
1963 // are considered for device selection
1964 audioSession->changeActiveCount(1);
1965
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001966 // Routing?
1967 mInputRoutes.incRouteActivity(session);
1968
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001969 if (audioSession->activeCount() == 1 || mInputRoutes.hasRouteChanged(session)) {
Eric Laurent271a93e2016-09-29 14:47:06 -07001970 // indicate active capture to sound trigger service if starting capture from a mic on
1971 // primary HW module
Eric Laurentf7c50102016-09-30 15:19:43 -07001972 audio_devices_t device = getNewInputDevice(inputDesc);
Eric Laurent271a93e2016-09-29 14:47:06 -07001973 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001974
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001975 if (inputDesc->getAudioSessionCount(true/*activeOnly*/) == 1) {
1976 // if input maps to a dynamic policy with an activity listener, notify of state change
1977 if ((inputDesc->mPolicyMix != NULL)
1978 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
1979 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
1980 MIX_STATE_MIXING);
Eric Laurentc722f302014-12-10 11:21:49 -08001981 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001982
Eric Laurentf7c50102016-09-30 15:19:43 -07001983 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
1984 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Eric Laurent05b345e2016-11-18 12:36:27 -08001985 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001986 SoundTrigger::setCaptureState(true);
1987 }
1988
1989 // automatically enable the remote submix output when input is started if not
1990 // used by a policy mix of type MIX_TYPE_RECORDERS
1991 // For remote submix (a virtual device), we open only one input per capture request.
1992 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1993 String8 address = String8("");
1994 if (inputDesc->mPolicyMix == NULL) {
1995 address = String8("0");
1996 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1997 address = inputDesc->mPolicyMix->mDeviceAddress;
1998 }
1999 if (address != "") {
2000 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2001 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2002 address, "remote-submix");
2003 }
Eric Laurentc722f302014-12-10 11:21:49 -08002004 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002005 }
Eric Laurente552edb2014-03-10 17:42:56 -07002006 }
2007
Eric Laurent599c7582015-12-07 18:05:55 -08002008 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
Eric Laurente552edb2014-03-10 17:42:56 -07002009
Eric Laurente552edb2014-03-10 17:42:56 -07002010 return NO_ERROR;
2011}
2012
Eric Laurent4dc68062014-07-28 17:26:49 -07002013status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
2014 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07002015{
2016 ALOGV("stopInput() input %d", input);
2017 ssize_t index = mInputs.indexOfKey(input);
2018 if (index < 0) {
2019 ALOGW("stopInput() unknown input %d", input);
2020 return BAD_VALUE;
2021 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002022 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07002023
Eric Laurent599c7582015-12-07 18:05:55 -08002024 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07002025 if (index < 0) {
2026 ALOGW("stopInput() unknown session %d on input %d", session, input);
2027 return BAD_VALUE;
2028 }
2029
Eric Laurent599c7582015-12-07 18:05:55 -08002030 if (audioSession->activeCount() == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002031 ALOGW("stopInput() input %d already stopped", input);
2032 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002033 }
2034
Eric Laurent599c7582015-12-07 18:05:55 -08002035 audioSession->changeActiveCount(-1);
Paul McLean466dc8e2015-04-17 13:15:36 -06002036
2037 // Routing?
2038 mInputRoutes.decRouteActivity(session);
2039
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002040 if (audioSession->activeCount() == 0) {
Eric Laurent84332aa2016-01-28 22:19:18 +00002041
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002042 if (inputDesc->isActive()) {
2043 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2044 } else {
2045 // if input maps to a dynamic policy with an activity listener, notify of state change
2046 if ((inputDesc->mPolicyMix != NULL)
2047 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2048 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2049 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002050 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002051
2052 // automatically disable the remote submix output when input is stopped if not
2053 // used by a policy mix of type MIX_TYPE_RECORDERS
2054 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2055 String8 address = String8("");
2056 if (inputDesc->mPolicyMix == NULL) {
2057 address = String8("0");
2058 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2059 address = inputDesc->mPolicyMix->mDeviceAddress;
2060 }
2061 if (address != "") {
2062 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2063 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2064 address, "remote-submix");
2065 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002066 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002067
Eric Laurentf7c50102016-09-30 15:19:43 -07002068 audio_devices_t device = inputDesc->mDevice;
Eric Laurentfb66dd92016-01-28 18:32:03 -08002069 resetInputDevice(input);
Eric Laurent84332aa2016-01-28 22:19:18 +00002070
Eric Laurentf7c50102016-09-30 15:19:43 -07002071 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2072 // primary HW module
2073 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2074 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2075 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08002076 SoundTrigger::setCaptureState(false);
2077 }
2078 inputDesc->clearPreemptedSessions();
Eric Laurent84332aa2016-01-28 22:19:18 +00002079 }
Eric Laurente552edb2014-03-10 17:42:56 -07002080 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002081 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002082}
2083
Eric Laurent4dc68062014-07-28 17:26:49 -07002084void AudioPolicyManager::releaseInput(audio_io_handle_t input,
2085 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07002086{
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002087
Eric Laurente552edb2014-03-10 17:42:56 -07002088 ALOGV("releaseInput() %d", input);
2089 ssize_t index = mInputs.indexOfKey(input);
2090 if (index < 0) {
2091 ALOGW("releaseInput() releasing unknown input %d", input);
2092 return;
2093 }
Paul McLean466dc8e2015-04-17 13:15:36 -06002094
2095 // Routing
2096 mInputRoutes.removeRoute(session);
2097
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002098 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
2099 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07002100
Eric Laurent599c7582015-12-07 18:05:55 -08002101 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
vivek mehta587b8df2017-01-31 14:58:44 -08002102 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07002103 ALOGW("releaseInput() unknown session %d on input %d", session, input);
2104 return;
2105 }
Eric Laurent599c7582015-12-07 18:05:55 -08002106
2107 if (audioSession->openCount() == 0) {
2108 ALOGW("releaseInput() invalid open count %d on session %d",
2109 audioSession->openCount(), session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002110 return;
2111 }
Eric Laurent599c7582015-12-07 18:05:55 -08002112
2113 if (audioSession->changeOpenCount(-1) == 0) {
2114 inputDesc->removeAudioSession(session);
2115 }
2116
Jean-Michel Trivi65bfe912015-12-04 15:56:47 -08002117 if (inputDesc->getOpenRefCount() > 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002118 ALOGV("releaseInput() exit > 0");
2119 return;
2120 }
2121
Eric Laurent05b90f82014-08-27 15:32:29 -07002122 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002123 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002124 ALOGV("releaseInput() exit");
2125}
2126
Eric Laurentd4692962014-05-05 18:13:44 -07002127void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002128 bool patchRemoved = false;
2129
Eric Laurentd4692962014-05-05 18:13:44 -07002130 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002131 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002132 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002133 if (patch_index >= 0) {
2134 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002135 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002136 mAudioPatches.removeItemsAt(patch_index);
2137 patchRemoved = true;
2138 }
Eric Laurentd4692962014-05-05 18:13:44 -07002139 mpClientInterface->closeInput(mInputs.keyAt(input_index));
2140 }
2141 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002142 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002143 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002144
2145 if (patchRemoved) {
2146 mpClientInterface->onAudioPatchListUpdate();
2147 }
Eric Laurentd4692962014-05-05 18:13:44 -07002148}
2149
Eric Laurente0720872014-03-11 09:30:41 -07002150void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002151 int indexMin,
2152 int indexMax)
2153{
2154 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002155 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002156
2157 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002158 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2159 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002160 continue;
2161 }
2162 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002163 }
Eric Laurente552edb2014-03-10 17:42:56 -07002164}
2165
Eric Laurente0720872014-03-11 09:30:41 -07002166status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002167 int index,
2168 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002169{
2170
François Gaffied1ab2bd2015-12-02 18:20:06 +01002171 if ((index < mVolumeCurves->getVolumeIndexMin(stream)) ||
2172 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002173 return BAD_VALUE;
2174 }
2175 if (!audio_is_output_device(device)) {
2176 return BAD_VALUE;
2177 }
2178
2179 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002180 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002181
Eric Laurent1fd372e2016-04-06 14:23:53 -07002182 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002183 stream, device, index);
2184
Eric Laurent28d09f02016-03-08 10:43:05 -08002185 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002186 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2187 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002188 continue;
2189 }
2190 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2191 }
Eric Laurente552edb2014-03-10 17:42:56 -07002192
Eric Laurent1fd372e2016-04-06 14:23:53 -07002193 // update volume on all outputs and streams matching the following:
2194 // - The requested stream (or a stream matching for volume control) is active on the output
2195 // - The device (or devices) selected by the strategy corresponding to this stream includes
2196 // the requested device
2197 // - For non default requested device, currently selected device on the output is either the
2198 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002199 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2200 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002201 status_t status = NO_ERROR;
2202 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002203 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2204 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08002205 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2206 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002207 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002208 }
Eric Laurentd3926fe2016-04-15 18:10:07 -07002209 if (!(desc->isStreamActive((audio_stream_type_t)curStream) ||
2210 (isInCall() && (curStream == AUDIO_STREAM_VOICE_CALL)))) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002211 continue;
2212 }
Eric Laurent794fde22016-03-11 09:50:45 -08002213 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002214 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2215 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002216 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2217 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002218 continue;
2219 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002220 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002221 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002222 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07002223 applyVolume = (curDevice & curStreamDevice) != 0;
2224 } else {
2225 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002226 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002227 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002228
Eric Laurente76f29c2016-09-14 17:17:53 -07002229 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002230 //FIXME: workaround for truncated touch sounds
2231 // delayed volume change for system stream to be removed when the problem is
2232 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002233 status_t volStatus =
Eric Laurentdc462862016-07-19 12:29:53 -07002234 checkAndSetVolume((audio_stream_type_t)curStream, index, desc, curDevice,
2235 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002236 if (volStatus != NO_ERROR) {
2237 status = volStatus;
2238 }
2239 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002240 }
Eric Laurente552edb2014-03-10 17:42:56 -07002241 }
2242 return status;
2243}
2244
Eric Laurente0720872014-03-11 09:30:41 -07002245status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002246 int *index,
2247 audio_devices_t device)
2248{
2249 if (index == NULL) {
2250 return BAD_VALUE;
2251 }
2252 if (!audio_is_output_device(device)) {
2253 return BAD_VALUE;
2254 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002255 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002256 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002257 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002258 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2259 }
François Gaffiedfd74092015-03-19 12:10:59 +01002260 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002261
François Gaffied1ab2bd2015-12-02 18:20:06 +01002262 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002263 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2264 return NO_ERROR;
2265}
2266
Eric Laurent36829f92017-04-07 19:04:42 -07002267audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002268{
2269 // select one output among several suitable for global effects.
2270 // The priority is as follows:
2271 // 1: An offloaded output. If the effect ends up not being offloadable,
2272 // AudioFlinger will invalidate the track and the offloaded output
2273 // will be closed causing the effect to be moved to a PCM output.
2274 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002275 // 3: The primary output
2276 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002277
Eric Laurent3b73df72014-03-11 09:06:29 -07002278 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002279 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent36829f92017-04-07 19:04:42 -07002280 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002281
Eric Laurent36829f92017-04-07 19:04:42 -07002282 if (outputs.size() == 0) {
2283 return AUDIO_IO_HANDLE_NONE;
2284 }
Eric Laurente552edb2014-03-10 17:42:56 -07002285
Eric Laurent36829f92017-04-07 19:04:42 -07002286 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2287 bool activeOnly = true;
2288
2289 while (output == AUDIO_IO_HANDLE_NONE) {
2290 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2291 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2292 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2293
2294 for (size_t i = 0; i < outputs.size(); i++) {
2295 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
2296 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2297 continue;
2298 }
2299 ALOGV("selectOutputForMusicEffects activeOnly %d outputs[%zu] flags 0x%08x",
2300 activeOnly, i, desc->mFlags);
2301 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
2302 outputOffloaded = outputs[i];
2303 }
2304 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
2305 outputDeepBuffer = outputs[i];
2306 }
2307 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
2308 outputPrimary = outputs[i];
2309 }
2310 }
2311 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2312 output = outputOffloaded;
2313 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2314 output = outputDeepBuffer;
2315 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2316 output = outputPrimary;
2317 } else {
2318 output = outputs[0];
2319 }
2320 activeOnly = false;
2321 }
2322
2323 if (output != mMusicEffectOutput) {
2324 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2325 mMusicEffectOutput = output;
2326 }
2327
2328 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002329 return output;
2330}
2331
Eric Laurent36829f92017-04-07 19:04:42 -07002332audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2333{
2334 return selectOutputForMusicEffects();
2335}
2336
Eric Laurente0720872014-03-11 09:30:41 -07002337status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002338 audio_io_handle_t io,
2339 uint32_t strategy,
2340 int session,
2341 int id)
2342{
2343 ssize_t index = mOutputs.indexOfKey(io);
2344 if (index < 0) {
2345 index = mInputs.indexOfKey(io);
2346 if (index < 0) {
2347 ALOGW("registerEffect() unknown io %d", io);
2348 return INVALID_OPERATION;
2349 }
2350 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002351 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002352}
2353
Eric Laurentc75307b2015-03-17 15:29:32 -07002354bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2355{
Eric Laurent28d09f02016-03-08 10:43:05 -08002356 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002357 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2358 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002359 continue;
2360 }
2361 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2362 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002363 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002364}
2365
2366bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2367{
2368 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2369}
2370
Eric Laurente0720872014-03-11 09:30:41 -07002371bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002372{
2373 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002374 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002375 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002376 return true;
2377 }
2378 }
2379 return false;
2380}
2381
Eric Laurent275e8e92014-11-30 15:14:47 -08002382// Register a list of custom mixes with their attributes and format.
2383// When a mix is registered, corresponding input and output profiles are
2384// added to the remote submix hw module. The profile contains only the
2385// parameters (sampling rate, format...) specified by the mix.
2386// The corresponding input remote submix device is also connected.
2387//
2388// When a remote submix device is connected, the address is checked to select the
2389// appropriate profile and the corresponding input or output stream is opened.
2390//
2391// When capture starts, getInputForAttr() will:
2392// - 1 look for a mix matching the address passed in attribtutes tags if any
2393// - 2 if none found, getDeviceForInputSource() will:
2394// - 2.1 look for a mix matching the attributes source
2395// - 2.2 if none found, default to device selection by policy rules
2396// At this time, the corresponding output remote submix device is also connected
2397// and active playback use cases can be transferred to this mix if needed when reconnecting
2398// after AudioTracks are invalidated
2399//
2400// When playback starts, getOutputForAttr() will:
2401// - 1 look for a mix matching the address passed in attribtutes tags if any
2402// - 2 if none found, look for a mix matching the attributes usage
2403// - 3 if none found, default to device and output selection by policy rules.
2404
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002405status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002406{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002407 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2408 status_t res = NO_ERROR;
2409
2410 sp<HwModule> rSubmixModule;
2411 // examine each mix's route type
2412 for (size_t i = 0; i < mixes.size(); i++) {
2413 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
2414 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
2415 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002416 break;
2417 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002418 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
2419 // Loop back through "remote submix"
2420 if (rSubmixModule == 0) {
2421 for (size_t j = 0; i < mHwModules.size(); j++) {
2422 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
2423 && mHwModules[j]->mHandle != 0) {
2424 rSubmixModule = mHwModules[j];
2425 break;
2426 }
2427 }
2428 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002429
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002430 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Eric Laurent275e8e92014-11-30 15:14:47 -08002431
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002432 if (rSubmixModule == 0) {
2433 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration", i);
2434 res = INVALID_OPERATION;
2435 break;
2436 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002437
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002438 String8 address = mixes[i].mDeviceAddress;
François Gaffie036e1e92015-03-19 10:16:24 +01002439
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002440 if (mPolicyMixes.registerMix(address, mixes[i], 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002441 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002442 res = INVALID_OPERATION;
2443 break;
2444 }
2445 audio_config_t outputConfig = mixes[i].mFormat;
2446 audio_config_t inputConfig = mixes[i].mFormat;
2447 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2448 // stereo and let audio flinger do the channel conversion if needed.
2449 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2450 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2451 rSubmixModule->addOutputProfile(address, &outputConfig,
2452 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2453 rSubmixModule->addInputProfile(address, &inputConfig,
2454 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002455
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002456 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
2457 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2458 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2459 address.string(), "remote-submix");
2460 } else {
2461 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2462 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2463 address.string(), "remote-submix");
2464 }
2465 } else if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002466 String8 address = mixes[i].mDeviceAddress;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002467 audio_devices_t device = mixes[i].mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002468 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2469 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002470
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002471 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002472 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2473 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2474 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2475 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2476 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2477 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002478 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2479 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002480 if (mPolicyMixes.registerMix(address, mixes[i], desc) != NO_ERROR) {
2481 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002482 } else {
2483 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002484 }
2485 break;
2486 }
2487 }
2488
2489 if (res != NO_ERROR) {
2490 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002491 i, device, address.string());
2492 res = INVALID_OPERATION;
2493 break;
2494 } else if (!foundOutput) {
2495 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2496 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002497 res = INVALID_OPERATION;
2498 break;
2499 }
Eric Laurentc722f302014-12-10 11:21:49 -08002500 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002501 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002502 if (res != NO_ERROR) {
2503 unregisterPolicyMixes(mixes);
2504 }
2505 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002506}
2507
2508status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2509{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002510 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002511 status_t res = NO_ERROR;
2512 sp<HwModule> rSubmixModule;
2513 // examine each mix's route type
Eric Laurent275e8e92014-11-30 15:14:47 -08002514 for (size_t i = 0; i < mixes.size(); i++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002515 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002516
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002517 if (rSubmixModule == 0) {
2518 for (size_t j = 0; i < mHwModules.size(); j++) {
2519 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
2520 && mHwModules[j]->mHandle != 0) {
2521 rSubmixModule = mHwModules[j];
2522 break;
2523 }
2524 }
2525 }
2526 if (rSubmixModule == 0) {
2527 res = INVALID_OPERATION;
2528 continue;
2529 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002530
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002531 String8 address = mixes[i].mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002532
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002533 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2534 res = INVALID_OPERATION;
2535 continue;
2536 }
2537
2538 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2539 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2540 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2541 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2542 address.string(), "remote-submix");
2543 }
2544 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2545 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2546 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2547 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2548 address.string(), "remote-submix");
2549 }
2550 rSubmixModule->removeOutputProfile(address);
2551 rSubmixModule->removeInputProfile(address);
2552
2553 } if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2554 if (mPolicyMixes.unregisterMix(mixes[i].mDeviceAddress) != NO_ERROR) {
2555 res = INVALID_OPERATION;
2556 continue;
2557 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002558 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002559 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002560 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002561}
2562
Eric Laurente552edb2014-03-10 17:42:56 -07002563
Eric Laurente0720872014-03-11 09:30:41 -07002564status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002565{
2566 const size_t SIZE = 256;
2567 char buffer[SIZE];
2568 String8 result;
2569
2570 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2571 result.append(buffer);
2572
Eric Laurent87ffa392015-05-22 10:32:38 -07002573 snprintf(buffer, SIZE, " Primary Output: %d\n",
2574 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Eric Laurente552edb2014-03-10 17:42:56 -07002575 result.append(buffer);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002576 std::string stateLiteral;
2577 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
2578 snprintf(buffer, SIZE, " Phone state: %s\n", stateLiteral.c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002579 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002580 snprintf(buffer, SIZE, " Force use for communications %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002581 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07002582 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002583 snprintf(buffer, SIZE, " Force use for media %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA));
Eric Laurente552edb2014-03-10 17:42:56 -07002584 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002585 snprintf(buffer, SIZE, " Force use for record %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD));
Eric Laurente552edb2014-03-10 17:42:56 -07002586 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002587 snprintf(buffer, SIZE, " Force use for dock %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_DOCK));
Eric Laurente552edb2014-03-10 17:42:56 -07002588 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002589 snprintf(buffer, SIZE, " Force use for system %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM));
Eric Laurente552edb2014-03-10 17:42:56 -07002590 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002591 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002592 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO));
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002593 result.append(buffer);
Phil Burk09bc4612016-02-24 15:58:15 -08002594 snprintf(buffer, SIZE, " Force use for encoded surround output %d\n",
2595 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND));
2596 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002597 snprintf(buffer, SIZE, " TTS output %s\n", mTtsOutputAvailable ? "available" : "not available");
2598 result.append(buffer);
Andy Hung2ddee192015-12-18 17:34:44 -08002599 snprintf(buffer, SIZE, " Master mono: %s\n", mMasterMono ? "on" : "off");
2600 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002601
François Gaffie2110e042015-03-24 08:41:51 +01002602 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002603
François Gaffie112b0af2015-11-19 16:13:25 +01002604 mAvailableOutputDevices.dump(fd, String8("Available output"));
2605 mAvailableInputDevices.dump(fd, String8("Available input"));
François Gaffie53615e22015-03-19 09:24:12 +01002606 mHwModules.dump(fd);
2607 mOutputs.dump(fd);
2608 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002609 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002610 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002611 mAudioPatches.dump(fd);
Mikhail Naganov44344b02016-12-13 11:21:02 -08002612 mPolicyMixes.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002613
2614 return NO_ERROR;
2615}
2616
2617// This function checks for the parameters which can be offloaded.
2618// This can be enhanced depending on the capability of the DSP and policy
2619// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002620bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002621{
2622 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002623 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002624 offloadInfo.sample_rate, offloadInfo.channel_mask,
2625 offloadInfo.format,
2626 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2627 offloadInfo.has_video);
2628
Andy Hung2ddee192015-12-18 17:34:44 -08002629 if (mMasterMono) {
2630 return false; // no offloading if mono is set.
2631 }
2632
Eric Laurente552edb2014-03-10 17:42:56 -07002633 // Check if offload has been disabled
2634 char propValue[PROPERTY_VALUE_MAX];
2635 if (property_get("audio.offload.disable", propValue, "0")) {
2636 if (atoi(propValue) != 0) {
2637 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2638 return false;
2639 }
2640 }
2641
2642 // Check if stream type is music, then only allow offload as of now.
2643 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2644 {
2645 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2646 return false;
2647 }
2648
2649 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002650 const bool allowOffloadWithVideo =
2651 property_get_bool("audio.offload.video", false /* default_value */);
2652 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002653 ALOGV("isOffloadSupported: has_video == true, returning false");
2654 return false;
2655 }
2656
2657 //If duration is less than minimum value defined in property, return false
2658 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2659 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2660 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2661 return false;
2662 }
2663 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2664 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2665 return false;
2666 }
2667
2668 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2669 // creating an offloaded track and tearing it down immediately after start when audioflinger
2670 // detects there is an active non offloadable effect.
2671 // FIXME: We should check the audio session here but we do not have it in this context.
2672 // This may prevent offloading in rare situations where effects are left active by apps
2673 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002674 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002675 return false;
2676 }
2677
2678 // See if there is a profile to support this.
2679 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002680 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002681 offloadInfo.sample_rate,
2682 offloadInfo.format,
2683 offloadInfo.channel_mask,
2684 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002685 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2686 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002687}
2688
Eric Laurent6a94d692014-05-20 11:18:06 -07002689status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2690 audio_port_type_t type,
2691 unsigned int *num_ports,
2692 struct audio_port *ports,
2693 unsigned int *generation)
2694{
2695 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2696 generation == NULL) {
2697 return BAD_VALUE;
2698 }
2699 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2700 if (ports == NULL) {
2701 *num_ports = 0;
2702 }
2703
2704 size_t portsWritten = 0;
2705 size_t portsMax = *num_ports;
2706 *num_ports = 0;
2707 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002708 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2709 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002710 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002711 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
2712 if (mAvailableOutputDevices[i]->type() == AUDIO_DEVICE_OUT_STUB) {
2713 continue;
2714 }
2715 if (portsWritten < portsMax) {
2716 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2717 }
2718 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002719 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002720 }
2721 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002722 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2723 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_STUB) {
2724 continue;
2725 }
2726 if (portsWritten < portsMax) {
2727 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2728 }
2729 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002730 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002731 }
2732 }
2733 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2734 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2735 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2736 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2737 }
2738 *num_ports += mInputs.size();
2739 }
2740 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002741 size_t numOutputs = 0;
2742 for (size_t i = 0; i < mOutputs.size(); i++) {
2743 if (!mOutputs[i]->isDuplicated()) {
2744 numOutputs++;
2745 if (portsWritten < portsMax) {
2746 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2747 }
2748 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002749 }
Eric Laurent84c70242014-06-23 08:46:27 -07002750 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002751 }
2752 }
2753 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002754 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002755 return NO_ERROR;
2756}
2757
2758status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2759{
2760 return NO_ERROR;
2761}
2762
Eric Laurent6a94d692014-05-20 11:18:06 -07002763status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2764 audio_patch_handle_t *handle,
2765 uid_t uid)
2766{
2767 ALOGV("createAudioPatch()");
2768
2769 if (handle == NULL || patch == NULL) {
2770 return BAD_VALUE;
2771 }
2772 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2773
Eric Laurent874c42872014-08-08 15:13:39 -07002774 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2775 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2776 return BAD_VALUE;
2777 }
2778 // only one source per audio patch supported for now
2779 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002780 return INVALID_OPERATION;
2781 }
Eric Laurent874c42872014-08-08 15:13:39 -07002782
2783 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002784 return INVALID_OPERATION;
2785 }
Eric Laurent874c42872014-08-08 15:13:39 -07002786 for (size_t i = 0; i < patch->num_sinks; i++) {
2787 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2788 return INVALID_OPERATION;
2789 }
2790 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002791
2792 sp<AudioPatch> patchDesc;
2793 ssize_t index = mAudioPatches.indexOfKey(*handle);
2794
Eric Laurent6a94d692014-05-20 11:18:06 -07002795 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2796 patch->sources[0].role,
2797 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002798#if LOG_NDEBUG == 0
2799 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002800 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002801 patch->sinks[i].role,
2802 patch->sinks[i].type);
2803 }
2804#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002805
2806 if (index >= 0) {
2807 patchDesc = mAudioPatches.valueAt(index);
2808 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2809 mUidCached, patchDesc->mUid, uid);
2810 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2811 return INVALID_OPERATION;
2812 }
2813 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002814 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002815 }
2816
2817 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002818 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002819 if (outputDesc == NULL) {
2820 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2821 return BAD_VALUE;
2822 }
Eric Laurent84c70242014-06-23 08:46:27 -07002823 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2824 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002825 if (patchDesc != 0) {
2826 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2827 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2828 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2829 return BAD_VALUE;
2830 }
2831 }
Eric Laurent874c42872014-08-08 15:13:39 -07002832 DeviceVector devices;
2833 for (size_t i = 0; i < patch->num_sinks; i++) {
2834 // Only support mix to devices connection
2835 // TODO add support for mix to mix connection
2836 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2837 ALOGV("createAudioPatch() source mix but sink is not a device");
2838 return INVALID_OPERATION;
2839 }
2840 sp<DeviceDescriptor> devDesc =
2841 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2842 if (devDesc == 0) {
2843 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2844 return BAD_VALUE;
2845 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002846
François Gaffie53615e22015-03-19 09:24:12 +01002847 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002848 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002849 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002850 NULL, // updatedSamplingRate
2851 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002852 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002853 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002854 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002855 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002856 ALOGV("createAudioPatch() profile not supported for device %08x",
2857 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002858 return INVALID_OPERATION;
2859 }
2860 devices.add(devDesc);
2861 }
2862 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002863 return INVALID_OPERATION;
2864 }
Eric Laurent874c42872014-08-08 15:13:39 -07002865
Eric Laurent6a94d692014-05-20 11:18:06 -07002866 // TODO: reconfigure output format and channels here
2867 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002868 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002869 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002870 index = mAudioPatches.indexOfKey(*handle);
2871 if (index >= 0) {
2872 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2873 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2874 }
2875 patchDesc = mAudioPatches.valueAt(index);
2876 patchDesc->mUid = uid;
2877 ALOGV("createAudioPatch() success");
2878 } else {
2879 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2880 return INVALID_OPERATION;
2881 }
2882 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2883 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2884 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002885 // only one sink supported when connecting an input device to a mix
2886 if (patch->num_sinks > 1) {
2887 return INVALID_OPERATION;
2888 }
François Gaffie53615e22015-03-19 09:24:12 +01002889 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002890 if (inputDesc == NULL) {
2891 return BAD_VALUE;
2892 }
2893 if (patchDesc != 0) {
2894 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2895 return BAD_VALUE;
2896 }
2897 }
2898 sp<DeviceDescriptor> devDesc =
2899 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2900 if (devDesc == 0) {
2901 return BAD_VALUE;
2902 }
2903
François Gaffie53615e22015-03-19 09:24:12 +01002904 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002905 devDesc->mAddress,
2906 patch->sinks[0].sample_rate,
2907 NULL, /*updatedSampleRate*/
2908 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002909 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002910 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002911 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002912 // FIXME for the parameter type,
2913 // and the NONE
2914 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002915 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002916 return INVALID_OPERATION;
2917 }
2918 // TODO: reconfigure output format and channels here
2919 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01002920 devDesc->type(), inputDesc->mIoHandle);
2921 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002922 index = mAudioPatches.indexOfKey(*handle);
2923 if (index >= 0) {
2924 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2925 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2926 }
2927 patchDesc = mAudioPatches.valueAt(index);
2928 patchDesc->mUid = uid;
2929 ALOGV("createAudioPatch() success");
2930 } else {
2931 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2932 return INVALID_OPERATION;
2933 }
2934 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2935 // device to device connection
2936 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002937 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002938 return BAD_VALUE;
2939 }
2940 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002941 sp<DeviceDescriptor> srcDeviceDesc =
2942 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002943 if (srcDeviceDesc == 0) {
2944 return BAD_VALUE;
2945 }
Eric Laurent874c42872014-08-08 15:13:39 -07002946
Eric Laurent6a94d692014-05-20 11:18:06 -07002947 //update source and sink with our own data as the data passed in the patch may
2948 // be incomplete.
2949 struct audio_patch newPatch = *patch;
2950 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002951
Eric Laurent874c42872014-08-08 15:13:39 -07002952 for (size_t i = 0; i < patch->num_sinks; i++) {
2953 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2954 ALOGV("createAudioPatch() source device but one sink is not a device");
2955 return INVALID_OPERATION;
2956 }
2957
2958 sp<DeviceDescriptor> sinkDeviceDesc =
2959 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2960 if (sinkDeviceDesc == 0) {
2961 return BAD_VALUE;
2962 }
2963 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2964
Eric Laurent3bcf8592015-04-03 12:13:24 -07002965 // create a software bridge in PatchPanel if:
2966 // - source and sink devices are on differnt HW modules OR
2967 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08002968 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07002969 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07002970 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07002971 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002972 return INVALID_OPERATION;
2973 }
Eric Laurent874c42872014-08-08 15:13:39 -07002974 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01002975 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07002976 // if the sink device is reachable via an opened output stream, request to go via
2977 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002978 audio_io_handle_t output = selectOutput(outputs,
2979 AUDIO_OUTPUT_FLAG_NONE,
2980 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002981 if (output != AUDIO_IO_HANDLE_NONE) {
2982 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2983 if (outputDesc->isDuplicated()) {
2984 return INVALID_OPERATION;
2985 }
2986 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07002987 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07002988 newPatch.num_sources = 2;
2989 }
Eric Laurent83b88082014-06-20 18:31:16 -07002990 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002991 }
2992 // TODO: check from routing capabilities in config file and other conflicting patches
2993
2994 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2995 if (index >= 0) {
2996 afPatchHandle = patchDesc->mAfPatchHandle;
2997 }
2998
2999 status_t status = mpClientInterface->createAudioPatch(&newPatch,
3000 &afPatchHandle,
3001 0);
3002 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
3003 status, afPatchHandle);
3004 if (status == NO_ERROR) {
3005 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01003006 patchDesc = new AudioPatch(&newPatch, uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003007 addAudioPatch(patchDesc->mHandle, patchDesc);
3008 } else {
3009 patchDesc->mPatch = newPatch;
3010 }
3011 patchDesc->mAfPatchHandle = afPatchHandle;
3012 *handle = patchDesc->mHandle;
3013 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003014 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003015 } else {
3016 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3017 status);
3018 return INVALID_OPERATION;
3019 }
3020 } else {
3021 return BAD_VALUE;
3022 }
3023 } else {
3024 return BAD_VALUE;
3025 }
3026 return NO_ERROR;
3027}
3028
3029status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3030 uid_t uid)
3031{
3032 ALOGV("releaseAudioPatch() patch %d", handle);
3033
3034 ssize_t index = mAudioPatches.indexOfKey(handle);
3035
3036 if (index < 0) {
3037 return BAD_VALUE;
3038 }
3039 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3040 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3041 mUidCached, patchDesc->mUid, uid);
3042 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3043 return INVALID_OPERATION;
3044 }
3045
3046 struct audio_patch *patch = &patchDesc->mPatch;
3047 patchDesc->mUid = mUidCached;
3048 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003049 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003050 if (outputDesc == NULL) {
3051 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3052 return BAD_VALUE;
3053 }
3054
Eric Laurentc75307b2015-03-17 15:29:32 -07003055 setOutputDevice(outputDesc,
3056 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07003057 true,
3058 0,
3059 NULL);
3060 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3061 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003062 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003063 if (inputDesc == NULL) {
3064 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3065 return BAD_VALUE;
3066 }
3067 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003068 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003069 true,
3070 NULL);
3071 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003072 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3073 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3074 status, patchDesc->mAfPatchHandle);
3075 removeAudioPatch(patchDesc->mHandle);
3076 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003077 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003078 } else {
3079 return BAD_VALUE;
3080 }
3081 } else {
3082 return BAD_VALUE;
3083 }
3084 return NO_ERROR;
3085}
3086
3087status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3088 struct audio_patch *patches,
3089 unsigned int *generation)
3090{
François Gaffie53615e22015-03-19 09:24:12 +01003091 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003092 return BAD_VALUE;
3093 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003094 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003095 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003096}
3097
Eric Laurente1715a42014-05-20 11:30:42 -07003098status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003099{
Eric Laurente1715a42014-05-20 11:30:42 -07003100 ALOGV("setAudioPortConfig()");
3101
3102 if (config == NULL) {
3103 return BAD_VALUE;
3104 }
3105 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3106 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003107 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3108 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003109 }
3110
Eric Laurenta121f902014-06-03 13:32:54 -07003111 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003112 if (config->type == AUDIO_PORT_TYPE_MIX) {
3113 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003114 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003115 if (outputDesc == NULL) {
3116 return BAD_VALUE;
3117 }
Eric Laurent84c70242014-06-23 08:46:27 -07003118 ALOG_ASSERT(!outputDesc->isDuplicated(),
3119 "setAudioPortConfig() called on duplicated output %d",
3120 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003121 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003122 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003123 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003124 if (inputDesc == NULL) {
3125 return BAD_VALUE;
3126 }
Eric Laurenta121f902014-06-03 13:32:54 -07003127 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003128 } else {
3129 return BAD_VALUE;
3130 }
3131 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3132 sp<DeviceDescriptor> deviceDesc;
3133 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3134 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3135 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3136 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3137 } else {
3138 return BAD_VALUE;
3139 }
3140 if (deviceDesc == NULL) {
3141 return BAD_VALUE;
3142 }
Eric Laurenta121f902014-06-03 13:32:54 -07003143 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003144 } else {
3145 return BAD_VALUE;
3146 }
3147
Eric Laurenta121f902014-06-03 13:32:54 -07003148 struct audio_port_config backupConfig;
3149 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3150 if (status == NO_ERROR) {
3151 struct audio_port_config newConfig;
3152 audioPortConfig->toAudioPortConfig(&newConfig, config);
3153 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003154 }
Eric Laurenta121f902014-06-03 13:32:54 -07003155 if (status != NO_ERROR) {
3156 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003157 }
Eric Laurente1715a42014-05-20 11:30:42 -07003158
3159 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003160}
3161
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003162void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3163{
Eric Laurentd60560a2015-04-10 11:31:20 -07003164 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003165 clearAudioPatches(uid);
3166 clearSessionRoutes(uid);
3167}
3168
Eric Laurent6a94d692014-05-20 11:18:06 -07003169void AudioPolicyManager::clearAudioPatches(uid_t uid)
3170{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003171 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003172 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3173 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003174 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003175 }
3176 }
3177}
3178
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003179void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3180 audio_io_handle_t ouptutToSkip)
3181{
3182 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3183 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3184 for (size_t j = 0; j < mOutputs.size(); j++) {
3185 if (mOutputs.keyAt(j) == ouptutToSkip) {
3186 continue;
3187 }
3188 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3189 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3190 continue;
3191 }
3192 // If the default device for this strategy is on another output mix,
3193 // invalidate all tracks in this strategy to force re connection.
3194 // Otherwise select new device on the output mix.
3195 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003196 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003197 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3198 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3199 }
3200 }
3201 } else {
3202 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3203 setOutputDevice(outputDesc, newDevice, false);
3204 }
3205 }
3206}
3207
3208void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3209{
3210 // remove output routes associated with this uid
3211 SortedVector<routing_strategy> affectedStrategies;
3212 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
3213 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
3214 if (route->mUid == uid) {
3215 mOutputRoutes.removeItemsAt(i);
3216 if (route->mDeviceDescriptor != 0) {
3217 affectedStrategies.add(getStrategy(route->mStreamType));
3218 }
3219 }
3220 }
3221 // reroute outputs if necessary
3222 for (size_t i = 0; i < affectedStrategies.size(); i++) {
3223 checkStrategyRoute(affectedStrategies[i], AUDIO_IO_HANDLE_NONE);
3224 }
3225
3226 // remove input routes associated with this uid
3227 SortedVector<audio_source_t> affectedSources;
3228 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
3229 sp<SessionRoute> route = mInputRoutes.valueAt(i);
3230 if (route->mUid == uid) {
3231 mInputRoutes.removeItemsAt(i);
3232 if (route->mDeviceDescriptor != 0) {
3233 affectedSources.add(route->mSource);
3234 }
3235 }
3236 }
3237 // reroute inputs if necessary
3238 SortedVector<audio_io_handle_t> inputsToClose;
3239 for (size_t i = 0; i < mInputs.size(); i++) {
3240 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003241 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003242 inputsToClose.add(inputDesc->mIoHandle);
3243 }
3244 }
3245 for (size_t i = 0; i < inputsToClose.size(); i++) {
3246 closeInput(inputsToClose[i]);
3247 }
3248}
3249
Eric Laurentd60560a2015-04-10 11:31:20 -07003250void AudioPolicyManager::clearAudioSources(uid_t uid)
3251{
3252 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
3253 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3254 if (sourceDesc->mUid == uid) {
3255 stopAudioSource(mAudioSources.keyAt(i));
3256 }
3257 }
3258}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003259
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003260status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3261 audio_io_handle_t *ioHandle,
3262 audio_devices_t *device)
3263{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003264 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3265 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003266 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003267
François Gaffiedf372692015-03-19 10:43:27 +01003268 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003269}
3270
Eric Laurentd60560a2015-04-10 11:31:20 -07003271status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
3272 const audio_attributes_t *attributes,
Glenn Kasten559d4392016-03-29 13:42:57 -07003273 audio_patch_handle_t *handle,
Eric Laurentd60560a2015-04-10 11:31:20 -07003274 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003275{
Eric Laurentd60560a2015-04-10 11:31:20 -07003276 ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle);
3277 if (source == NULL || attributes == NULL || handle == NULL) {
3278 return BAD_VALUE;
3279 }
3280
Glenn Kasten559d4392016-03-29 13:42:57 -07003281 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003282
3283 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3284 source->type != AUDIO_PORT_TYPE_DEVICE) {
3285 ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type);
3286 return INVALID_OPERATION;
3287 }
3288
3289 sp<DeviceDescriptor> srcDeviceDesc =
3290 mAvailableInputDevices.getDevice(source->ext.device.type,
3291 String8(source->ext.device.address));
3292 if (srcDeviceDesc == 0) {
3293 ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
3294 return BAD_VALUE;
3295 }
3296 sp<AudioSourceDescriptor> sourceDesc =
3297 new AudioSourceDescriptor(srcDeviceDesc, attributes, uid);
3298
3299 struct audio_patch dummyPatch;
3300 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
3301 sourceDesc->mPatchDesc = patchDesc;
3302
3303 status_t status = connectAudioSource(sourceDesc);
3304 if (status == NO_ERROR) {
3305 mAudioSources.add(sourceDesc->getHandle(), sourceDesc);
3306 *handle = sourceDesc->getHandle();
3307 }
3308 return status;
3309}
3310
3311status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3312{
3313 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3314
3315 // make sure we only have one patch per source.
3316 disconnectAudioSource(sourceDesc);
3317
3318 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
Eric Laurent28d09f02016-03-08 10:43:05 -08003319 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003320 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice;
3321
3322 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3323 sp<DeviceDescriptor> sinkDeviceDesc =
3324 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3325
3326 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3327 struct audio_patch *patch = &sourceDesc->mPatchDesc->mPatch;
3328
3329 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3330 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003331 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003332 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3333 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3334 // create patch between src device and output device
3335 // create Hwoutput and add to mHwOutputs
3336 } else {
3337 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3338 audio_io_handle_t output =
3339 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3340 if (output == AUDIO_IO_HANDLE_NONE) {
3341 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3342 return INVALID_OPERATION;
3343 }
3344 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3345 if (outputDesc->isDuplicated()) {
3346 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3347 return INVALID_OPERATION;
3348 }
3349 // create a special patch with no sink and two sources:
3350 // - the second source indicates to PatchPanel through which output mix this patch should
3351 // be connected as well as the stream type for volume control
3352 // - the sink is defined by whatever output device is currently selected for the output
3353 // though which this patch is routed.
3354 patch->num_sinks = 0;
3355 patch->num_sources = 2;
3356 srcDeviceDesc->toAudioPortConfig(&patch->sources[0], NULL);
3357 outputDesc->toAudioPortConfig(&patch->sources[1], NULL);
3358 patch->sources[1].ext.mix.usecase.stream = stream;
3359 status_t status = mpClientInterface->createAudioPatch(patch,
3360 &afPatchHandle,
3361 0);
3362 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3363 status, afPatchHandle);
3364 if (status != NO_ERROR) {
3365 ALOGW("%s patch panel could not connect device patch, error %d",
3366 __FUNCTION__, status);
3367 return INVALID_OPERATION;
3368 }
3369 uint32_t delayMs = 0;
Eric Laurentc40d9692016-04-13 19:14:13 -07003370 status = startSource(outputDesc, stream, sinkDevice, NULL, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003371
3372 if (status != NO_ERROR) {
3373 mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0);
3374 return status;
3375 }
3376 sourceDesc->mSwOutput = outputDesc;
3377 if (delayMs != 0) {
3378 usleep(delayMs * 1000);
3379 }
3380 }
3381
3382 sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle;
3383 addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc);
3384
3385 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003386}
3387
Glenn Kasten559d4392016-03-29 13:42:57 -07003388status_t AudioPolicyManager::stopAudioSource(audio_patch_handle_t handle __unused)
Eric Laurent554a2772015-04-10 11:29:24 -07003389{
Eric Laurentd60560a2015-04-10 11:31:20 -07003390 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle);
3391 ALOGV("%s handle %d", __FUNCTION__, handle);
3392 if (sourceDesc == 0) {
3393 ALOGW("%s unknown source for handle %d", __FUNCTION__, handle);
3394 return BAD_VALUE;
3395 }
3396 status_t status = disconnectAudioSource(sourceDesc);
3397
3398 mAudioSources.removeItem(handle);
3399 return status;
3400}
3401
Andy Hung2ddee192015-12-18 17:34:44 -08003402status_t AudioPolicyManager::setMasterMono(bool mono)
3403{
3404 if (mMasterMono == mono) {
3405 return NO_ERROR;
3406 }
3407 mMasterMono = mono;
3408 // if enabling mono we close all offloaded devices, which will invalidate the
3409 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3410 // for recreating the new AudioTrack as non-offloaded PCM.
3411 //
3412 // If disabling mono, we leave all tracks as is: we don't know which clients
3413 // and tracks are able to be recreated as offloaded. The next "song" should
3414 // play back offloaded.
3415 if (mMasterMono) {
3416 Vector<audio_io_handle_t> offloaded;
3417 for (size_t i = 0; i < mOutputs.size(); ++i) {
3418 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3419 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3420 offloaded.push(desc->mIoHandle);
3421 }
3422 }
3423 for (size_t i = 0; i < offloaded.size(); ++i) {
3424 closeOutput(offloaded[i]);
3425 }
3426 }
3427 // update master mono for all remaining outputs
3428 for (size_t i = 0; i < mOutputs.size(); ++i) {
3429 updateMono(mOutputs.keyAt(i));
3430 }
3431 return NO_ERROR;
3432}
3433
3434status_t AudioPolicyManager::getMasterMono(bool *mono)
3435{
3436 *mono = mMasterMono;
3437 return NO_ERROR;
3438}
3439
Eric Laurentac9cef52017-06-09 15:46:26 -07003440float AudioPolicyManager::getStreamVolumeDB(
3441 audio_stream_type_t stream, int index, audio_devices_t device)
3442{
3443 return computeVolume(stream, index, device);
3444}
3445
Eric Laurentd60560a2015-04-10 11:31:20 -07003446status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3447{
3448 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3449
3450 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle);
3451 if (patchDesc == 0) {
3452 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
3453 sourceDesc->mPatchDesc->mHandle);
3454 return BAD_VALUE;
3455 }
3456 removeAudioPatch(sourceDesc->mPatchDesc->mHandle);
3457
Eric Laurent28d09f02016-03-08 10:43:05 -08003458 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003459 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote();
3460 if (swOutputDesc != 0) {
3461 stopSource(swOutputDesc, stream, false);
3462 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3463 } else {
3464 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote();
3465 if (hwOutputDesc != 0) {
3466 // release patch between src device and output device
3467 // close Hwoutput and remove from mHwOutputs
3468 } else {
3469 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3470 }
3471 }
3472 return NO_ERROR;
3473}
3474
3475sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
3476 audio_io_handle_t output, routing_strategy strategy)
3477{
3478 sp<AudioSourceDescriptor> source;
3479 for (size_t i = 0; i < mAudioSources.size(); i++) {
3480 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3481 routing_strategy sourceStrategy =
3482 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
3483 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote();
3484 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3485 source = sourceDesc;
3486 break;
3487 }
3488 }
3489 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003490}
3491
Eric Laurente552edb2014-03-10 17:42:56 -07003492// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003493// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003494// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003495uint32_t AudioPolicyManager::nextAudioPortGeneration()
3496{
3497 return android_atomic_inc(&mAudioPortGeneration);
3498}
3499
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003500#ifdef USE_XML_AUDIO_POLICY_CONF
3501// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3502static const char *kConfigLocationList[] =
3503 {"/odm/etc", "/vendor/etc", "/system/etc"};
3504static const int kConfigLocationListSize =
3505 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3506
3507static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3508 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
3509 status_t ret;
3510
3511 for (int i = 0; i < kConfigLocationListSize; i++) {
3512 PolicySerializer serializer;
3513 snprintf(audioPolicyXmlConfigFile,
3514 sizeof(audioPolicyXmlConfigFile),
3515 "%s/%s",
3516 kConfigLocationList[i],
3517 AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3518 ret = serializer.deserialize(audioPolicyXmlConfigFile, config);
3519 if (ret == NO_ERROR) {
3520 break;
3521 }
3522 }
3523 return ret;
3524}
3525#endif
3526
Eric Laurente0720872014-03-11 09:30:41 -07003527AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07003528 :
Eric Laurente552edb2014-03-10 17:42:56 -07003529 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003530 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003531 mAudioPortGeneration(1),
3532 mBeaconMuteRefCount(0),
3533 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003534 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003535 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003536 mMasterMono(false),
Chris Thornton2b864642017-06-27 21:26:07 -07003537 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE),
3538 mHasComputedSoundTriggerSupportsConcurrentCapture(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003539{
François Gaffied1ab2bd2015-12-02 18:20:06 +01003540 mUidCached = getuid();
3541 mpClientInterface = clientInterface;
3542
3543 // TODO: remove when legacy conf file is removed. true on devices that use DRC on the
3544 // DEVICE_CATEGORY_SPEAKER path to boost soft sounds, used to adjust volume curves accordingly.
3545 // Note: remove also speaker_drc_enabled from global configuration of XML config file.
3546 bool speakerDrcEnabled = false;
3547
3548#ifdef USE_XML_AUDIO_POLICY_CONF
3549 mVolumeCurves = new VolumeCurvesCollection();
3550 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3551 mDefaultOutputDevice, speakerDrcEnabled,
3552 static_cast<VolumeCurvesCollection *>(mVolumeCurves));
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003553 if (deserializeAudioPolicyXmlConfig(config) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003554#else
3555 mVolumeCurves = new StreamDescriptorCollection();
3556 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3557 mDefaultOutputDevice, speakerDrcEnabled);
3558 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, config) != NO_ERROR) &&
3559 (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, config) != NO_ERROR)) {
3560#endif
3561 ALOGE("could not load audio policy configuration file, setting defaults");
3562 config.setDefault();
3563 }
3564 // must be done after reading the policy (since conditionned by Speaker Drc Enabling)
3565 mVolumeCurves->initializeVolumeCurves(speakerDrcEnabled);
3566
3567 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003568 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3569 if (!engineInstance) {
3570 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
3571 return;
3572 }
3573 // Retrieve the Policy Manager Interface
3574 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3575 if (mEngine == NULL) {
3576 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
3577 return;
3578 }
3579 mEngine->setObserver(this);
3580 status_t status = mEngine->initCheck();
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07003581 (void) status;
François Gaffie2110e042015-03-24 08:41:51 +01003582 ALOG_ASSERT(status == NO_ERROR, "Policy engine not initialized(err=%d)", status);
3583
Eric Laurent3a4311c2014-03-17 12:00:47 -07003584 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003585 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003586 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3587 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003588 for (size_t i = 0; i < mHwModules.size(); i++) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003589 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003590 if (mHwModules[i]->mHandle == 0) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003591 ALOGW("could not open HW module %s", mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003592 continue;
3593 }
3594 // open all output streams needed to access attached devices
3595 // except for direct output streams that are only opened when they are actually
3596 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003597 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07003598 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3599 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003600 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003601
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003602 if (!outProfile->hasSupportedDevices()) {
3603 ALOGW("Output profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003604 continue;
3605 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003606 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003607 mTtsOutputAvailable = true;
3608 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003609
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003610 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003611 continue;
3612 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003613 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003614 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3615 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003616 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003617 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003618 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003619 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003620 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003621 if ((profileType & outputDeviceTypes) == 0) {
3622 continue;
3623 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003624 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3625 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003626 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
3627 const DeviceVector &devicesForType = supportedDevices.getDevicesFromType(profileType);
3628 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3629 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003630
3631 outputDesc->mDevice = profileType;
3632 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3633 config.sample_rate = outputDesc->mSamplingRate;
3634 config.channel_mask = outputDesc->mChannelMask;
3635 config.format = outputDesc->mFormat;
3636 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003637 status_t status = mpClientInterface->openOutput(outProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003638 &output,
3639 &config,
3640 &outputDesc->mDevice,
Eric Laurentc40d9692016-04-13 19:14:13 -07003641 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003642 &outputDesc->mLatency,
3643 outputDesc->mFlags);
3644
3645 if (status != NO_ERROR) {
3646 ALOGW("Cannot open output stream for device %08x on hw module %s",
3647 outputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003648 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003649 } else {
3650 outputDesc->mSamplingRate = config.sample_rate;
3651 outputDesc->mChannelMask = config.channel_mask;
3652 outputDesc->mFormat = config.format;
3653
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003654 for (size_t k = 0; k < supportedDevices.size(); k++) {
3655 ssize_t index = mAvailableOutputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003656 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003657 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
3658 mAvailableOutputDevices[index]->attach(mHwModules[i]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003659 }
3660 }
3661 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003662 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003663 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003664 }
3665 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003666 setOutputDevice(outputDesc,
Eric Laurentd78f1532014-09-16 16:38:20 -07003667 outputDesc->mDevice,
Eric Laurentc40d9692016-04-13 19:14:13 -07003668 true,
3669 0,
3670 NULL,
3671 address.string());
Eric Laurentd78f1532014-09-16 16:38:20 -07003672 }
Eric Laurente552edb2014-03-10 17:42:56 -07003673 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003674 // open input streams needed to access attached devices to validate
3675 // mAvailableInputDevices list
3676 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3677 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003678 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003679
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003680 if (!inProfile->hasSupportedDevices()) {
3681 ALOGW("Input profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003682 continue;
3683 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003684 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003685 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003686 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
3687
Eric Laurentd78f1532014-09-16 16:38:20 -07003688 if ((profileType & inputDeviceTypes) == 0) {
3689 continue;
3690 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08003691 sp<AudioInputDescriptor> inputDesc =
3692 new AudioInputDescriptor(inProfile);
Eric Laurentd78f1532014-09-16 16:38:20 -07003693
Eric Laurentd78f1532014-09-16 16:38:20 -07003694 inputDesc->mDevice = profileType;
3695
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003696 // find the address
3697 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
3698 // the inputs vector must be of size 1, but we don't want to crash here
3699 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3700 : String8("");
3701 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
3702 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
3703
Eric Laurentd78f1532014-09-16 16:38:20 -07003704 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3705 config.sample_rate = inputDesc->mSamplingRate;
3706 config.channel_mask = inputDesc->mChannelMask;
3707 config.format = inputDesc->mFormat;
3708 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003709 status_t status = mpClientInterface->openInput(inProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003710 &input,
3711 &config,
3712 &inputDesc->mDevice,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003713 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003714 AUDIO_SOURCE_MIC,
3715 AUDIO_INPUT_FLAG_NONE);
3716
3717 if (status == NO_ERROR) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003718 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
3719 for (size_t k = 0; k < supportedDevices.size(); k++) {
3720 ssize_t index = mAvailableInputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003721 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07003722 if (index >= 0) {
3723 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
3724 if (!devDesc->isAttached()) {
3725 devDesc->attach(mHwModules[i]);
Eric Laurent83efe1c2017-07-09 16:51:08 -07003726 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07003727 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003728 }
3729 }
3730 mpClientInterface->closeInput(input);
3731 } else {
3732 ALOGW("Cannot open input stream for device %08x on hw module %s",
3733 inputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003734 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003735 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003736 }
3737 }
3738 // make sure all attached devices have been allocated a unique ID
3739 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003740 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003741 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003742 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
3743 continue;
3744 }
François Gaffie2110e042015-03-24 08:41:51 +01003745 // The device is now validated and can be appended to the available devices of the engine
3746 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
3747 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003748 i++;
3749 }
3750 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003751 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01003752 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003753 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
3754 continue;
3755 }
François Gaffie2110e042015-03-24 08:41:51 +01003756 // The device is now validated and can be appended to the available devices of the engine
3757 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
3758 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003759 i++;
3760 }
3761 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003762 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01003763 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003764 }
Eric Laurente552edb2014-03-10 17:42:56 -07003765
3766 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
3767
3768 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -07003769}
3770
Eric Laurente0720872014-03-11 09:30:41 -07003771AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07003772{
Eric Laurente552edb2014-03-10 17:42:56 -07003773 for (size_t i = 0; i < mOutputs.size(); i++) {
3774 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003775 }
3776 for (size_t i = 0; i < mInputs.size(); i++) {
3777 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003778 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003779 mAvailableOutputDevices.clear();
3780 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003781 mOutputs.clear();
3782 mInputs.clear();
3783 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07003784}
3785
Eric Laurente0720872014-03-11 09:30:41 -07003786status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07003787{
Eric Laurent87ffa392015-05-22 10:32:38 -07003788 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003789}
3790
Eric Laurente552edb2014-03-10 17:42:56 -07003791// ---
3792
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003793void AudioPolicyManager::addOutput(audio_io_handle_t output, const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003794{
François Gaffie98cc1912015-03-18 17:52:40 +01003795 outputDesc->setIoHandle(output);
Eric Laurent1c333e22014-05-20 10:48:17 -07003796 mOutputs.add(output, outputDesc);
Andy Hung2ddee192015-12-18 17:34:44 -08003797 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07003798 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07003799 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003800}
3801
François Gaffie53615e22015-03-19 09:24:12 +01003802void AudioPolicyManager::removeOutput(audio_io_handle_t output)
3803{
3804 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07003805 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01003806}
3807
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003808void AudioPolicyManager::addInput(audio_io_handle_t input, const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003809{
François Gaffie98cc1912015-03-18 17:52:40 +01003810 inputDesc->setIoHandle(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07003811 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003812 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003813}
Eric Laurente552edb2014-03-10 17:42:56 -07003814
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003815void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08003816 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003817 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003818 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08003819 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003820 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08003821 if (devDesc != 0) {
3822 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
3823 desc->mIoHandle, address.string());
3824 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003825 }
3826}
3827
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003828status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01003829 audio_policy_dev_state_t state,
3830 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003831 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07003832{
François Gaffie53615e22015-03-19 09:24:12 +01003833 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07003834 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07003835
3836 if (audio_device_is_digital(device)) {
3837 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08003838 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07003839 }
Eric Laurente552edb2014-03-10 17:42:56 -07003840
Eric Laurent3b73df72014-03-11 09:06:29 -07003841 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003842 // first list already open outputs that can be routed to this device
3843 for (size_t i = 0; i < mOutputs.size(); i++) {
3844 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07003845 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003846 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003847 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3848 outputs.add(mOutputs.keyAt(i));
3849 } else {
3850 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08003851 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003852 }
Eric Laurente552edb2014-03-10 17:42:56 -07003853 }
3854 }
3855 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003856 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003857 for (size_t i = 0; i < mHwModules.size(); i++)
3858 {
3859 if (mHwModules[i]->mHandle == 0) {
3860 continue;
3861 }
3862 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3863 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003864 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003865 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003866 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003867 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003868 profiles.add(profile);
3869 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
3870 }
Eric Laurente552edb2014-03-10 17:42:56 -07003871 }
3872 }
3873 }
3874
Eric Laurent7b279bb2015-12-14 10:18:23 -08003875 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003876
Eric Laurente552edb2014-03-10 17:42:56 -07003877 if (profiles.isEmpty() && outputs.isEmpty()) {
3878 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3879 return BAD_VALUE;
3880 }
3881
3882 // open outputs for matching profiles if needed. Direct outputs are also opened to
3883 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3884 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003885 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003886
3887 // nothing to do if one output is already opened for this profile
3888 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003889 for (j = 0; j < outputs.size(); j++) {
3890 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003891 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003892 // matching profile: save the sample rates, format and channel masks supported
3893 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07003894 if (audio_device_is_digital(device)) {
3895 devDesc->importAudioPort(profile);
3896 }
Eric Laurente552edb2014-03-10 17:42:56 -07003897 break;
3898 }
3899 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003900 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003901 continue;
3902 }
3903
Eric Laurent83efe1c2017-07-09 16:51:08 -07003904 ALOGV("opening output for device %08x with params %s profile %p name %s",
3905 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07003906 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07003907 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003908 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3909 config.sample_rate = desc->mSamplingRate;
3910 config.channel_mask = desc->mChannelMask;
3911 config.format = desc->mFormat;
3912 config.offload_info.sample_rate = desc->mSamplingRate;
3913 config.offload_info.channel_mask = desc->mChannelMask;
3914 config.offload_info.format = desc->mFormat;
3915 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003916 status_t status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003917 &output,
3918 &config,
3919 &desc->mDevice,
3920 address,
3921 &desc->mLatency,
3922 desc->mFlags);
3923 if (status == NO_ERROR) {
3924 desc->mSamplingRate = config.sample_rate;
3925 desc->mChannelMask = config.channel_mask;
3926 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003927
Eric Laurentd4692962014-05-05 18:13:44 -07003928 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003929 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003930 char *param = audio_device_address_to_parameter(device, address);
3931 mpClientInterface->setParameters(output, String8(param));
3932 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003933 }
Phil Burk00eeb322016-03-31 12:41:00 -07003934 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01003935 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003936 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003937 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003938 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01003939 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07003940 mpClientInterface->closeOutput(output);
Phil Burk702b1052016-03-02 16:38:26 -08003941 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01003942 profile->pickAudioProfile(config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003943 config.offload_info.sample_rate = config.sample_rate;
3944 config.offload_info.channel_mask = config.channel_mask;
3945 config.offload_info.format = config.format;
Eric Laurent322b4d22015-04-03 15:57:54 -07003946 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003947 &output,
3948 &config,
3949 &desc->mDevice,
3950 address,
3951 &desc->mLatency,
3952 desc->mFlags);
3953 if (status == NO_ERROR) {
3954 desc->mSamplingRate = config.sample_rate;
3955 desc->mChannelMask = config.channel_mask;
3956 desc->mFormat = config.format;
3957 } else {
3958 output = AUDIO_IO_HANDLE_NONE;
3959 }
Eric Laurentd4692962014-05-05 18:13:44 -07003960 }
3961
Eric Laurentcf2c0212014-07-25 16:20:43 -07003962 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003963 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01003964 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01003965 sp<AudioPolicyMix> policyMix;
3966 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003967 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
3968 address.string());
3969 }
François Gaffie036e1e92015-03-19 10:16:24 +01003970 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07003971 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01003972
Eric Laurent87ffa392015-05-22 10:32:38 -07003973 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
3974 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08003975 // no duplicated output for direct outputs and
3976 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07003977 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003978
Eric Laurentd4692962014-05-05 18:13:44 -07003979 // set initial stream volume for device
Eric Laurentc75307b2015-03-17 15:29:32 -07003980 applyStreamVolumes(desc, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003981
Eric Laurentd4692962014-05-05 18:13:44 -07003982 //TODO: configure audio effect output stage here
3983
3984 // open a duplicating output thread for the new output and the primary output
Eric Laurentc75307b2015-03-17 15:29:32 -07003985 duplicatedOutput =
3986 mpClientInterface->openDuplicateOutput(output,
3987 mPrimaryOutput->mIoHandle);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003988 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003989 // add duplicated output descriptor
Eric Laurentc75307b2015-03-17 15:29:32 -07003990 sp<SwAudioOutputDescriptor> dupOutputDesc =
3991 new SwAudioOutputDescriptor(NULL, mpClientInterface);
3992 dupOutputDesc->mOutput1 = mPrimaryOutput;
3993 dupOutputDesc->mOutput2 = desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003994 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3995 dupOutputDesc->mFormat = desc->mFormat;
3996 dupOutputDesc->mChannelMask = desc->mChannelMask;
3997 dupOutputDesc->mLatency = desc->mLatency;
3998 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003999 applyStreamVolumes(dupOutputDesc, device, 0, true);
Eric Laurentd4692962014-05-05 18:13:44 -07004000 } else {
4001 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004002 mPrimaryOutput->mIoHandle, output);
Eric Laurentd4692962014-05-05 18:13:44 -07004003 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01004004 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004005 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004006 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004007 }
Eric Laurente552edb2014-03-10 17:42:56 -07004008 }
4009 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004010 } else {
4011 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004012 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004013 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004014 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004015 profiles.removeAt(profile_index);
4016 profile_index--;
4017 } else {
4018 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004019 // Load digital format info only for digital devices
4020 if (audio_device_is_digital(device)) {
4021 devDesc->importAudioPort(profile);
4022 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004023
François Gaffie53615e22015-03-19 09:24:12 +01004024 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004025 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4026 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004027 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004028 NULL/*patch handle*/, address.string());
4029 }
Eric Laurente552edb2014-03-10 17:42:56 -07004030 ALOGV("checkOutputsForDevice(): adding output %d", output);
4031 }
4032 }
4033
4034 if (profiles.isEmpty()) {
4035 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4036 return BAD_VALUE;
4037 }
Eric Laurentd4692962014-05-05 18:13:44 -07004038 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004039 // check if one opened output is not needed any more after disconnecting one device
4040 for (size_t i = 0; i < mOutputs.size(); i++) {
4041 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004042 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004043 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004044 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004045 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004046 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004047 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004048 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4049 mOutputs.keyAt(i));
4050 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004051 }
Eric Laurente552edb2014-03-10 17:42:56 -07004052 }
4053 }
Eric Laurentd4692962014-05-05 18:13:44 -07004054 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07004055 for (size_t i = 0; i < mHwModules.size(); i++)
4056 {
4057 if (mHwModules[i]->mHandle == 0) {
4058 continue;
4059 }
4060 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
4061 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004062 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004063 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004064 ALOGV("checkOutputsForDevice(): "
4065 "clearing direct output profile %zu on module %zu", j, i);
François Gaffie112b0af2015-11-19 16:13:25 +01004066 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004067 }
4068 }
4069 }
4070 }
4071 return NO_ERROR;
4072}
4073
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004074status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004075 audio_policy_dev_state_t state,
4076 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004077 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004078{
Paul McLean9080a4c2015-06-18 08:24:02 -07004079 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004080 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004081
4082 if (audio_device_is_digital(device)) {
4083 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004084 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004085 }
4086
Eric Laurentd4692962014-05-05 18:13:44 -07004087 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4088 // first list already open inputs that can be routed to this device
4089 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4090 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004091 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004092 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4093 inputs.add(mInputs.keyAt(input_index));
4094 }
4095 }
4096
4097 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004098 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07004099 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
4100 {
4101 if (mHwModules[module_idx]->mHandle == 0) {
4102 continue;
4103 }
4104 for (size_t profile_index = 0;
4105 profile_index < mHwModules[module_idx]->mInputProfiles.size();
4106 profile_index++)
4107 {
Eric Laurent275e8e92014-11-30 15:14:47 -08004108 sp<IOProfile> profile = mHwModules[module_idx]->mInputProfiles[profile_index];
4109
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004110 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004111 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004112 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004113 profiles.add(profile);
4114 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
4115 profile_index, module_idx);
4116 }
Eric Laurentd4692962014-05-05 18:13:44 -07004117 }
4118 }
4119 }
4120
4121 if (profiles.isEmpty() && inputs.isEmpty()) {
4122 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4123 return BAD_VALUE;
4124 }
4125
4126 // open inputs for matching profiles if needed. Direct inputs are also opened to
4127 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4128 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4129
Eric Laurent1c333e22014-05-20 10:48:17 -07004130 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07004131 // nothing to do if one input is already opened for this profile
4132 size_t input_index;
4133 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4134 desc = mInputs.valueAt(input_index);
4135 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004136 if (audio_device_is_digital(device)) {
4137 devDesc->importAudioPort(profile);
4138 }
Eric Laurentd4692962014-05-05 18:13:44 -07004139 break;
4140 }
4141 }
4142 if (input_index != mInputs.size()) {
4143 continue;
4144 }
4145
4146 ALOGV("opening input for device 0x%X with params %s", device, address.string());
4147 desc = new AudioInputDescriptor(profile);
4148 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07004149 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4150 config.sample_rate = desc->mSamplingRate;
4151 config.channel_mask = desc->mChannelMask;
4152 config.format = desc->mFormat;
4153 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent83efe1c2017-07-09 16:51:08 -07004154
4155 ALOGV("opening inputput for device %08x with params %s profile %p name %s",
4156 desc->mDevice, address.string(), profile.get(), profile->getName().string());
4157
Eric Laurent322b4d22015-04-03 15:57:54 -07004158 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07004159 &input,
4160 &config,
4161 &desc->mDevice,
4162 address,
4163 AUDIO_SOURCE_MIC,
4164 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07004165
Eric Laurentcf2c0212014-07-25 16:20:43 -07004166 if (status == NO_ERROR) {
4167 desc->mSamplingRate = config.sample_rate;
4168 desc->mChannelMask = config.channel_mask;
4169 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07004170
Eric Laurentd4692962014-05-05 18:13:44 -07004171 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004172 char *param = audio_device_address_to_parameter(device, address);
4173 mpClientInterface->setParameters(input, String8(param));
4174 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004175 }
Phil Burk00eeb322016-03-31 12:41:00 -07004176 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004177 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004178 ALOGW("checkInputsForDevice() direct input missing param");
4179 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004180 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004181 }
4182
4183 if (input != 0) {
4184 addInput(input, desc);
4185 }
4186 } // endif input != 0
4187
Eric Laurentcf2c0212014-07-25 16:20:43 -07004188 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004189 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004190 profiles.removeAt(profile_index);
4191 profile_index--;
4192 } else {
4193 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004194 if (audio_device_is_digital(device)) {
4195 devDesc->importAudioPort(profile);
4196 }
Eric Laurentd4692962014-05-05 18:13:44 -07004197 ALOGV("checkInputsForDevice(): adding input %d", input);
4198 }
4199 } // end scan profiles
4200
4201 if (profiles.isEmpty()) {
4202 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4203 return BAD_VALUE;
4204 }
4205 } else {
4206 // Disconnect
4207 // check if one opened input is not needed any more after disconnecting one device
4208 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4209 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004210 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004211 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4212 mInputs.keyAt(input_index));
4213 inputs.add(mInputs.keyAt(input_index));
4214 }
4215 }
4216 // Clear any profiles associated with the disconnected device.
4217 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
4218 if (mHwModules[module_index]->mHandle == 0) {
4219 continue;
4220 }
4221 for (size_t profile_index = 0;
4222 profile_index < mHwModules[module_index]->mInputProfiles.size();
4223 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004224 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004225 if (profile->supportDevice(device)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004226 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07004227 profile_index, module_index);
François Gaffie112b0af2015-11-19 16:13:25 +01004228 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004229 }
4230 }
4231 }
4232 } // end disconnect
4233
4234 return NO_ERROR;
4235}
4236
4237
Eric Laurente0720872014-03-11 09:30:41 -07004238void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004239{
4240 ALOGV("closeOutput(%d)", output);
4241
Eric Laurentc75307b2015-03-17 15:29:32 -07004242 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004243 if (outputDesc == NULL) {
4244 ALOGW("closeOutput() unknown output %d", output);
4245 return;
4246 }
François Gaffie036e1e92015-03-19 10:16:24 +01004247 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004248
Eric Laurente552edb2014-03-10 17:42:56 -07004249 // look for duplicated outputs connected to the output being removed.
4250 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004251 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004252 if (dupOutputDesc->isDuplicated() &&
4253 (dupOutputDesc->mOutput1 == outputDesc ||
4254 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004255 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004256 if (dupOutputDesc->mOutput1 == outputDesc) {
4257 outputDesc2 = dupOutputDesc->mOutput2;
4258 } else {
4259 outputDesc2 = dupOutputDesc->mOutput1;
4260 }
4261 // As all active tracks on duplicated output will be deleted,
4262 // and as they were also referenced on the other output, the reference
4263 // count for their stream type must be adjusted accordingly on
4264 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07004265 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004266 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07004267 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004268 }
4269 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4270 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4271
4272 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004273 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004274 }
4275 }
4276
Eric Laurent05b90f82014-08-27 15:32:29 -07004277 nextAudioPortGeneration();
4278
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004279 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004280 if (index >= 0) {
4281 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004282 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004283 mAudioPatches.removeItemsAt(index);
4284 mpClientInterface->onAudioPatchListUpdate();
4285 }
4286
Eric Laurente552edb2014-03-10 17:42:56 -07004287 AudioParameter param;
4288 param.add(String8("closing"), String8("true"));
4289 mpClientInterface->setParameters(output, param.toString());
4290
4291 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01004292 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004293 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004294}
4295
4296void AudioPolicyManager::closeInput(audio_io_handle_t input)
4297{
4298 ALOGV("closeInput(%d)", input);
4299
4300 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4301 if (inputDesc == NULL) {
4302 ALOGW("closeInput() unknown input %d", input);
4303 return;
4304 }
4305
Eric Laurent6a94d692014-05-20 11:18:06 -07004306 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004307
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004308 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004309 if (index >= 0) {
4310 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004311 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004312 mAudioPatches.removeItemsAt(index);
4313 mpClientInterface->onAudioPatchListUpdate();
4314 }
4315
4316 mpClientInterface->closeInput(input);
4317 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004318}
4319
Eric Laurentc75307b2015-03-17 15:29:32 -07004320SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4321 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004322 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004323{
4324 SortedVector<audio_io_handle_t> outputs;
4325
4326 ALOGVV("getOutputsForDevice() device %04x", device);
4327 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004328 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004329 i, openOutputs.valueAt(i)->isDuplicated(),
4330 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004331 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4332 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4333 outputs.add(openOutputs.keyAt(i));
4334 }
4335 }
4336 return outputs;
4337}
4338
Eric Laurente0720872014-03-11 09:30:41 -07004339bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
François Gaffie53615e22015-03-19 09:24:12 +01004340 SortedVector<audio_io_handle_t>& outputs2)
Eric Laurente552edb2014-03-10 17:42:56 -07004341{
4342 if (outputs1.size() != outputs2.size()) {
4343 return false;
4344 }
4345 for (size_t i = 0; i < outputs1.size(); i++) {
4346 if (outputs1[i] != outputs2[i]) {
4347 return false;
4348 }
4349 }
4350 return true;
4351}
4352
Eric Laurente0720872014-03-11 09:30:41 -07004353void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004354{
4355 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4356 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4357 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4358 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4359
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004360 // also take into account external policy-related changes: add all outputs which are
4361 // associated with policies in the "before" and "after" output vectors
4362 ALOGVV("checkOutputForStrategy(): policy related outputs");
4363 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004364 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004365 if (desc != 0 && desc->mPolicyMix != NULL) {
4366 srcOutputs.add(desc->mIoHandle);
4367 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4368 }
4369 }
4370 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004371 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004372 if (desc != 0 && desc->mPolicyMix != NULL) {
4373 dstOutputs.add(desc->mIoHandle);
4374 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4375 }
4376 }
4377
Eric Laurente552edb2014-03-10 17:42:56 -07004378 if (!vectorsEqual(srcOutputs,dstOutputs)) {
4379 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4380 strategy, srcOutputs[0], dstOutputs[0]);
4381 // mute strategy while moving tracks from one output to another
4382 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004383 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
François Gaffiead3183e2015-03-18 16:55:35 +01004384 if (isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004385 setStrategyMute(strategy, true, desc);
4386 setStrategyMute(strategy, false, desc, MUTE_TIME_MS, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004387 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004388 sp<AudioSourceDescriptor> source =
4389 getSourceForStrategyOnOutput(srcOutputs[i], strategy);
4390 if (source != 0){
4391 connectAudioSource(source);
4392 }
Eric Laurente552edb2014-03-10 17:42:56 -07004393 }
4394
4395 // Move effects associated to this strategy from previous output to new output
4396 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004397 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004398 }
4399 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004400 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004401 if (getStrategy((audio_stream_type_t)i) == strategy) {
4402 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004403 }
4404 }
4405 }
4406}
4407
Eric Laurente0720872014-03-11 09:30:41 -07004408void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004409{
François Gaffie2110e042015-03-24 08:41:51 +01004410 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004411 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004412 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004413 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004414 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004415 checkOutputForStrategy(STRATEGY_SONIFICATION);
4416 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004417 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004418 checkOutputForStrategy(STRATEGY_MEDIA);
4419 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004420 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004421}
4422
Eric Laurente0720872014-03-11 09:30:41 -07004423void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004424{
François Gaffie53615e22015-03-19 09:24:12 +01004425 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Eric Laurente552edb2014-03-10 17:42:56 -07004426 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004427 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004428 return;
4429 }
4430
Eric Laurent3a4311c2014-03-17 12:00:47 -07004431 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004432 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4433 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4434 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004435
4436 // if suspended, restore A2DP output if:
4437 // ((SCO device is NOT connected) ||
4438 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4439 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004440 //
Eric Laurentf732e072016-08-03 19:30:28 -07004441 // if not suspended, suspend A2DP output if:
4442 // (SCO device is connected) &&
4443 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4444 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004445 //
4446 if (mA2dpSuspended) {
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->restoreOutput(a2dpOutput);
4456 mA2dpSuspended = false;
4457 }
4458 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004459 if (isScoConnected &&
4460 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4461 AUDIO_POLICY_FORCE_BT_SCO) ||
4462 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4463 AUDIO_POLICY_FORCE_BT_SCO) ||
4464 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004465 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004466
4467 mpClientInterface->suspendOutput(a2dpOutput);
4468 mA2dpSuspended = true;
4469 }
4470 }
4471}
4472
Eric Laurentc75307b2015-03-17 15:29:32 -07004473audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4474 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004475{
4476 audio_devices_t device = AUDIO_DEVICE_NONE;
4477
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004478 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004479 if (index >= 0) {
4480 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4481 if (patchDesc->mUid != mUidCached) {
4482 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004483 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004484 return outputDesc->device();
4485 }
4486 }
4487
Eric Laurente552edb2014-03-10 17:42:56 -07004488 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004489 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004490 // use device for strategy enforced audible
4491 // 2: we are in call or the strategy phone is active on the output:
4492 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004493 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004494 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004495 // 4: the strategy for enforced audible is active but not enforced on the output:
4496 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004497 // 5: the strategy accessibility is active on the output:
4498 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004499 // 6: the strategy "respectful" sonification is active on the output:
4500 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004501 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004502 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004503 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004504 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004505 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004506 // use device for strategy t-t-s
François Gaffiead3183e2015-03-18 16:55:35 +01004507 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004508 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004509 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4510 } else if (isInCall() ||
François Gaffiead3183e2015-03-18 16:55:35 +01004511 isStrategyActive(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004512 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004513 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004514 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004515 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
4516 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004517 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4518 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004519 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004520 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004521 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004522 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004523 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004524 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004525 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004526 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004527 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004528 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004529 }
4530
Eric Laurent1c333e22014-05-20 10:48:17 -07004531 ALOGV("getNewOutputDevice() selected device %x", device);
4532 return device;
4533}
4534
Eric Laurentfb66dd92016-01-28 18:32:03 -08004535audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004536{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004537 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004538
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004539 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004540 if (index >= 0) {
4541 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4542 if (patchDesc->mUid != mUidCached) {
4543 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004544 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004545 return inputDesc->mDevice;
4546 }
4547 }
4548
Eric Laurentfb66dd92016-01-28 18:32:03 -08004549 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
4550 if (isInCall()) {
4551 device = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
4552 } else if (source != AUDIO_SOURCE_DEFAULT) {
4553 device = getDeviceAndMixForInputSource(source);
4554 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004555
Eric Laurente552edb2014-03-10 17:42:56 -07004556 return device;
4557}
4558
Eric Laurent794fde22016-03-11 09:50:45 -08004559bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4560 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004561 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004562}
4563
Eric Laurente0720872014-03-11 09:30:41 -07004564uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004565 return (uint32_t)getStrategy(stream);
4566}
4567
Eric Laurente0720872014-03-11 09:30:41 -07004568audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004569 // By checking the range of stream before calling getStrategy, we avoid
4570 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4571 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004572 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004573 return AUDIO_DEVICE_NONE;
4574 }
Eric Laurent28d09f02016-03-08 10:43:05 -08004575 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004576 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4577 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004578 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004579 }
Eric Laurent794fde22016-03-11 09:50:45 -08004580 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004581 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004582 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Eric Laurent28d09f02016-03-08 10:43:05 -08004583 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(curDevices, mOutputs);
4584 for (size_t i = 0; i < outputs.size(); i++) {
4585 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent794fde22016-03-11 09:50:45 -08004586 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004587 curDevices |= outputDesc->device();
4588 }
4589 }
4590 devices |= curDevices;
Eric Laurente552edb2014-03-10 17:42:56 -07004591 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004592
4593 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4594 and doesn't really need to.*/
4595 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4596 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4597 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4598 }
Eric Laurente552edb2014-03-10 17:42:56 -07004599 return devices;
4600}
4601
François Gaffie2110e042015-03-24 08:41:51 +01004602routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4603{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004604 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004605 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004606}
4607
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004608uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4609 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004610 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4611 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4612 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004613 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4614 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4615 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004616 // usage to strategy mapping
François Gaffie2110e042015-03-24 08:41:51 +01004617 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004618}
4619
Eric Laurente0720872014-03-11 09:30:41 -07004620void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004621 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004622 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004623 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4624 updateDevicesAndOutputs();
4625 break;
4626 default:
4627 break;
4628 }
4629}
4630
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004631uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004632
4633 // skip beacon mute management if a dedicated TTS output is available
4634 if (mTtsOutputAvailable) {
4635 return 0;
4636 }
4637
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004638 switch(event) {
4639 case STARTING_OUTPUT:
4640 mBeaconMuteRefCount++;
4641 break;
4642 case STOPPING_OUTPUT:
4643 if (mBeaconMuteRefCount > 0) {
4644 mBeaconMuteRefCount--;
4645 }
4646 break;
4647 case STARTING_BEACON:
4648 mBeaconPlayingRefCount++;
4649 break;
4650 case STOPPING_BEACON:
4651 if (mBeaconPlayingRefCount > 0) {
4652 mBeaconPlayingRefCount--;
4653 }
4654 break;
4655 }
4656
4657 if (mBeaconMuteRefCount > 0) {
4658 // any playback causes beacon to be muted
4659 return setBeaconMute(true);
4660 } else {
4661 // no other playback: unmute when beacon starts playing, mute when it stops
4662 return setBeaconMute(mBeaconPlayingRefCount == 0);
4663 }
4664}
4665
4666uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4667 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4668 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4669 // keep track of muted state to avoid repeating mute/unmute operations
4670 if (mBeaconMuted != mute) {
4671 // mute/unmute AUDIO_STREAM_TTS on all outputs
4672 ALOGV("\t muting %d", mute);
4673 uint32_t maxLatency = 0;
4674 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004675 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004676 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07004677 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004678 0 /*delay*/, AUDIO_DEVICE_NONE);
4679 const uint32_t latency = desc->latency() * 2;
4680 if (latency > maxLatency) {
4681 maxLatency = latency;
4682 }
4683 }
4684 mBeaconMuted = mute;
4685 return maxLatency;
4686 }
4687 return 0;
4688}
4689
Eric Laurente0720872014-03-11 09:30:41 -07004690audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01004691 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004692{
Paul McLeanaa981192015-03-21 09:55:15 -07004693 // Routing
4694 // see if we have an explicit route
4695 // scan the whole RouteMap, for each entry, convert the stream type to a strategy
4696 // (getStrategy(stream)).
4697 // if the strategy from the stream type in the RouteMap is the same as the argument above,
Eric Laurentad2e7b92017-09-14 20:06:42 -07004698 // and activity count is non-zero and the device in the route descriptor is available
4699 // then select this device.
Paul McLeanaa981192015-03-21 09:55:15 -07004700 for (size_t routeIndex = 0; routeIndex < mOutputRoutes.size(); routeIndex++) {
4701 sp<SessionRoute> route = mOutputRoutes.valueAt(routeIndex);
Eric Laurent28d09f02016-03-08 10:43:05 -08004702 routing_strategy routeStrategy = getStrategy(route->mStreamType);
Eric Laurentad2e7b92017-09-14 20:06:42 -07004703 if ((routeStrategy == strategy) && route->isActive() &&
4704 (mAvailableOutputDevices.indexOf(route->mDeviceDescriptor) >= 0)) {
Paul McLeanaa981192015-03-21 09:55:15 -07004705 return route->mDeviceDescriptor->type();
4706 }
4707 }
4708
Eric Laurente552edb2014-03-10 17:42:56 -07004709 if (fromCache) {
4710 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4711 strategy, mDeviceForStrategy[strategy]);
4712 return mDeviceForStrategy[strategy];
4713 }
François Gaffie2110e042015-03-24 08:41:51 +01004714 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07004715}
4716
Eric Laurente0720872014-03-11 09:30:41 -07004717void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004718{
4719 for (int i = 0; i < NUM_STRATEGIES; i++) {
4720 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4721 }
4722 mPreviousOutputs = mOutputs;
4723}
4724
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004725uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004726 audio_devices_t prevDevice,
4727 uint32_t delayMs)
4728{
4729 // mute/unmute strategies using an incompatible device combination
4730 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4731 // if unmuting, unmute only after the specified delay
4732 if (outputDesc->isDuplicated()) {
4733 return 0;
4734 }
4735
4736 uint32_t muteWaitMs = 0;
4737 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004738 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004739
4740 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4741 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07004742 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07004743 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4744 bool doMute = false;
4745
4746 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4747 doMute = true;
4748 outputDesc->mStrategyMutedByDevice[i] = true;
4749 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4750 doMute = true;
4751 outputDesc->mStrategyMutedByDevice[i] = false;
4752 }
Eric Laurent99401132014-05-07 19:48:15 -07004753 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004754 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004755 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004756 // skip output if it does not share any device with current output
4757 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4758 == AUDIO_DEVICE_NONE) {
4759 continue;
4760 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07004761 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07004762 mute ? "muting" : "unmuting", i, curDevice);
4763 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01004764 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004765 if (mute) {
4766 // FIXME: should not need to double latency if volume could be applied
4767 // immediately by the audioflinger mixer. We must account for the delay
4768 // between now and the next time the audioflinger thread for this output
4769 // will process a buffer (which corresponds to one buffer size,
4770 // usually 1/2 or 1/4 of the latency).
4771 if (muteWaitMs < desc->latency() * 2) {
4772 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004773 }
4774 }
4775 }
4776 }
4777 }
4778 }
4779
Eric Laurent99401132014-05-07 19:48:15 -07004780 // temporary mute output if device selection changes to avoid volume bursts due to
4781 // different per device volumes
4782 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07004783 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
4784 // temporary mute duration is conservatively set to 4 times the reported latency
4785 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
4786 if (muteWaitMs < tempMuteWaitMs) {
4787 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07004788 }
Eric Laurentdc462862016-07-19 12:29:53 -07004789
Eric Laurent99401132014-05-07 19:48:15 -07004790 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01004791 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07004792 // make sure that we do not start the temporary mute period too early in case of
4793 // delayed device change
4794 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004795 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07004796 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07004797 }
4798 }
4799 }
4800
Eric Laurente552edb2014-03-10 17:42:56 -07004801 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4802 if (muteWaitMs > delayMs) {
4803 muteWaitMs -= delayMs;
4804 usleep(muteWaitMs * 1000);
4805 return muteWaitMs;
4806 }
4807 return 0;
4808}
4809
Eric Laurentc75307b2015-03-17 15:29:32 -07004810uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004811 audio_devices_t device,
4812 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004813 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004814 audio_patch_handle_t *patchHandle,
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00004815 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004816{
Eric Laurentc75307b2015-03-17 15:29:32 -07004817 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004818 AudioParameter param;
4819 uint32_t muteWaitMs;
4820
4821 if (outputDesc->isDuplicated()) {
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00004822 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs);
4823 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004824 return muteWaitMs;
4825 }
4826 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4827 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07004828 if ((device != AUDIO_DEVICE_NONE) &&
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00004829 ((device & outputDesc->supportedDevices()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004830 return 0;
4831 }
4832
4833 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07004834 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004835
4836 audio_devices_t prevDevice = outputDesc->mDevice;
4837
Paul McLeanaa981192015-03-21 09:55:15 -07004838 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004839
4840 if (device != AUDIO_DEVICE_NONE) {
4841 outputDesc->mDevice = device;
4842 }
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00004843 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004844
4845 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07004846 // the requested device is AUDIO_DEVICE_NONE
4847 // OR the requested device is the same as current device
4848 // AND force is not specified
4849 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07004850 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07004851 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
4852 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004853 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004854 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004855 return muteWaitMs;
4856 }
4857
4858 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004859
Eric Laurente552edb2014-03-10 17:42:56 -07004860 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004861 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004862 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004863 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07004864 DeviceVector deviceList;
4865 if ((address == NULL) || (strlen(address) == 0)) {
4866 deviceList = mAvailableOutputDevices.getDevicesFromType(device);
4867 } else {
4868 deviceList = mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
4869 }
4870
Eric Laurent1c333e22014-05-20 10:48:17 -07004871 if (!deviceList.isEmpty()) {
4872 struct audio_patch patch;
4873 outputDesc->toAudioPortConfig(&patch.sources[0]);
4874 patch.num_sources = 1;
4875 patch.num_sinks = 0;
4876 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4877 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004878 patch.num_sinks++;
4879 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004880 ssize_t index;
4881 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4882 index = mAudioPatches.indexOfKey(*patchHandle);
4883 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004884 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004885 }
4886 sp< AudioPatch> patchDesc;
4887 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4888 if (index >= 0) {
4889 patchDesc = mAudioPatches.valueAt(index);
4890 afPatchHandle = patchDesc->mAfPatchHandle;
4891 }
4892
Eric Laurent1c333e22014-05-20 10:48:17 -07004893 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004894 &afPatchHandle,
4895 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004896 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4897 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004898 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004899 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004900 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01004901 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004902 addAudioPatch(patchDesc->mHandle, patchDesc);
4903 } else {
4904 patchDesc->mPatch = patch;
4905 }
4906 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07004907 if (patchHandle) {
4908 *patchHandle = patchDesc->mHandle;
4909 }
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004910 outputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004911 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004912 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004913 }
4914 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004915
4916 // inform all input as well
4917 for (size_t i = 0; i < mInputs.size(); i++) {
4918 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01004919 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08004920 AudioParameter inputCmd = AudioParameter();
4921 ALOGV("%s: inform input %d of device:%d", __func__,
4922 inputDescriptor->mIoHandle, device);
4923 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4924 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4925 inputCmd.toString(),
4926 delayMs);
4927 }
4928 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004929 }
Eric Laurente552edb2014-03-10 17:42:56 -07004930
4931 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07004932 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004933
4934 return muteWaitMs;
4935}
4936
Eric Laurentc75307b2015-03-17 15:29:32 -07004937status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07004938 int delayMs,
4939 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004940{
Eric Laurent6a94d692014-05-20 11:18:06 -07004941 ssize_t index;
4942 if (patchHandle) {
4943 index = mAudioPatches.indexOfKey(*patchHandle);
4944 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004945 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004946 }
4947 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004948 return INVALID_OPERATION;
4949 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004950 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4951 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004952 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07004953 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07004954 removeAudioPatch(patchDesc->mHandle);
4955 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004956 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004957 return status;
4958}
4959
4960status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4961 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004962 bool force,
4963 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004964{
4965 status_t status = NO_ERROR;
4966
Eric Laurent1f2f2232014-06-02 12:01:23 -07004967 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004968 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4969 inputDesc->mDevice = device;
4970
4971 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4972 if (!deviceList.isEmpty()) {
4973 struct audio_patch patch;
4974 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004975 // AUDIO_SOURCE_HOTWORD is for internal use only:
4976 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004977 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
Eric Laurent599c7582015-12-07 18:05:55 -08004978 !inputDesc->isSoundTrigger()) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004979 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4980 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004981 patch.num_sinks = 1;
4982 //only one input device for now
4983 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004984 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004985 ssize_t index;
4986 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4987 index = mAudioPatches.indexOfKey(*patchHandle);
4988 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004989 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004990 }
4991 sp< AudioPatch> patchDesc;
4992 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4993 if (index >= 0) {
4994 patchDesc = mAudioPatches.valueAt(index);
4995 afPatchHandle = patchDesc->mAfPatchHandle;
4996 }
4997
Eric Laurent1c333e22014-05-20 10:48:17 -07004998 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004999 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07005000 0);
5001 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07005002 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005003 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005004 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01005005 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005006 addAudioPatch(patchDesc->mHandle, patchDesc);
5007 } else {
5008 patchDesc->mPatch = patch;
5009 }
5010 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07005011 if (patchHandle) {
5012 *patchHandle = patchDesc->mHandle;
5013 }
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005014 inputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005015 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005016 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005017 }
5018 }
5019 }
5020 return status;
5021}
5022
Eric Laurent6a94d692014-05-20 11:18:06 -07005023status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5024 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005025{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005026 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005027 ssize_t index;
5028 if (patchHandle) {
5029 index = mAudioPatches.indexOfKey(*patchHandle);
5030 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005031 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005032 }
5033 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005034 return INVALID_OPERATION;
5035 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005036 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5037 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005038 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005039 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005040 removeAudioPatch(patchDesc->mHandle);
5041 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005042 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005043 return status;
5044}
5045
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005046sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005047 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005048 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005049 audio_format_t& format,
5050 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005051 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005052{
5053 // Choose an input profile based on the requested capture parameters: select the first available
5054 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005055 //
5056 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5057 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005058
5059 for (size_t i = 0; i < mHwModules.size(); i++)
5060 {
5061 if (mHwModules[i]->mHandle == 0) {
5062 continue;
5063 }
5064 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
5065 {
Eric Laurent1c333e22014-05-20 10:48:17 -07005066 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07005067 // profile->log();
Eric Laurent275e8e92014-11-30 15:14:47 -08005068 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07005069 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005070 format,
5071 &format /*updatedFormat*/,
5072 channelMask,
5073 &channelMask /*updatedChannelMask*/,
5074 (audio_output_flags_t) flags)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005075
Eric Laurente552edb2014-03-10 17:42:56 -07005076 return profile;
5077 }
5078 }
5079 }
5080 return NULL;
5081}
5082
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005083
5084audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005085 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005086{
François Gaffie036e1e92015-03-19 10:16:24 +01005087 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5088 audio_devices_t selectedDeviceFromMix =
5089 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005090
François Gaffie036e1e92015-03-19 10:16:24 +01005091 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5092 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005093 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005094 return getDeviceForInputSource(inputSource);
5095}
5096
5097audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5098{
Eric Laurentad2e7b92017-09-14 20:06:42 -07005099 // Routing
5100 // Scan the whole RouteMap to see if we have an explicit route:
5101 // if the input source in the RouteMap is the same as the argument above,
5102 // and activity count is non-zero and the device in the route descriptor is available
5103 // then select this device.
Paul McLean466dc8e2015-04-17 13:15:36 -06005104 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
5105 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
Eric Laurentad2e7b92017-09-14 20:06:42 -07005106 if ((inputSource == route->mSource) && route->isActive() &&
5107 (mAvailableInputDevices.indexOf(route->mDeviceDescriptor) >= 0)) {
Paul McLean466dc8e2015-04-17 13:15:36 -06005108 return route->mDeviceDescriptor->type();
5109 }
5110 }
5111
5112 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005113}
5114
Eric Laurente0720872014-03-11 09:30:41 -07005115float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005116 int index,
5117 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005118{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005119 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005120
5121 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5122 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5123 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5124 // the ringtone volume
5125 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5126 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5127 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5128 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5129 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5130 }
5131
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005132 // in-call: always cap earpiece volume by voice volume + some low headroom
5133 if ((stream != AUDIO_STREAM_VOICE_CALL) && (device & AUDIO_DEVICE_OUT_EARPIECE) && isInCall()) {
5134 switch (stream) {
5135 case AUDIO_STREAM_SYSTEM:
5136 case AUDIO_STREAM_RING:
5137 case AUDIO_STREAM_MUSIC:
5138 case AUDIO_STREAM_ALARM:
5139 case AUDIO_STREAM_NOTIFICATION:
5140 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5141 case AUDIO_STREAM_DTMF:
5142 case AUDIO_STREAM_ACCESSIBILITY: {
5143 const float maxVoiceVolDb = computeVolume(AUDIO_STREAM_VOICE_CALL, index, device)
5144 + IN_CALL_EARPIECE_HEADROOM_DB;
5145 if (volumeDB > maxVoiceVolDb) {
5146 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5147 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5148 volumeDB = maxVoiceVolDb;
5149 }
5150 } break;
5151 default:
5152 break;
5153 }
5154 }
5155
Eric Laurente552edb2014-03-10 17:42:56 -07005156 // if a headset is connected, apply the following rules to ring tones and notifications
5157 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005158 // - always attenuate notifications volume by 6dB
5159 // - attenuate ring tones volume by 6dB unless music is not playing and
5160 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005161 // - if music is playing, always limit the volume to current music volume,
5162 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005163 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005164 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5165 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5166 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005167 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
5168 AUDIO_DEVICE_OUT_USB_HEADSET)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005169 ((stream_strategy == STRATEGY_SONIFICATION)
5170 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005171 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005172 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005173 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005174 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005175 // when the phone is ringing we must consider that music could have been paused just before
5176 // by the music application and behave as if music was active if the last music track was
5177 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005178 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005179 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005180 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005181 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005182 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005183 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5184 musicDevice),
5185 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005186 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5187 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005188 if (volumeDB > minVolDB) {
5189 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005190 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005191 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005192 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5193 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5194 // on A2DP, also ensure notification volume is not too low compared to media when
5195 // intended to be played
5196 if ((volumeDB > -96.0f) &&
5197 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5198 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5199 stream, device,
5200 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5201 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5202 }
5203 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005204 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5205 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005206 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005207 }
5208 }
5209
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005210 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005211}
5212
Eric Laurente0720872014-03-11 09:30:41 -07005213status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005214 int index,
5215 const sp<AudioOutputDescriptor>& outputDesc,
5216 audio_devices_t device,
5217 int delayMs,
5218 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005219{
Eric Laurente552edb2014-03-10 17:42:56 -07005220 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005221 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005222 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005223 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005224 return NO_ERROR;
5225 }
François Gaffie2110e042015-03-24 08:41:51 +01005226 audio_policy_forced_cfg_t forceUseForComm =
5227 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005228 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005229 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5230 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005231 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005232 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005233 return INVALID_OPERATION;
5234 }
5235
Eric Laurentc75307b2015-03-17 15:29:32 -07005236 if (device == AUDIO_DEVICE_NONE) {
5237 device = outputDesc->device();
5238 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005239
Eric Laurentffbc80f2015-03-18 18:30:19 -07005240 float volumeDb = computeVolume(stream, index, device);
Eric Laurentc75307b2015-03-17 15:29:32 -07005241 if (outputDesc->isFixedVolume(device)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005242 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005243 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005244
Eric Laurentffbc80f2015-03-18 18:30:19 -07005245 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005246
Eric Laurent3b73df72014-03-11 09:06:29 -07005247 if (stream == AUDIO_STREAM_VOICE_CALL ||
5248 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005249 float voiceVolume;
5250 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005251 if (stream == AUDIO_STREAM_VOICE_CALL) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005252 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005253 } else {
5254 voiceVolume = 1.0;
5255 }
5256
Eric Laurent18fba842016-03-31 14:41:26 -07005257 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005258 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5259 mLastVoiceVolume = voiceVolume;
5260 }
5261 }
5262
5263 return NO_ERROR;
5264}
5265
Eric Laurentc75307b2015-03-17 15:29:32 -07005266void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5267 audio_devices_t device,
5268 int delayMs,
5269 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005270{
Eric Laurentc75307b2015-03-17 15:29:32 -07005271 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005272
Eric Laurent794fde22016-03-11 09:50:45 -08005273 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005274 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005275 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005276 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005277 device,
5278 delayMs,
5279 force);
5280 }
5281}
5282
Eric Laurente0720872014-03-11 09:30:41 -07005283void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005284 bool on,
5285 const sp<AudioOutputDescriptor>& outputDesc,
5286 int delayMs,
5287 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005288{
Eric Laurent72249d52015-06-08 11:12:15 -07005289 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5290 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005291 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005292 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005293 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005294 }
5295 }
5296}
5297
Eric Laurente0720872014-03-11 09:30:41 -07005298void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005299 bool on,
5300 const sp<AudioOutputDescriptor>& outputDesc,
5301 int delayMs,
5302 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005303{
Eric Laurente552edb2014-03-10 17:42:56 -07005304 if (device == AUDIO_DEVICE_NONE) {
5305 device = outputDesc->device();
5306 }
5307
Eric Laurentc75307b2015-03-17 15:29:32 -07005308 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5309 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005310
5311 if (on) {
5312 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005313 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005314 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005315 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005316 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005317 }
5318 }
5319 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5320 outputDesc->mMuteCount[stream]++;
5321 } else {
5322 if (outputDesc->mMuteCount[stream] == 0) {
5323 ALOGV("setStreamMute() unmuting non muted stream!");
5324 return;
5325 }
5326 if (--outputDesc->mMuteCount[stream] == 0) {
5327 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005328 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005329 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005330 device,
5331 delayMs);
5332 }
5333 }
5334}
5335
Eric Laurente0720872014-03-11 09:30:41 -07005336void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005337 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005338{
Eric Laurent87ffa392015-05-22 10:32:38 -07005339 if(!hasPrimaryOutput()) {
5340 return;
5341 }
5342
Eric Laurente552edb2014-03-10 17:42:56 -07005343 // if the stream pertains to sonification strategy and we are in call we must
5344 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5345 // in the device used for phone strategy and play the tone if the selected device does not
5346 // interfere with the device used for phone strategy
5347 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5348 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005349 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005350 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5351 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005352 sp<SwAudioOutputDescriptor> outputDesc = mPrimaryOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07005353 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5354 stream, starting, outputDesc->mDevice, stateChange);
5355 if (outputDesc->mRefCount[stream]) {
5356 int muteCount = 1;
5357 if (stateChange) {
5358 muteCount = outputDesc->mRefCount[stream];
5359 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005360 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005361 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5362 for (int i = 0; i < muteCount; i++) {
5363 setStreamMute(stream, starting, mPrimaryOutput);
5364 }
5365 } else {
5366 ALOGV("handleIncallSonification() high visibility");
5367 if (outputDesc->device() &
5368 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5369 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5370 for (int i = 0; i < muteCount; i++) {
5371 setStreamMute(stream, starting, mPrimaryOutput);
5372 }
5373 }
5374 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005375 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5376 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005377 } else {
5378 mpClientInterface->stopTone();
5379 }
5380 }
5381 }
5382 }
5383}
5384
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005385audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5386{
5387 // flags to stream type mapping
5388 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5389 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5390 }
5391 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5392 return AUDIO_STREAM_BLUETOOTH_SCO;
5393 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005394 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5395 return AUDIO_STREAM_TTS;
5396 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005397
5398 // usage to stream type mapping
5399 switch (attr->usage) {
5400 case AUDIO_USAGE_MEDIA:
5401 case AUDIO_USAGE_GAME:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005402 case AUDIO_USAGE_ASSISTANT:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005403 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5404 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005405 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5406 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005407 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5408 return AUDIO_STREAM_SYSTEM;
5409 case AUDIO_USAGE_VOICE_COMMUNICATION:
5410 return AUDIO_STREAM_VOICE_CALL;
5411
5412 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5413 return AUDIO_STREAM_DTMF;
5414
5415 case AUDIO_USAGE_ALARM:
5416 return AUDIO_STREAM_ALARM;
5417 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5418 return AUDIO_STREAM_RING;
5419
5420 case AUDIO_USAGE_NOTIFICATION:
5421 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5422 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5423 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5424 case AUDIO_USAGE_NOTIFICATION_EVENT:
5425 return AUDIO_STREAM_NOTIFICATION;
5426
5427 case AUDIO_USAGE_UNKNOWN:
5428 default:
5429 return AUDIO_STREAM_MUSIC;
5430 }
5431}
Eric Laurente83b55d2014-11-14 10:06:21 -08005432
François Gaffie53615e22015-03-19 09:24:12 +01005433bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5434{
Eric Laurente83b55d2014-11-14 10:06:21 -08005435 // has flags that map to a strategy?
5436 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5437 return true;
5438 }
5439
5440 // has known usage?
5441 switch (paa->usage) {
5442 case AUDIO_USAGE_UNKNOWN:
5443 case AUDIO_USAGE_MEDIA:
5444 case AUDIO_USAGE_VOICE_COMMUNICATION:
5445 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5446 case AUDIO_USAGE_ALARM:
5447 case AUDIO_USAGE_NOTIFICATION:
5448 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5449 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5450 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5451 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5452 case AUDIO_USAGE_NOTIFICATION_EVENT:
5453 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5454 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5455 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5456 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005457 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005458 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005459 break;
5460 default:
5461 return false;
5462 }
5463 return true;
5464}
5465
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005466bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005467 routing_strategy strategy, uint32_t inPastMs,
5468 nsecs_t sysTime) const
5469{
5470 if ((sysTime == 0) && (inPastMs != 0)) {
5471 sysTime = systemTime();
5472 }
Eric Laurent794fde22016-03-11 09:50:45 -08005473 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005474 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5475 (NUM_STRATEGIES == strategy)) &&
5476 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5477 return true;
5478 }
5479 }
5480 return false;
5481}
5482
François Gaffie2110e042015-03-24 08:41:51 +01005483audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5484{
5485 return mEngine->getForceUse(usage);
5486}
5487
5488bool AudioPolicyManager::isInCall()
5489{
5490 return isStateInCall(mEngine->getPhoneState());
5491}
5492
5493bool AudioPolicyManager::isStateInCall(int state)
5494{
5495 return is_state_in_call(state);
5496}
5497
Eric Laurentd60560a2015-04-10 11:31:20 -07005498void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5499{
5500 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5501 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
5502 if (sourceDesc->mDevice->equals(deviceDesc)) {
5503 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle());
5504 stopAudioSource(sourceDesc->getHandle());
5505 }
5506 }
5507
5508 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5509 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5510 bool release = false;
5511 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5512 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5513 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5514 source->ext.device.type == deviceDesc->type()) {
5515 release = true;
5516 }
5517 }
5518 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5519 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5520 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5521 sink->ext.device.type == deviceDesc->type()) {
5522 release = true;
5523 }
5524 }
5525 if (release) {
5526 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5527 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5528 }
5529 }
5530}
5531
Phil Burk09bc4612016-02-24 15:58:15 -08005532// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005533void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5534 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005535 // TODO Set this based on Config properties.
5536 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005537
5538 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5539 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005540 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005541
5542 // Analyze original support for various formats.
Phil Burk07ac1142016-03-25 13:39:29 -07005543 bool supportsAC3 = false;
5544 bool supportsOtherSurround = false;
Phil Burk09bc4612016-02-24 15:58:15 -08005545 bool supportsIEC61937 = false;
5546 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
5547 audio_format_t format = formats[formatIndex];
Phil Burk09bc4612016-02-24 15:58:15 -08005548 switch (format) {
5549 case AUDIO_FORMAT_AC3:
Phil Burk07ac1142016-03-25 13:39:29 -07005550 supportsAC3 = true;
5551 break;
Phil Burk09bc4612016-02-24 15:58:15 -08005552 case AUDIO_FORMAT_E_AC3:
5553 case AUDIO_FORMAT_DTS:
5554 case AUDIO_FORMAT_DTS_HD:
Phil Burk07ac1142016-03-25 13:39:29 -07005555 supportsOtherSurround = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005556 break;
5557 case AUDIO_FORMAT_IEC61937:
5558 supportsIEC61937 = true;
5559 break;
5560 default:
5561 break;
5562 }
5563 }
Phil Burk09bc4612016-02-24 15:58:15 -08005564
5565 // Modify formats based on surround preferences.
5566 // If NEVER, remove support for surround formats.
Phil Burk07ac1142016-03-25 13:39:29 -07005567 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5568 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5569 // Remove surround sound related formats.
5570 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5571 audio_format_t format = formats[formatIndex];
5572 switch(format) {
5573 case AUDIO_FORMAT_AC3:
5574 case AUDIO_FORMAT_E_AC3:
5575 case AUDIO_FORMAT_DTS:
5576 case AUDIO_FORMAT_DTS_HD:
5577 case AUDIO_FORMAT_IEC61937:
Phil Burk07ac1142016-03-25 13:39:29 -07005578 formats.removeAt(formatIndex);
5579 break;
5580 default:
5581 formatIndex++; // keep it
5582 break;
5583 }
Phil Burk09bc4612016-02-24 15:58:15 -08005584 }
Phil Burk07ac1142016-03-25 13:39:29 -07005585 supportsAC3 = false;
5586 supportsOtherSurround = false;
5587 supportsIEC61937 = false;
Phil Burk09bc4612016-02-24 15:58:15 -08005588 }
Phil Burk07ac1142016-03-25 13:39:29 -07005589 } else { // AUTO or ALWAYS
5590 // Most TVs support AC3 even if they do not report it in the EDID.
5591 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
5592 && !supportsAC3) {
5593 formats.add(AUDIO_FORMAT_AC3);
5594 supportsAC3 = true;
5595 }
5596
5597 // If ALWAYS, add support for raw surround formats if all are missing.
5598 // This assumes that if any of these formats are reported by the HAL
5599 // then the report is valid and should not be modified.
5600 if ((forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS)
5601 && !supportsOtherSurround) {
5602 formats.add(AUDIO_FORMAT_E_AC3);
5603 formats.add(AUDIO_FORMAT_DTS);
5604 formats.add(AUDIO_FORMAT_DTS_HD);
5605 supportsOtherSurround = true;
5606 }
5607
5608 // Add support for IEC61937 if any raw surround supported.
5609 // The HAL could do this but add it here, just in case.
5610 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
5611 formats.add(AUDIO_FORMAT_IEC61937);
5612 supportsIEC61937 = true;
5613 }
Phil Burk09bc4612016-02-24 15:58:15 -08005614 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005615}
5616
5617// Modify the list of channel masks supported.
5618void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
5619 ChannelsVector &channelMasks = *channelMasksPtr;
5620 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5621 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5622
5623 // If NEVER, then remove support for channelMasks > stereo.
5624 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5625 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5626 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5627 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5628 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5629 channelMasks.removeAt(maskIndex);
5630 } else {
5631 maskIndex++;
5632 }
5633 }
5634 // If ALWAYS, then make sure we at least support 5.1
5635 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5636 bool supports5dot1 = false;
5637 // Are there any channel masks that can be considered "surround"?
5638 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); maskIndex++) {
5639 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5640 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5641 supports5dot1 = true;
5642 break;
5643 }
5644 }
5645 // If not then add 5.1 support.
5646 if (!supports5dot1) {
5647 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
5648 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
5649 }
Phil Burk09bc4612016-02-24 15:58:15 -08005650 }
5651}
5652
Phil Burk00eeb322016-03-31 12:41:00 -07005653void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
5654 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005655 AudioProfileVector &profiles)
5656{
5657 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07005658
François Gaffie112b0af2015-11-19 16:13:25 +01005659 // Format MUST be checked first to update the list of AudioProfile
5660 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005661 reply = mpClientInterface->getParameters(
5662 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
Phil Burk0709b0a2016-03-31 12:54:57 -07005663 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005664 AudioParameter repliedParameters(reply);
5665 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005666 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005667 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5668 return;
5669 }
Phil Burk09bc4612016-02-24 15:58:15 -08005670 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07005671 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005672 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005673 }
Phil Burk09bc4612016-02-24 15:58:15 -08005674 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005675 }
5676 const FormatVector &supportedFormats = profiles.getSupportedFormats();
5677
Eric Laurent20eb3a42016-01-26 18:39:17 -08005678 for (size_t formatIndex = 0; formatIndex < supportedFormats.size(); formatIndex++) {
François Gaffie112b0af2015-11-19 16:13:25 +01005679 audio_format_t format = supportedFormats[formatIndex];
Eric Laurent20eb3a42016-01-26 18:39:17 -08005680 ChannelsVector channelMasks;
5681 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005682 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07005683 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01005684
5685 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005686 reply = mpClientInterface->getParameters(
5687 ioHandle,
5688 requestedParameters.toString() + ";" +
5689 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01005690 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005691 AudioParameter repliedParameters(reply);
5692 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005693 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005694 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005695 }
5696 }
5697 if (profiles.hasDynamicChannelsFor(format)) {
5698 reply = mpClientInterface->getParameters(ioHandle,
5699 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07005700 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01005701 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005702 AudioParameter repliedParameters(reply);
5703 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005704 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005705 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07005706 if (device == AUDIO_DEVICE_OUT_HDMI) {
5707 filterSurroundChannelMasks(&channelMasks);
5708 }
François Gaffie112b0af2015-11-19 16:13:25 +01005709 }
5710 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08005711 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01005712 }
5713}
Eric Laurentd60560a2015-04-10 11:31:20 -07005714
Eric Laurente552edb2014-03-10 17:42:56 -07005715}; // namespace android