blob: 2096ddaed536e627d64f3d7b961d7953cb5e6c00 [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 Laurentf4e63452017-11-06 19:31:46 +0000754audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700755{
Eric Laurent3b73df72014-03-11 09:06:29 -0700756 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700757 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800758
759 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
760 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
761 // format, flags, etc. This may result in some discrepancy for functions that utilize
762 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
763 // and AudioSystem::getOutputSamplingRate().
764
Eric Laurentf4e63452017-11-06 19:31:46 +0000765 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
766 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
Eric Laurente552edb2014-03-10 17:42:56 -0700767
Eric Laurentf4e63452017-11-06 19:31:46 +0000768 ALOGV("getOutput() stream %d selected device %08x, output %d", stream, device, output);
769 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700770}
771
Eric Laurente83b55d2014-11-14 10:06:21 -0800772status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
773 audio_io_handle_t *output,
774 audio_session_t session,
775 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700776 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800777 const audio_config_t *config,
Eric Laurente83b55d2014-11-14 10:06:21 -0800778 audio_output_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700779 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800780 audio_port_handle_t *portId)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700781{
Eric Laurente83b55d2014-11-14 10:06:21 -0800782 audio_attributes_t attributes;
783 if (attr != NULL) {
784 if (!isValidAttributes(attr)) {
785 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
786 attr->usage, attr->content_type, attr->flags,
787 attr->tags);
788 return BAD_VALUE;
789 }
790 attributes = *attr;
791 } else {
792 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
793 ALOGE("getOutputForAttr(): invalid stream type");
794 return BAD_VALUE;
795 }
796 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700797 }
Eric Laurent20b9ef02016-12-05 11:03:16 -0800798
799 // TODO: check for existing client for this port ID
800 if (*portId == AUDIO_PORT_HANDLE_NONE) {
801 *portId = AudioPort::getNextUniqueId();
802 }
803
Eric Laurentc75307b2015-03-17 15:29:32 -0700804 sp<SwAudioOutputDescriptor> desc;
Jean-Michel Trivie8deced2016-02-11 12:50:39 -0800805 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
François Gaffie036e1e92015-03-19 10:16:24 +0100806 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
Eric Laurent20b9ef02016-12-05 11:03:16 -0800807 if (!audio_has_proportional_frames(config->format)) {
François Gaffie036e1e92015-03-19 10:16:24 +0100808 return BAD_VALUE;
Eric Laurent275e8e92014-11-30 15:14:47 -0800809 }
François Gaffie036e1e92015-03-19 10:16:24 +0100810 *stream = streamTypefromAttributesInt(&attributes);
811 *output = desc->mIoHandle;
812 ALOGV("getOutputForAttr() returns output %d", *output);
813 return NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -0800814 }
815 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
816 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
817 return BAD_VALUE;
818 }
819
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700820 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
821 " session %d selectedDeviceId %d",
822 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700823 session, *selectedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700824
825 *stream = streamTypefromAttributesInt(&attributes);
826
827 // Explicit routing?
828 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -0700829 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
830 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
831 if (mAvailableOutputDevices[i]->getId() == *selectedDeviceId) {
832 deviceDesc = mAvailableOutputDevices[i];
833 break;
834 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700835 }
836 }
837 mOutputRoutes.addRoute(session, *stream, SessionRoute::SOURCE_TYPE_NA, deviceDesc, uid);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700838
Eric Laurente83b55d2014-11-14 10:06:21 -0800839 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700840 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700841
Eric Laurente83b55d2014-11-14 10:06:21 -0800842 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Eric Laurent93c3d412014-08-01 14:48:35 -0700843 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
844 }
845
Eric Laurentfe231122017-11-17 17:48:06 -0800846 ALOGV("getOutputForAttr() device 0x%x, sampling rate %d, format %x, channel mask %x, flags %x",
Eric Laurent20b9ef02016-12-05 11:03:16 -0800847 device, config->sample_rate, config->format, config->channel_mask, flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700848
Eric Laurentfe231122017-11-17 17:48:06 -0800849 *output = getOutputForDevice(device, session, *stream, config, flags);
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,
Eric Laurentfe231122017-11-17 17:48:06 -0800868 const audio_config_t *config,
869 audio_output_flags_t flags)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700870{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700871 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700872 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700873
Eric Laurente552edb2014-03-10 17:42:56 -0700874 // open a direct output if required by specified parameters
875 //force direct flag if offload flag is set: offloading implies a direct output stream
876 // and all common behaviors are driven by checking only the direct flag
877 // this should normally be set appropriately in the policy configuration file
878 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700879 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700880 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700881 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
882 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
883 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800884 // only allow deep buffering for music stream type
885 if (stream != AUDIO_STREAM_MUSIC) {
886 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700887 } else if (/* stream == AUDIO_STREAM_MUSIC && */
888 flags == AUDIO_OUTPUT_FLAG_NONE &&
889 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
890 // use DEEP_BUFFER as default output for music stream type
891 flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800892 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700893 if (stream == AUDIO_STREAM_TTS) {
894 flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700895 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Eric Laurentfe231122017-11-17 17:48:06 -0800896 audio_is_linear_pcm(config->format)) {
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700897 flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
898 AUDIO_OUTPUT_FLAG_DIRECT);
899 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700900 }
Eric Laurente552edb2014-03-10 17:42:56 -0700901
Eric Laurentb732cf52014-09-24 19:08:21 -0700902 sp<IOProfile> profile;
903
904 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700905 // and not explicitly requested
906 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Eric Laurentfe231122017-11-17 17:48:06 -0800907 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
908 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
Eric Laurentb732cf52014-09-24 19:08:21 -0700909 goto non_direct_output;
910 }
911
Andy Hung2ddee192015-12-18 17:34:44 -0800912 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
913 // This prevents creating an offloaded track and tearing it down immediately after start
914 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700915 // FIXME: We should check the audio session here but we do not have it in this context.
916 // This may prevent offloading in rare situations where effects are left active by apps
917 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700918
Eric Laurente552edb2014-03-10 17:42:56 -0700919 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800920 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700921 profile = getProfileForDirectOutput(device,
Eric Laurentfe231122017-11-17 17:48:06 -0800922 config->sample_rate,
923 config->format,
924 config->channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -0700925 (audio_output_flags_t)flags);
926 }
927
Eric Laurent1c333e22014-05-20 10:48:17 -0700928 if (profile != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700929 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700930 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700931 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
Kevin Rocard551061a2017-02-06 15:59:29 -0800932 // reuse direct output if currently open by the same client
933 // and configured with same parameters
Eric Laurentf05fc902017-11-21 12:08:15 -0800934 if ((config->sample_rate == desc->mSamplingRate) &&
935 audio_formats_match(config->format, desc->mFormat) &&
936 (config->channel_mask == desc->mChannelMask) &&
937 (session == desc->mDirectClientSession)) {
938 desc->mDirectOpenCount++;
939 ALOGV("getOutputForDevice() reusing direct output %d for session %d",
940 mOutputs.keyAt(i), session);
941 return mOutputs.keyAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700942 }
943 }
944 }
Eric Laurentf05fc902017-11-21 12:08:15 -0800945
946 if (!profile->canOpenNewIo()) {
947 goto non_direct_output;
Eric Laurente552edb2014-03-10 17:42:56 -0700948 }
Eric Laurent861a6282015-05-18 15:40:16 -0700949
Eric Laurentf05fc902017-11-21 12:08:15 -0800950 sp<SwAudioOutputDescriptor> outputDesc =
951 new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentfe231122017-11-17 17:48:06 -0800952 status = outputDesc->open(config, device, String8(""), stream, flags, &output);
Eric Laurente552edb2014-03-10 17:42:56 -0700953
954 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -0700955 if (status != NO_ERROR ||
Eric Laurentfe231122017-11-17 17:48:06 -0800956 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
957 (config->format != AUDIO_FORMAT_DEFAULT &&
958 !audio_formats_match(config->format, outputDesc->mFormat)) ||
959 (config->channel_mask != 0 && config->channel_mask != outputDesc->mChannelMask)) {
960 ALOGV("getOutputForDevice() failed opening direct output: output %d sample rate %d %d,"
961 "format %d %d, channel mask %04x %04x", output, config->sample_rate,
962 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
963 config->channel_mask, outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700964 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -0800965 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -0700966 }
Eric Laurenta82797f2015-01-30 11:49:43 -0800967 // fall back to mixer output if possible when the direct output could not be open
Eric Laurentfe231122017-11-17 17:48:06 -0800968 if (audio_is_linear_pcm(config->format) &&
969 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -0800970 goto non_direct_output;
971 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700972 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -0700973 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700974 outputDesc->mRefCount[stream] = 0;
975 outputDesc->mStopTime[stream] = 0;
976 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -0800977 outputDesc->mDirectClientSession = session;
978
Eric Laurente552edb2014-03-10 17:42:56 -0700979 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700980 mPreviousOutputs = mOutputs;
Eric Laurentf4e63452017-11-06 19:31:46 +0000981 ALOGV("getOutputForDevice() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -0700982 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700983 return output;
984 }
985
Eric Laurentb732cf52014-09-24 19:08:21 -0700986non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -0700987
988 // A request for HW A/V sync cannot fallback to a mixed output because time
989 // stamps are embedded in audio data
990 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
991 return AUDIO_IO_HANDLE_NONE;
992 }
993
Eric Laurente552edb2014-03-10 17:42:56 -0700994 // ignoring channel mask due to downmix capability in mixer
995
996 // open a non direct output
997
998 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -0800999 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001000 // get which output is suitable for the specified stream. The actual
1001 // routing change will happen when startOutput() will be called
1002 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1003
Eric Laurent8838a382014-09-08 16:44:28 -07001004 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
1005 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurentfe231122017-11-17 17:48:06 -08001006 output = selectOutput(outputs, flags, config->format);
Eric Laurente552edb2014-03-10 17:42:56 -07001007 }
Eric Laurentf4e63452017-11-06 19:31:46 +00001008 ALOGW_IF((output == 0), "getOutputForDevice() could not find output for stream %d, "
Eric Laurentfe231122017-11-17 17:48:06 -08001009 "sampling rate %d, format %d, channels %x, flags %x",
1010 stream, config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001011
Eric Laurente552edb2014-03-10 17:42:56 -07001012 return output;
1013}
1014
Eric Laurente0720872014-03-11 09:30:41 -07001015audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001016 audio_output_flags_t flags,
1017 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001018{
1019 // select one output among several that provide a path to a particular device or set of
1020 // devices (the list was previously build by getOutputsForDevice()).
1021 // The priority is as follows:
1022 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001023 // 2: the output with the bit depth the closest to the requested one
1024 // 3: the primary output
1025 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001026
1027 if (outputs.size() == 0) {
1028 return 0;
1029 }
1030 if (outputs.size() == 1) {
1031 return outputs[0];
1032 }
1033
1034 int maxCommonFlags = 0;
Eric Laurente6930022016-02-11 10:20:40 -08001035 audio_io_handle_t outputForFlags = 0;
1036 audio_io_handle_t outputForPrimary = 0;
1037 audio_io_handle_t outputForFormat = 0;
1038 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1039 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001040
1041 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001042 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001043 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001044 // if a valid format is specified, skip output if not compatible
1045 if (format != AUDIO_FORMAT_INVALID) {
1046 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente6930022016-02-11 10:20:40 -08001047 if (!audio_formats_match(format, outputDesc->mFormat)) {
Eric Laurent8838a382014-09-08 16:44:28 -07001048 continue;
1049 }
1050 } else if (!audio_is_linear_pcm(format)) {
1051 continue;
1052 }
Eric Laurente6930022016-02-11 10:20:40 -08001053 if (AudioPort::isBetterFormatMatch(
1054 outputDesc->mFormat, bestFormat, format)) {
1055 outputForFormat = outputs[i];
1056 bestFormat = outputDesc->mFormat;
1057 }
Eric Laurent8838a382014-09-08 16:44:28 -07001058 }
1059
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001060 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001061 if (commonFlags >= maxCommonFlags) {
1062 if (commonFlags == maxCommonFlags) {
Andy Hungc9901522017-11-10 20:07:54 -08001063 if (format != AUDIO_FORMAT_INVALID
1064 && AudioPort::isBetterFormatMatch(
1065 outputDesc->mFormat, bestFormatForFlags, format)) {
Eric Laurente6930022016-02-11 10:20:40 -08001066 outputForFlags = outputs[i];
1067 bestFormatForFlags = outputDesc->mFormat;
1068 }
1069 } else {
1070 outputForFlags = outputs[i];
1071 maxCommonFlags = commonFlags;
1072 bestFormatForFlags = outputDesc->mFormat;
1073 }
Eric Laurente552edb2014-03-10 17:42:56 -07001074 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1075 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001076 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurente6930022016-02-11 10:20:40 -08001077 outputForPrimary = outputs[i];
Eric Laurente552edb2014-03-10 17:42:56 -07001078 }
1079 }
1080 }
1081
Eric Laurente6930022016-02-11 10:20:40 -08001082 if (outputForFlags != 0) {
1083 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001084 }
Eric Laurente6930022016-02-11 10:20:40 -08001085 if (outputForFormat != 0) {
1086 return outputForFormat;
1087 }
1088 if (outputForPrimary != 0) {
1089 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001090 }
1091
1092 return outputs[0];
1093}
1094
Eric Laurente0720872014-03-11 09:30:41 -07001095status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001096 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001097 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001098{
Paul McLeanaa981192015-03-21 09:55:15 -07001099 ALOGV("startOutput() output %d, stream %d, session %d",
1100 output, stream, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001101 ssize_t index = mOutputs.indexOfKey(output);
1102 if (index < 0) {
1103 ALOGW("startOutput() unknown output %d", output);
1104 return BAD_VALUE;
1105 }
1106
Eric Laurentc75307b2015-03-17 15:29:32 -07001107 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1108
Eric Laurentf05fc902017-11-21 12:08:15 -08001109 if (!outputDesc->isActive()) {
1110 if (!outputDesc->mProfile->canStartNewIo()) {
1111 return INVALID_OPERATION;
1112 }
1113 outputDesc->mProfile->curActiveCount++;
1114 }
1115
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001116 // Routing?
1117 mOutputRoutes.incRouteActivity(session);
1118
Eric Laurentc75307b2015-03-17 15:29:32 -07001119 audio_devices_t newDevice;
Eric Laurentc40d9692016-04-13 19:14:13 -07001120 AudioMix *policyMix = NULL;
1121 const char *address = NULL;
Eric Laurentc75307b2015-03-17 15:29:32 -07001122 if (outputDesc->mPolicyMix != NULL) {
Eric Laurentc40d9692016-04-13 19:14:13 -07001123 policyMix = outputDesc->mPolicyMix;
1124 address = policyMix->mDeviceAddress.string();
1125 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1126 newDevice = policyMix->mDeviceType;
1127 } else {
1128 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1129 }
Eric Laurent493404d2015-04-21 15:07:36 -07001130 } else if (mOutputRoutes.hasRouteChanged(session)) {
1131 newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001132 checkStrategyRoute(getStrategy(stream), output);
Eric Laurentc75307b2015-03-17 15:29:32 -07001133 } else {
1134 newDevice = AUDIO_DEVICE_NONE;
1135 }
1136
1137 uint32_t delayMs = 0;
1138
Eric Laurentc40d9692016-04-13 19:14:13 -07001139 status_t status = startSource(outputDesc, stream, newDevice, address, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001140
1141 if (status != NO_ERROR) {
1142 mOutputRoutes.decRouteActivity(session);
Eric Laurentf05fc902017-11-21 12:08:15 -08001143 if (!outputDesc->isActive()) {
1144 LOG_ALWAYS_FATAL_IF(outputDesc->mProfile->curActiveCount < 1,
1145 "%s invalid profile active count %u",
1146 __FUNCTION__, outputDesc->mProfile->curActiveCount);
1147 outputDesc->mProfile->curActiveCount--;
1148 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001149 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001150 }
1151 // Automatically enable the remote submix input when output is started on a re routing mix
1152 // of type MIX_TYPE_RECORDERS
Eric Laurentc40d9692016-04-13 19:14:13 -07001153 if (audio_is_remote_submix_device(newDevice) && policyMix != NULL &&
1154 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001155 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1156 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Eric Laurentc40d9692016-04-13 19:14:13 -07001157 address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001158 "remote-submix");
1159 }
1160
1161 if (delayMs != 0) {
1162 usleep(delayMs * 1000);
1163 }
1164
1165 return status;
1166}
1167
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001168status_t AudioPolicyManager::startSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurentc75307b2015-03-17 15:29:32 -07001169 audio_stream_type_t stream,
1170 audio_devices_t device,
Eric Laurentc40d9692016-04-13 19:14:13 -07001171 const char *address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001172 uint32_t *delayMs)
1173{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001174 // cannot start playback of STREAM_TTS if any other output is being used
1175 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001176
1177 *delayMs = 0;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001178 if (stream == AUDIO_STREAM_TTS) {
1179 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001180 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001181 return INVALID_OPERATION;
1182 } else {
1183 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1184 }
1185 } else {
1186 // some playback other than beacon starts
1187 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1188 }
1189
Eric Laurent77305a62016-07-25 16:39:22 -07001190 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001191 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001192 bool force = !outputDesc->isActive() &&
1193 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001194
Andy Hung7c7124e2017-10-20 12:03:34 -07001195 // requiresMuteCheck is false when we can bypass mute strategy.
1196 // It covers a common case when there is no materially active audio
1197 // and muting would result in unnecessary delay and dropped audio.
1198 const uint32_t outputLatencyMs = outputDesc->latency();
1199 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1200
Eric Laurente552edb2014-03-10 17:42:56 -07001201 // increment usage count for this stream on the requested output:
1202 // NOTE that the usage count is the same for duplicated output and hardware output which is
1203 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1204 outputDesc->changeRefCount(stream, 1);
1205
Eric Laurent36829f92017-04-07 19:04:42 -07001206 if (stream == AUDIO_STREAM_MUSIC) {
1207 selectOutputForMusicEffects();
1208 }
1209
Eric Laurent493404d2015-04-21 15:07:36 -07001210 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001211 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001212 if (device == AUDIO_DEVICE_NONE) {
1213 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001214 }
Eric Laurent36829f92017-04-07 19:04:42 -07001215
Eric Laurente552edb2014-03-10 17:42:56 -07001216 routing_strategy strategy = getStrategy(stream);
1217 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001218 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1219 (beaconMuteLatency > 0);
1220 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001221 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001222 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001223 if (desc != outputDesc) {
Andy Hung7c7124e2017-10-20 12:03:34 -07001224 // An output has a shared device if
1225 // - managed by the same hw module
1226 // - supports the currently selected device
1227 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
1228 && (desc->supportedDevices() & device) != AUDIO_DEVICE_NONE;
1229
Eric Laurent77305a62016-07-25 16:39:22 -07001230 // force a device change if any other output is:
1231 // - managed by the same hw module
Eric Laurent77305a62016-07-25 16:39:22 -07001232 // - supports currently selected device
Andy Hung7c7124e2017-10-20 12:03:34 -07001233 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001234 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001235 // In this case, the audio HAL must receive the new device selection so that it can
Andy Hung7c7124e2017-10-20 12:03:34 -07001236 // change the device currently selected by the other output.
1237 if (sharedDevice &&
Eric Laurent77305a62016-07-25 16:39:22 -07001238 desc->device() != device &&
Eric Laurent77305a62016-07-25 16:39:22 -07001239 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001240 force = true;
1241 }
1242 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001243 // a notification so that audio focus effect can propagate, or that a mute/unmute
1244 // event occurred for beacon
Andy Hung7c7124e2017-10-20 12:03:34 -07001245 const uint32_t latencyMs = desc->latency();
1246 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1247
1248 if (shouldWait && isActive && (waitMs < latencyMs)) {
1249 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001250 }
Andy Hung7c7124e2017-10-20 12:03:34 -07001251
1252 // Require mute check if another output is on a shared device
1253 // and currently active to have proper drain and avoid pops.
1254 // Note restoring AudioTracks onto this output needs to invoke
1255 // a volume ramp if there is no mute.
1256 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001257 }
1258 }
Andy Hung7c7124e2017-10-20 12:03:34 -07001259
1260 const uint32_t muteWaitMs =
1261 setOutputDevice(outputDesc, device, force, 0, NULL, address, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001262
1263 // handle special case for sonification while in call
1264 if (isInCall()) {
1265 handleIncallSonification(stream, true, false);
1266 }
1267
1268 // apply volume rules for current stream and device if necessary
1269 checkAndSetVolume(stream,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001270 mVolumeCurves->getVolumeIndex(stream, outputDesc->device()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001271 outputDesc,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001272 outputDesc->device());
Eric Laurente552edb2014-03-10 17:42:56 -07001273
1274 // update the outputs if starting an output with a stream that can affect notification
1275 // routing
1276 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001277
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001278 // force reevaluating accessibility routing when ringtone or alarm starts
1279 if (strategy == STRATEGY_SONIFICATION) {
1280 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1281 }
Eric Laurentdc462862016-07-19 12:29:53 -07001282
1283 if (waitMs > muteWaitMs) {
1284 *delayMs = waitMs - muteWaitMs;
1285 }
Andy Hung7c7124e2017-10-20 12:03:34 -07001286
1287 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1288 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1289 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1290 // change occurs after the MixerThread starts and causes a stream volume
1291 // glitch.
1292 //
1293 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001294 }
Eric Laurentdc462862016-07-19 12:29:53 -07001295
Eric Laurente552edb2014-03-10 17:42:56 -07001296 return NO_ERROR;
1297}
1298
1299
Eric Laurente0720872014-03-11 09:30:41 -07001300status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001301 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001302 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001303{
1304 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1305 ssize_t index = mOutputs.indexOfKey(output);
1306 if (index < 0) {
1307 ALOGW("stopOutput() unknown output %d", output);
1308 return BAD_VALUE;
1309 }
1310
Eric Laurentc75307b2015-03-17 15:29:32 -07001311 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001312
Eric Laurentc75307b2015-03-17 15:29:32 -07001313 if (outputDesc->mRefCount[stream] == 1) {
1314 // Automatically disable the remote submix input when output is stopped on a
1315 // re routing mix of type MIX_TYPE_RECORDERS
1316 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1317 outputDesc->mPolicyMix != NULL &&
1318 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1319 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1320 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001321 outputDesc->mPolicyMix->mDeviceAddress,
Eric Laurentc75307b2015-03-17 15:29:32 -07001322 "remote-submix");
1323 }
1324 }
1325
1326 // Routing?
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001327 bool forceDeviceUpdate = false;
Eric Laurentc75307b2015-03-17 15:29:32 -07001328 if (outputDesc->mRefCount[stream] > 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001329 int activityCount = mOutputRoutes.decRouteActivity(session);
1330 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1331
1332 if (forceDeviceUpdate) {
1333 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1334 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001335 }
1336
Eric Laurentf05fc902017-11-21 12:08:15 -08001337 status_t status = stopSource(outputDesc, stream, forceDeviceUpdate);
1338
1339 if (status == NO_ERROR && !outputDesc->isActive()) {
1340 LOG_ALWAYS_FATAL_IF(outputDesc->mProfile->curActiveCount < 1,
1341 "%s invalid profile active count %u",
1342 __FUNCTION__, outputDesc->mProfile->curActiveCount);
1343 outputDesc->mProfile->curActiveCount--;
1344 }
1345 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001346}
1347
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001348status_t AudioPolicyManager::stopSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001349 audio_stream_type_t stream,
1350 bool forceDeviceUpdate)
Eric Laurentc75307b2015-03-17 15:29:32 -07001351{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001352 // always handle stream stop, check which stream type is stopping
1353 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1354
Eric Laurente552edb2014-03-10 17:42:56 -07001355 // handle special case for sonification while in call
1356 if (isInCall()) {
1357 handleIncallSonification(stream, false, false);
1358 }
1359
1360 if (outputDesc->mRefCount[stream] > 0) {
1361 // decrement usage count of this stream on the output
1362 outputDesc->changeRefCount(stream, -1);
Paul McLeanaa981192015-03-21 09:55:15 -07001363
Eric Laurente552edb2014-03-10 17:42:56 -07001364 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001365 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001366 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001367 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001368 // delay the device switch by twice the latency because stopOutput() is executed when
1369 // the track stop() command is received and at that time the audio track buffer can
1370 // still contain data that needs to be drained. The latency only covers the audio HAL
1371 // and kernel buffers. Also the latency does not always include additional delay in the
1372 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001373 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001374
1375 // force restoring the device selection on other active outputs if it differs from the
1376 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001377 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001378 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001379 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001380 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001381 desc->isActive() &&
1382 outputDesc->sharesHwModuleWith(desc) &&
1383 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001384 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1385 bool force = desc->device() != newDevice2;
Eric Laurentc75307b2015-03-17 15:29:32 -07001386 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001387 newDevice2,
1388 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001389 delayMs);
1390 // re-apply device specific volume if not done by setOutputDevice()
1391 if (!force) {
1392 applyStreamVolumes(desc, newDevice2, delayMs);
1393 }
Eric Laurente552edb2014-03-10 17:42:56 -07001394 }
1395 }
1396 // update the outputs if stopping one with a stream that can affect notification routing
1397 handleNotificationRoutingForStream(stream);
1398 }
Eric Laurent36829f92017-04-07 19:04:42 -07001399 if (stream == AUDIO_STREAM_MUSIC) {
1400 selectOutputForMusicEffects();
1401 }
Eric Laurente552edb2014-03-10 17:42:56 -07001402 return NO_ERROR;
1403 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001404 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001405 return INVALID_OPERATION;
1406 }
1407}
1408
Eric Laurente83b55d2014-11-14 10:06:21 -08001409void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001410 audio_stream_type_t stream __unused,
1411 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001412{
1413 ALOGV("releaseOutput() %d", output);
1414 ssize_t index = mOutputs.indexOfKey(output);
1415 if (index < 0) {
1416 ALOGW("releaseOutput() releasing unknown output %d", output);
1417 return;
1418 }
1419
Paul McLeanaa981192015-03-21 09:55:15 -07001420 // Routing
1421 mOutputRoutes.removeRoute(session);
1422
Eric Laurentc75307b2015-03-17 15:29:32 -07001423 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001424 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001425 if (desc->mDirectOpenCount <= 0) {
1426 ALOGW("releaseOutput() invalid open count %d for output %d",
1427 desc->mDirectOpenCount, output);
1428 return;
1429 }
1430 if (--desc->mDirectOpenCount == 0) {
1431 closeOutput(output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001432 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001433 }
1434 }
1435}
1436
1437
Eric Laurentcaf7f482014-11-25 17:50:47 -08001438status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1439 audio_io_handle_t *input,
1440 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001441 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001442 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001443 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001444 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001445 input_type_t *inputType,
1446 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001447{
Eric Laurentfe231122017-11-17 17:48:06 -08001448 ALOGV("getInputForAttr() source %d, sampling rate %d, format %d, channel mask %x,"
Eric Laurentcaf7f482014-11-25 17:50:47 -08001449 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001450 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001451
Eric Laurentad2e7b92017-09-14 20:06:42 -07001452 status_t status = NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -08001453 // handle legacy remote submix case where the address was not always specified
1454 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001455 audio_source_t halInputSource;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001456 audio_source_t inputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001457 AudioMix *policyMix = NULL;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001458 DeviceVector inputDevices;
Eric Laurent20b9ef02016-12-05 11:03:16 -08001459
Eric Laurentfe231122017-11-17 17:48:06 -08001460 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1461 inputSource = AUDIO_SOURCE_MIC;
1462 }
1463
Paul McLean466dc8e2015-04-17 13:15:36 -06001464 // Explicit routing?
1465 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -07001466 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
1467 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
1468 if (mAvailableInputDevices[i]->getId() == *selectedDeviceId) {
1469 deviceDesc = mAvailableInputDevices[i];
1470 break;
1471 }
Paul McLean466dc8e2015-04-17 13:15:36 -06001472 }
1473 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001474 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
Paul McLean466dc8e2015-04-17 13:15:36 -06001475
Eric Laurentad2e7b92017-09-14 20:06:42 -07001476 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1477 // possible
1478 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1479 *input != AUDIO_IO_HANDLE_NONE) {
1480 ssize_t index = mInputs.indexOfKey(*input);
1481 if (index < 0) {
1482 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1483 status = BAD_VALUE;
1484 goto error;
1485 }
1486 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1487 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1488 if (audioSession == 0) {
1489 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1490 status = BAD_VALUE;
1491 goto error;
1492 }
1493 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1494 // The second call is for the first active client and sets the UID. Any further call
1495 // corresponds to a new client and is only permitted from the same UId.
1496 if (audioSession->openCount() == 1) {
1497 audioSession->setUid(uid);
1498 } else if (audioSession->uid() != uid) {
1499 ALOGW("getInputForAttr() bad uid %d for session %d uid %d",
1500 uid, session, audioSession->uid());
1501 status = INVALID_OPERATION;
1502 goto error;
1503 }
1504 audioSession->changeOpenCount(1);
1505 *inputType = API_INPUT_LEGACY;
1506 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1507 *portId = AudioPort::getNextUniqueId();
1508 }
1509 inputDevices = mAvailableInputDevices.getDevicesFromType(inputDesc->mDevice);
1510 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1511 : AUDIO_PORT_HANDLE_NONE;
1512 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
1513
1514 return NO_ERROR;
1515 }
1516
1517 *input = AUDIO_IO_HANDLE_NONE;
1518 *inputType = API_INPUT_INVALID;
1519
Eric Laurentad2e7b92017-09-14 20:06:42 -07001520 halInputSource = inputSource;
1521
1522 // TODO: check for existing client for this port ID
1523 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1524 *portId = AudioPort::getNextUniqueId();
1525 }
1526
1527 audio_devices_t device;
1528
Eric Laurentc447ded2015-01-06 08:47:05 -08001529 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001530 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001531 status = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
1532 if (status != NO_ERROR) {
1533 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001534 }
1535 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001536 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1537 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001538 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001539 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001540 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001541 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001542 status = BAD_VALUE;
1543 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001544 }
Eric Laurentc722f302014-12-10 11:21:49 -08001545 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001546 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001547 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1548 // there is an external policy, but this input is attached to a mix of recorders,
1549 // meaning it receives audio injected into the framework, so the recorder doesn't
1550 // know about it and is therefore considered "legacy"
1551 *inputType = API_INPUT_LEGACY;
1552 } else {
1553 // recording a mix of players defined by an external policy, we're rerouting for
1554 // an external policy
1555 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1556 }
Eric Laurentc722f302014-12-10 11:21:49 -08001557 } else if (audio_is_remote_submix_device(device)) {
1558 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001559 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001560 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1561 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001562 } else {
1563 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001564 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001565
Eric Laurent599c7582015-12-07 18:05:55 -08001566 }
1567
1568 *input = getInputForDevice(device, address, session, uid, inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001569 config, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001570 policyMix);
1571 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001572 status = INVALID_OPERATION;
1573 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001574 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001575
Eric Laurentad2e7b92017-09-14 20:06:42 -07001576 inputDevices = mAvailableInputDevices.getDevicesFromType(device);
Eric Laurent2ac76942017-06-22 17:17:09 -07001577 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1578 : AUDIO_PORT_HANDLE_NONE;
1579
1580 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d",
1581 *input, *inputType, *selectedDeviceId);
1582
Eric Laurent599c7582015-12-07 18:05:55 -08001583 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001584
1585error:
1586 mInputRoutes.removeRoute(session);
1587 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001588}
1589
1590
1591audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1592 String8 address,
1593 audio_session_t session,
1594 uid_t uid,
1595 audio_source_t inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001596 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08001597 audio_input_flags_t flags,
1598 AudioMix *policyMix)
1599{
1600 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1601 audio_source_t halInputSource = inputSource;
1602 bool isSoundTrigger = false;
1603
1604 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1605 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1606 if (index >= 0) {
1607 input = mSoundTriggerSessions.valueFor(session);
1608 isSoundTrigger = true;
1609 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1610 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1611 } else {
1612 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001613 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001614 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08001615 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001616 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001617 }
1618
Andy Hungf129b032015-04-07 13:45:50 -07001619 // find a compatible input profile (not necessarily identical in parameters)
1620 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08001621 // sampling rate and flags may be updated by getInputProfile
1622 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
1623 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
1624 audio_format_t profileFormat = config->format;
1625 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07001626 audio_input_flags_t profileFlags = flags;
1627 for (;;) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001628 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001629 profileSamplingRate, profileFormat, profileChannelMask,
1630 profileFlags);
1631 if (profile != 0) {
1632 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001633 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1634 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001635 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1636 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1637 } else { // fail
Glenn Kastenfaa10a62017-05-25 15:52:05 -07001638 ALOGW("getInputForDevice() could not find profile for device 0x%X, "
Eric Laurentfe231122017-11-17 17:48:06 -08001639 "sampling rate %u, format %#x, channel mask 0x%X, flags %#x",
1640 device, config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001641 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001642 }
Eric Laurente552edb2014-03-10 17:42:56 -07001643 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001644 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08001645 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08001646 if (samplingRate == 0) {
1647 samplingRate = profileSamplingRate;
1648 }
Eric Laurente552edb2014-03-10 17:42:56 -07001649
Eric Laurent322b4d22015-04-03 15:57:54 -07001650 if (profile->getModuleHandle() == 0) {
1651 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001652 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001653 }
1654
Eric Laurent599c7582015-12-07 18:05:55 -08001655 sp<AudioSession> audioSession = new AudioSession(session,
Eric Laurentfe231122017-11-17 17:48:06 -08001656 inputSource,
1657 config->format,
1658 samplingRate,
1659 config->channel_mask,
1660 flags,
1661 uid,
1662 isSoundTrigger,
1663 policyMix, mpClientInterface);
Eric Laurent599c7582015-12-07 18:05:55 -08001664
Eric Laurent74708e72017-04-07 17:13:42 -07001665// FIXME: disable concurrent capture until UI is ready
1666#if 0
Eric Laurent599c7582015-12-07 18:05:55 -08001667 // reuse an open input if possible
Eric Laurent555530a2017-02-07 18:17:24 -08001668 sp<AudioInputDescriptor> reusedInputDesc;
Eric Laurent599c7582015-12-07 18:05:55 -08001669 for (size_t i = 0; i < mInputs.size(); i++) {
1670 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001671 // reuse input if:
1672 // - it shares the same profile
1673 // AND
1674 // - it is not a reroute submix input
1675 // AND
1676 // - it is: not used for sound trigger
1677 // OR
1678 // used for sound trigger and all clients use the same session ID
1679 //
1680 if ((profile == desc->mProfile) &&
1681 (isSoundTrigger == desc->isSoundTrigger()) &&
1682 !is_virtual_input_device(device)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001683
1684 sp<AudioSession> as = desc->getAudioSession(session);
1685 if (as != 0) {
1686 // do not allow unmatching properties on same session
1687 if (as->matches(audioSession)) {
1688 as->changeOpenCount(1);
1689 } else {
1690 ALOGW("getInputForDevice() record with different attributes"
1691 " exists for session %d", session);
Eric Laurent555530a2017-02-07 18:17:24 -08001692 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001693 }
Eric Laurentfb66dd92016-01-28 18:32:03 -08001694 } else if (isSoundTrigger) {
Eric Laurent555530a2017-02-07 18:17:24 -08001695 continue;
Eric Laurentfb66dd92016-01-28 18:32:03 -08001696 }
Eric Laurentbb948092017-01-23 18:33:30 -08001697
Eric Laurent555530a2017-02-07 18:17:24 -08001698 // Reuse the already opened input stream on this profile if:
1699 // - the new capture source is background OR
1700 // - the path requested configurations match OR
1701 // - the new source priority is less than the highest source priority on this input
1702 // If the input stream cannot be reused, close it before opening a new stream
1703 // on the same profile for the new client so that the requested path configuration
1704 // can be selected.
1705 if (!isConcurrentSource(inputSource) &&
Eric Laurentbb948092017-01-23 18:33:30 -08001706 ((desc->mSamplingRate != samplingRate ||
Eric Laurentfe231122017-11-17 17:48:06 -08001707 desc->mChannelMask != config->channel_mask ||
1708 !audio_formats_match(desc->mFormat, config->format)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001709 (source_priority(desc->getHighestPrioritySource(false /*activeOnly*/)) <
Eric Laurentbb948092017-01-23 18:33:30 -08001710 source_priority(inputSource)))) {
Eric Laurent555530a2017-02-07 18:17:24 -08001711 reusedInputDesc = desc;
1712 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001713 } else {
1714 desc->addAudioSession(session, audioSession);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001715 ALOGV("%s: reusing input %d", __FUNCTION__, mInputs.keyAt(i));
1716 return mInputs.keyAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08001717 }
Eric Laurent599c7582015-12-07 18:05:55 -08001718 }
1719 }
Eric Laurent599c7582015-12-07 18:05:55 -08001720
Eric Laurent555530a2017-02-07 18:17:24 -08001721 if (reusedInputDesc != 0) {
1722 AudioSessionCollection sessions = reusedInputDesc->getAudioSessions(false /*activeOnly*/);
1723 for (size_t j = 0; j < sessions.size(); j++) {
1724 audio_session_t currentSession = sessions.keyAt(j);
1725 stopInput(reusedInputDesc->mIoHandle, currentSession);
1726 releaseInput(reusedInputDesc->mIoHandle, currentSession);
1727 }
1728 }
Eric Laurent74708e72017-04-07 17:13:42 -07001729#endif
Eric Laurent555530a2017-02-07 18:17:24 -08001730
Eric Laurentf05fc902017-11-21 12:08:15 -08001731 if (!profile->canOpenNewIo()) {
1732 return AUDIO_IO_HANDLE_NONE;
1733 }
1734
Eric Laurentfe231122017-11-17 17:48:06 -08001735 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001736
Eric Laurentfe231122017-11-17 17:48:06 -08001737 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
1738 lConfig.sample_rate = profileSamplingRate;
1739 lConfig.channel_mask = profileChannelMask;
1740 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07001741
Eric Laurentfe231122017-11-17 17:48:06 -08001742 status_t status = inputDesc->open(&lConfig, device, address,
1743 halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001744
1745 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001746 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08001747 (profileSamplingRate != lConfig.sample_rate) ||
1748 !audio_formats_match(profileFormat, lConfig.format) ||
1749 (profileChannelMask != lConfig.channel_mask)) {
1750 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
1751 ", format %d, channel mask %x",
1752 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001753 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001754 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07001755 }
Eric Laurent599c7582015-12-07 18:05:55 -08001756 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001757 }
1758
Eric Laurentc722f302014-12-10 11:21:49 -08001759 inputDesc->mPolicyMix = policyMix;
Eric Laurent599c7582015-12-07 18:05:55 -08001760 inputDesc->addAudioSession(session, audioSession);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001761
Eric Laurent599c7582015-12-07 18:05:55 -08001762 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001763 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001764
Eric Laurent599c7582015-12-07 18:05:55 -08001765 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001766}
1767
Eric Laurentbb948092017-01-23 18:33:30 -08001768//static
1769bool AudioPolicyManager::isConcurrentSource(audio_source_t source)
1770{
1771 return (source == AUDIO_SOURCE_HOTWORD) ||
1772 (source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
1773 (source == AUDIO_SOURCE_FM_TUNER);
1774}
1775
Eric Laurentfb66dd92016-01-28 18:32:03 -08001776bool AudioPolicyManager::isConcurentCaptureAllowed(const sp<AudioInputDescriptor>& inputDesc,
1777 const sp<AudioSession>& audioSession)
1778{
1779 // Do not allow capture if an active voice call is using a software patch and
1780 // the call TX source device is on the same HW module.
1781 // FIXME: would be better to refine to only inputs whose profile connects to the
1782 // call TX device but this information is not in the audio patch
1783 if (mCallTxPatch != 0 &&
1784 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1785 return false;
1786 }
1787
1788 // starting concurrent capture is enabled if:
1789 // 1) capturing for re-routing
1790 // 2) capturing for HOTWORD source
1791 // 3) capturing for FM TUNER source
1792 // 3) All other active captures are either for re-routing or HOTWORD
1793
1794 if (is_virtual_input_device(inputDesc->mDevice) ||
Eric Laurentbb948092017-01-23 18:33:30 -08001795 isConcurrentSource(audioSession->inputSource())) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001796 return true;
1797 }
1798
1799 Vector< sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
1800 for (size_t i = 0; i < activeInputs.size(); i++) {
1801 sp<AudioInputDescriptor> activeInput = activeInputs[i];
Eric Laurentbb948092017-01-23 18:33:30 -08001802 if (!isConcurrentSource(activeInput->inputSource(true)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001803 !is_virtual_input_device(activeInput->mDevice)) {
1804 return false;
1805 }
1806 }
1807
1808 return true;
1809}
1810
Chris Thornton2b864642017-06-27 21:26:07 -07001811// FIXME: remove when concurrent capture is ready. This is a hack to work around bug b/63083537.
1812bool AudioPolicyManager::soundTriggerSupportsConcurrentCapture() {
1813 if (!mHasComputedSoundTriggerSupportsConcurrentCapture) {
1814 bool soundTriggerSupportsConcurrentCapture = false;
1815 unsigned int numModules = 0;
1816 struct sound_trigger_module_descriptor* nModules = NULL;
1817
1818 status_t status = SoundTrigger::listModules(nModules, &numModules);
1819 if (status == NO_ERROR && numModules != 0) {
1820 nModules = (struct sound_trigger_module_descriptor*) calloc(
1821 numModules, sizeof(struct sound_trigger_module_descriptor));
1822 if (nModules == NULL) {
1823 // We failed to malloc the buffer, so just say no for now, and hope that we have more
1824 // ram the next time this function is called.
1825 ALOGE("Failed to allocate buffer for module descriptors");
1826 return false;
1827 }
1828
1829 status = SoundTrigger::listModules(nModules, &numModules);
1830 if (status == NO_ERROR) {
1831 soundTriggerSupportsConcurrentCapture = true;
1832 for (size_t i = 0; i < numModules; ++i) {
1833 soundTriggerSupportsConcurrentCapture &=
1834 nModules[i].properties.concurrent_capture;
1835 }
1836 }
1837 free(nModules);
1838 }
1839 mSoundTriggerSupportsConcurrentCapture = soundTriggerSupportsConcurrentCapture;
1840 mHasComputedSoundTriggerSupportsConcurrentCapture = true;
1841 }
1842 return mSoundTriggerSupportsConcurrentCapture;
1843}
1844
Eric Laurentfb66dd92016-01-28 18:32:03 -08001845
Eric Laurent4dc68062014-07-28 17:26:49 -07001846status_t AudioPolicyManager::startInput(audio_io_handle_t input,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001847 audio_session_t session,
1848 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07001849{
1850 ALOGV("startInput() input %d", input);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001851 *concurrency = API_INPUT_CONCURRENCY_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001852 ssize_t index = mInputs.indexOfKey(input);
1853 if (index < 0) {
1854 ALOGW("startInput() unknown input %d", input);
1855 return BAD_VALUE;
1856 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001857 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001858
Eric Laurent599c7582015-12-07 18:05:55 -08001859 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1860 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07001861 ALOGW("startInput() unknown session %d on input %d", session, input);
1862 return BAD_VALUE;
1863 }
1864
Eric Laurent74708e72017-04-07 17:13:42 -07001865// FIXME: disable concurrent capture until UI is ready
1866#if 0
Eric Laurentfb66dd92016-01-28 18:32:03 -08001867 if (!isConcurentCaptureAllowed(inputDesc, audioSession)) {
1868 ALOGW("startInput(%d) failed: other input already started", input);
1869 return INVALID_OPERATION;
1870 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001871
Eric Laurentfb66dd92016-01-28 18:32:03 -08001872 if (isInCall()) {
1873 *concurrency |= API_INPUT_CONCURRENCY_CALL;
1874 }
Eric Laurentf7c50102016-09-30 15:19:43 -07001875 if (mInputs.activeInputsCountOnDevices() != 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001876 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurente552edb2014-03-10 17:42:56 -07001877 }
Eric Laurent74708e72017-04-07 17:13:42 -07001878#else
1879 if (!is_virtual_input_device(inputDesc->mDevice)) {
1880 if (mCallTxPatch != 0 &&
1881 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1882 ALOGW("startInput(%d) failed: call in progress", input);
1883 return INVALID_OPERATION;
1884 }
1885
1886 Vector< sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
1887 for (size_t i = 0; i < activeInputs.size(); i++) {
1888 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
1889
1890 if (is_virtual_input_device(activeDesc->mDevice)) {
1891 continue;
1892 }
1893
Eric Laurentcb4dae22017-07-01 19:39:32 -07001894 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
1895 activeDesc->getId() == inputDesc->getId()) {
1896 continue;
1897 }
1898
Eric Laurent74708e72017-04-07 17:13:42 -07001899 audio_source_t activeSource = activeDesc->inputSource(true);
1900 if (audioSession->inputSource() == AUDIO_SOURCE_HOTWORD) {
1901 if (activeSource == AUDIO_SOURCE_HOTWORD) {
1902 if (activeDesc->hasPreemptedSession(session)) {
1903 ALOGW("startInput(%d) failed for HOTWORD: "
1904 "other input %d already started for HOTWORD",
1905 input, activeDesc->mIoHandle);
1906 return INVALID_OPERATION;
1907 }
1908 } else {
1909 ALOGV("startInput(%d) failed for HOTWORD: other input %d already started",
1910 input, activeDesc->mIoHandle);
1911 return INVALID_OPERATION;
1912 }
1913 } else {
1914 if (activeSource != AUDIO_SOURCE_HOTWORD) {
1915 ALOGW("startInput(%d) failed: other input %d already started",
1916 input, activeDesc->mIoHandle);
1917 return INVALID_OPERATION;
1918 }
1919 }
1920 }
1921
Chris Thornton2b864642017-06-27 21:26:07 -07001922 // We only need to check if the sound trigger session supports concurrent capture if the
1923 // input is also a sound trigger input. Otherwise, we should preempt any hotword stream
1924 // that's running.
1925 const bool allowConcurrentWithSoundTrigger =
1926 inputDesc->isSoundTrigger() ? soundTriggerSupportsConcurrentCapture() : false;
1927
Eric Laurent74708e72017-04-07 17:13:42 -07001928 // if capture is allowed, preempt currently active HOTWORD captures
1929 for (size_t i = 0; i < activeInputs.size(); i++) {
1930 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
1931
1932 if (is_virtual_input_device(activeDesc->mDevice)) {
1933 continue;
1934 }
1935
Chris Thornton2b864642017-06-27 21:26:07 -07001936 if (allowConcurrentWithSoundTrigger && activeDesc->isSoundTrigger()) {
1937 continue;
1938 }
1939
Eric Laurent74708e72017-04-07 17:13:42 -07001940 audio_source_t activeSource = activeDesc->inputSource(true);
1941 if (activeSource == AUDIO_SOURCE_HOTWORD) {
1942 AudioSessionCollection activeSessions =
1943 activeDesc->getAudioSessions(true /*activeOnly*/);
1944 audio_session_t activeSession = activeSessions.keyAt(0);
1945 audio_io_handle_t activeHandle = activeDesc->mIoHandle;
1946 SortedVector<audio_session_t> sessions = activeDesc->getPreemptedSessions();
1947 sessions.add(activeSession);
1948 inputDesc->setPreemptedSessions(sessions);
1949 stopInput(activeHandle, activeSession);
1950 releaseInput(activeHandle, activeSession);
1951 ALOGV("startInput(%d) for HOTWORD preempting HOTWORD input %d",
1952 input, activeDesc->mIoHandle);
1953 }
1954 }
1955 }
1956#endif
Eric Laurente552edb2014-03-10 17:42:56 -07001957
Eric Laurent313d1e72016-01-29 09:56:57 -08001958 // increment activity count before calling getNewInputDevice() below as only active sessions
1959 // are considered for device selection
1960 audioSession->changeActiveCount(1);
1961
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001962 // Routing?
1963 mInputRoutes.incRouteActivity(session);
1964
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001965 if (audioSession->activeCount() == 1 || mInputRoutes.hasRouteChanged(session)) {
Eric Laurent271a93e2016-09-29 14:47:06 -07001966 // indicate active capture to sound trigger service if starting capture from a mic on
1967 // primary HW module
Eric Laurentf7c50102016-09-30 15:19:43 -07001968 audio_devices_t device = getNewInputDevice(inputDesc);
Eric Laurent271a93e2016-09-29 14:47:06 -07001969 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001970
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001971 if (inputDesc->getAudioSessionCount(true/*activeOnly*/) == 1) {
Eric Laurentf05fc902017-11-21 12:08:15 -08001972 if (!inputDesc->mProfile->canStartNewIo()) {
1973 mInputRoutes.decRouteActivity(session);
1974 audioSession->changeActiveCount(-1);
1975 return INVALID_OPERATION;
1976 }
1977 inputDesc->mProfile->curActiveCount++;
1978
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001979 // if input maps to a dynamic policy with an activity listener, notify of state change
1980 if ((inputDesc->mPolicyMix != NULL)
1981 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
1982 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
1983 MIX_STATE_MIXING);
Eric Laurentc722f302014-12-10 11:21:49 -08001984 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001985
Eric Laurentf7c50102016-09-30 15:19:43 -07001986 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
1987 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Eric Laurent05b345e2016-11-18 12:36:27 -08001988 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001989 SoundTrigger::setCaptureState(true);
1990 }
1991
1992 // automatically enable the remote submix output when input is started if not
1993 // used by a policy mix of type MIX_TYPE_RECORDERS
1994 // For remote submix (a virtual device), we open only one input per capture request.
1995 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1996 String8 address = String8("");
1997 if (inputDesc->mPolicyMix == NULL) {
1998 address = String8("0");
1999 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2000 address = inputDesc->mPolicyMix->mDeviceAddress;
2001 }
2002 if (address != "") {
2003 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2004 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2005 address, "remote-submix");
2006 }
Eric Laurentc722f302014-12-10 11:21:49 -08002007 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002008 }
Eric Laurente552edb2014-03-10 17:42:56 -07002009 }
2010
Eric Laurent599c7582015-12-07 18:05:55 -08002011 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
Eric Laurente552edb2014-03-10 17:42:56 -07002012
Eric Laurente552edb2014-03-10 17:42:56 -07002013 return NO_ERROR;
2014}
2015
Eric Laurent4dc68062014-07-28 17:26:49 -07002016status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
2017 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07002018{
2019 ALOGV("stopInput() input %d", input);
2020 ssize_t index = mInputs.indexOfKey(input);
2021 if (index < 0) {
2022 ALOGW("stopInput() unknown input %d", input);
2023 return BAD_VALUE;
2024 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002025 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07002026
Eric Laurent599c7582015-12-07 18:05:55 -08002027 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07002028 if (index < 0) {
2029 ALOGW("stopInput() unknown session %d on input %d", session, input);
2030 return BAD_VALUE;
2031 }
2032
Eric Laurent599c7582015-12-07 18:05:55 -08002033 if (audioSession->activeCount() == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002034 ALOGW("stopInput() input %d already stopped", input);
2035 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002036 }
2037
Eric Laurent599c7582015-12-07 18:05:55 -08002038 audioSession->changeActiveCount(-1);
Paul McLean466dc8e2015-04-17 13:15:36 -06002039
2040 // Routing?
2041 mInputRoutes.decRouteActivity(session);
2042
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002043 if (audioSession->activeCount() == 0) {
Eric Laurent84332aa2016-01-28 22:19:18 +00002044
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002045 if (inputDesc->isActive()) {
2046 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2047 } else {
Eric Laurentf05fc902017-11-21 12:08:15 -08002048 LOG_ALWAYS_FATAL_IF(inputDesc->mProfile->curActiveCount < 1,
2049 "%s invalid profile active count %u",
2050 __FUNCTION__, inputDesc->mProfile->curActiveCount);
2051 inputDesc->mProfile->curActiveCount--;
2052
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002053 // if input maps to a dynamic policy with an activity listener, notify of state change
2054 if ((inputDesc->mPolicyMix != NULL)
2055 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2056 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2057 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002058 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002059
2060 // automatically disable the remote submix output when input is stopped if not
2061 // used by a policy mix of type MIX_TYPE_RECORDERS
2062 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2063 String8 address = String8("");
2064 if (inputDesc->mPolicyMix == NULL) {
2065 address = String8("0");
2066 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2067 address = inputDesc->mPolicyMix->mDeviceAddress;
2068 }
2069 if (address != "") {
2070 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2071 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2072 address, "remote-submix");
2073 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002074 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002075
Eric Laurentf7c50102016-09-30 15:19:43 -07002076 audio_devices_t device = inputDesc->mDevice;
Eric Laurentfb66dd92016-01-28 18:32:03 -08002077 resetInputDevice(input);
Eric Laurent84332aa2016-01-28 22:19:18 +00002078
Eric Laurentf7c50102016-09-30 15:19:43 -07002079 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2080 // primary HW module
2081 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2082 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2083 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08002084 SoundTrigger::setCaptureState(false);
2085 }
2086 inputDesc->clearPreemptedSessions();
Eric Laurent84332aa2016-01-28 22:19:18 +00002087 }
Eric Laurente552edb2014-03-10 17:42:56 -07002088 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002089 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002090}
2091
Eric Laurent4dc68062014-07-28 17:26:49 -07002092void AudioPolicyManager::releaseInput(audio_io_handle_t input,
2093 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07002094{
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002095
Eric Laurente552edb2014-03-10 17:42:56 -07002096 ALOGV("releaseInput() %d", input);
2097 ssize_t index = mInputs.indexOfKey(input);
2098 if (index < 0) {
2099 ALOGW("releaseInput() releasing unknown input %d", input);
2100 return;
2101 }
Paul McLean466dc8e2015-04-17 13:15:36 -06002102
2103 // Routing
2104 mInputRoutes.removeRoute(session);
2105
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002106 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
2107 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07002108
Eric Laurent599c7582015-12-07 18:05:55 -08002109 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
vivek mehta587b8df2017-01-31 14:58:44 -08002110 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07002111 ALOGW("releaseInput() unknown session %d on input %d", session, input);
2112 return;
2113 }
Eric Laurent599c7582015-12-07 18:05:55 -08002114
2115 if (audioSession->openCount() == 0) {
2116 ALOGW("releaseInput() invalid open count %d on session %d",
2117 audioSession->openCount(), session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002118 return;
2119 }
Eric Laurent599c7582015-12-07 18:05:55 -08002120
2121 if (audioSession->changeOpenCount(-1) == 0) {
2122 inputDesc->removeAudioSession(session);
2123 }
2124
Jean-Michel Trivi65bfe912015-12-04 15:56:47 -08002125 if (inputDesc->getOpenRefCount() > 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002126 ALOGV("releaseInput() exit > 0");
2127 return;
2128 }
2129
Eric Laurent05b90f82014-08-27 15:32:29 -07002130 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002131 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002132 ALOGV("releaseInput() exit");
2133}
2134
Eric Laurentd4692962014-05-05 18:13:44 -07002135void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002136 bool patchRemoved = false;
2137
Eric Laurentd4692962014-05-05 18:13:44 -07002138 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002139 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002140 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002141 if (patch_index >= 0) {
2142 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002143 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002144 mAudioPatches.removeItemsAt(patch_index);
2145 patchRemoved = true;
2146 }
Eric Laurentfe231122017-11-17 17:48:06 -08002147 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002148 }
2149 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002150 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002151 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002152
2153 if (patchRemoved) {
2154 mpClientInterface->onAudioPatchListUpdate();
2155 }
Eric Laurentd4692962014-05-05 18:13:44 -07002156}
2157
Eric Laurente0720872014-03-11 09:30:41 -07002158void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002159 int indexMin,
2160 int indexMax)
2161{
2162 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002163 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002164
2165 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002166 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2167 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002168 continue;
2169 }
2170 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002171 }
Eric Laurente552edb2014-03-10 17:42:56 -07002172}
2173
Eric Laurente0720872014-03-11 09:30:41 -07002174status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002175 int index,
2176 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002177{
2178
François Gaffied1ab2bd2015-12-02 18:20:06 +01002179 if ((index < mVolumeCurves->getVolumeIndexMin(stream)) ||
2180 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002181 return BAD_VALUE;
2182 }
2183 if (!audio_is_output_device(device)) {
2184 return BAD_VALUE;
2185 }
2186
2187 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002188 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002189
Eric Laurent1fd372e2016-04-06 14:23:53 -07002190 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002191 stream, device, index);
2192
Eric Laurent28d09f02016-03-08 10:43:05 -08002193 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002194 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2195 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002196 continue;
2197 }
2198 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2199 }
Eric Laurente552edb2014-03-10 17:42:56 -07002200
Eric Laurent1fd372e2016-04-06 14:23:53 -07002201 // update volume on all outputs and streams matching the following:
2202 // - The requested stream (or a stream matching for volume control) is active on the output
2203 // - The device (or devices) selected by the strategy corresponding to this stream includes
2204 // the requested device
2205 // - For non default requested device, currently selected device on the output is either the
2206 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002207 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2208 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002209 status_t status = NO_ERROR;
2210 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002211 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2212 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08002213 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2214 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002215 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002216 }
Eric Laurentd3926fe2016-04-15 18:10:07 -07002217 if (!(desc->isStreamActive((audio_stream_type_t)curStream) ||
2218 (isInCall() && (curStream == AUDIO_STREAM_VOICE_CALL)))) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002219 continue;
2220 }
Eric Laurent794fde22016-03-11 09:50:45 -08002221 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002222 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2223 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002224 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2225 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002226 continue;
2227 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002228 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002229 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002230 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07002231 applyVolume = (curDevice & curStreamDevice) != 0;
2232 } else {
2233 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002234 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002235 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002236
Eric Laurente76f29c2016-09-14 17:17:53 -07002237 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002238 //FIXME: workaround for truncated touch sounds
2239 // delayed volume change for system stream to be removed when the problem is
2240 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002241 status_t volStatus =
Eric Laurentdc462862016-07-19 12:29:53 -07002242 checkAndSetVolume((audio_stream_type_t)curStream, index, desc, curDevice,
2243 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002244 if (volStatus != NO_ERROR) {
2245 status = volStatus;
2246 }
2247 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002248 }
Eric Laurente552edb2014-03-10 17:42:56 -07002249 }
2250 return status;
2251}
2252
Eric Laurente0720872014-03-11 09:30:41 -07002253status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002254 int *index,
2255 audio_devices_t device)
2256{
2257 if (index == NULL) {
2258 return BAD_VALUE;
2259 }
2260 if (!audio_is_output_device(device)) {
2261 return BAD_VALUE;
2262 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002263 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002264 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002265 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002266 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2267 }
François Gaffiedfd74092015-03-19 12:10:59 +01002268 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002269
François Gaffied1ab2bd2015-12-02 18:20:06 +01002270 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002271 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2272 return NO_ERROR;
2273}
2274
Eric Laurent36829f92017-04-07 19:04:42 -07002275audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002276{
2277 // select one output among several suitable for global effects.
2278 // The priority is as follows:
2279 // 1: An offloaded output. If the effect ends up not being offloadable,
2280 // AudioFlinger will invalidate the track and the offloaded output
2281 // will be closed causing the effect to be moved to a PCM output.
2282 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002283 // 3: The primary output
2284 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002285
Eric Laurent3b73df72014-03-11 09:06:29 -07002286 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002287 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent36829f92017-04-07 19:04:42 -07002288 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002289
Eric Laurent36829f92017-04-07 19:04:42 -07002290 if (outputs.size() == 0) {
2291 return AUDIO_IO_HANDLE_NONE;
2292 }
Eric Laurente552edb2014-03-10 17:42:56 -07002293
Eric Laurent36829f92017-04-07 19:04:42 -07002294 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2295 bool activeOnly = true;
2296
2297 while (output == AUDIO_IO_HANDLE_NONE) {
2298 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2299 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2300 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2301
2302 for (size_t i = 0; i < outputs.size(); i++) {
2303 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
2304 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2305 continue;
2306 }
2307 ALOGV("selectOutputForMusicEffects activeOnly %d outputs[%zu] flags 0x%08x",
2308 activeOnly, i, desc->mFlags);
2309 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
2310 outputOffloaded = outputs[i];
2311 }
2312 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
2313 outputDeepBuffer = outputs[i];
2314 }
2315 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
2316 outputPrimary = outputs[i];
2317 }
2318 }
2319 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2320 output = outputOffloaded;
2321 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2322 output = outputDeepBuffer;
2323 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2324 output = outputPrimary;
2325 } else {
2326 output = outputs[0];
2327 }
2328 activeOnly = false;
2329 }
2330
2331 if (output != mMusicEffectOutput) {
2332 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2333 mMusicEffectOutput = output;
2334 }
2335
2336 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002337 return output;
2338}
2339
Eric Laurent36829f92017-04-07 19:04:42 -07002340audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2341{
2342 return selectOutputForMusicEffects();
2343}
2344
Eric Laurente0720872014-03-11 09:30:41 -07002345status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002346 audio_io_handle_t io,
2347 uint32_t strategy,
2348 int session,
2349 int id)
2350{
2351 ssize_t index = mOutputs.indexOfKey(io);
2352 if (index < 0) {
2353 index = mInputs.indexOfKey(io);
2354 if (index < 0) {
2355 ALOGW("registerEffect() unknown io %d", io);
2356 return INVALID_OPERATION;
2357 }
2358 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002359 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002360}
2361
Eric Laurentc75307b2015-03-17 15:29:32 -07002362bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2363{
Eric Laurent28d09f02016-03-08 10:43:05 -08002364 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002365 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2366 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002367 continue;
2368 }
2369 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2370 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002371 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002372}
2373
2374bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2375{
2376 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2377}
2378
Eric Laurente0720872014-03-11 09:30:41 -07002379bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002380{
2381 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002382 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002383 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002384 return true;
2385 }
2386 }
2387 return false;
2388}
2389
Eric Laurent275e8e92014-11-30 15:14:47 -08002390// Register a list of custom mixes with their attributes and format.
2391// When a mix is registered, corresponding input and output profiles are
2392// added to the remote submix hw module. The profile contains only the
2393// parameters (sampling rate, format...) specified by the mix.
2394// The corresponding input remote submix device is also connected.
2395//
2396// When a remote submix device is connected, the address is checked to select the
2397// appropriate profile and the corresponding input or output stream is opened.
2398//
2399// When capture starts, getInputForAttr() will:
2400// - 1 look for a mix matching the address passed in attribtutes tags if any
2401// - 2 if none found, getDeviceForInputSource() will:
2402// - 2.1 look for a mix matching the attributes source
2403// - 2.2 if none found, default to device selection by policy rules
2404// At this time, the corresponding output remote submix device is also connected
2405// and active playback use cases can be transferred to this mix if needed when reconnecting
2406// after AudioTracks are invalidated
2407//
2408// When playback starts, getOutputForAttr() will:
2409// - 1 look for a mix matching the address passed in attribtutes tags if any
2410// - 2 if none found, look for a mix matching the attributes usage
2411// - 3 if none found, default to device and output selection by policy rules.
2412
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002413status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002414{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002415 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2416 status_t res = NO_ERROR;
2417
2418 sp<HwModule> rSubmixModule;
2419 // examine each mix's route type
2420 for (size_t i = 0; i < mixes.size(); i++) {
2421 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
2422 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
2423 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002424 break;
2425 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002426 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
2427 // Loop back through "remote submix"
2428 if (rSubmixModule == 0) {
2429 for (size_t j = 0; i < mHwModules.size(); j++) {
2430 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
2431 && mHwModules[j]->mHandle != 0) {
2432 rSubmixModule = mHwModules[j];
2433 break;
2434 }
2435 }
2436 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002437
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002438 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Eric Laurent275e8e92014-11-30 15:14:47 -08002439
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002440 if (rSubmixModule == 0) {
2441 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration", i);
2442 res = INVALID_OPERATION;
2443 break;
2444 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002445
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002446 String8 address = mixes[i].mDeviceAddress;
François Gaffie036e1e92015-03-19 10:16:24 +01002447
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002448 if (mPolicyMixes.registerMix(address, mixes[i], 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002449 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002450 res = INVALID_OPERATION;
2451 break;
2452 }
2453 audio_config_t outputConfig = mixes[i].mFormat;
2454 audio_config_t inputConfig = mixes[i].mFormat;
2455 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2456 // stereo and let audio flinger do the channel conversion if needed.
2457 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2458 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2459 rSubmixModule->addOutputProfile(address, &outputConfig,
2460 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2461 rSubmixModule->addInputProfile(address, &inputConfig,
2462 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002463
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002464 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
2465 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2466 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2467 address.string(), "remote-submix");
2468 } else {
2469 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2470 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2471 address.string(), "remote-submix");
2472 }
2473 } else if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002474 String8 address = mixes[i].mDeviceAddress;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002475 audio_devices_t device = mixes[i].mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002476 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2477 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002478
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002479 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002480 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2481 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2482 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2483 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2484 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2485 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002486 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2487 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002488 if (mPolicyMixes.registerMix(address, mixes[i], desc) != NO_ERROR) {
2489 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002490 } else {
2491 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002492 }
2493 break;
2494 }
2495 }
2496
2497 if (res != NO_ERROR) {
2498 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002499 i, device, address.string());
2500 res = INVALID_OPERATION;
2501 break;
2502 } else if (!foundOutput) {
2503 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2504 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002505 res = INVALID_OPERATION;
2506 break;
2507 }
Eric Laurentc722f302014-12-10 11:21:49 -08002508 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002509 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002510 if (res != NO_ERROR) {
2511 unregisterPolicyMixes(mixes);
2512 }
2513 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002514}
2515
2516status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2517{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002518 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002519 status_t res = NO_ERROR;
2520 sp<HwModule> rSubmixModule;
2521 // examine each mix's route type
Eric Laurent275e8e92014-11-30 15:14:47 -08002522 for (size_t i = 0; i < mixes.size(); i++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002523 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002524
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002525 if (rSubmixModule == 0) {
2526 for (size_t j = 0; i < mHwModules.size(); j++) {
2527 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
2528 && mHwModules[j]->mHandle != 0) {
2529 rSubmixModule = mHwModules[j];
2530 break;
2531 }
2532 }
2533 }
2534 if (rSubmixModule == 0) {
2535 res = INVALID_OPERATION;
2536 continue;
2537 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002538
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002539 String8 address = mixes[i].mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002540
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002541 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2542 res = INVALID_OPERATION;
2543 continue;
2544 }
2545
2546 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2547 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2548 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2549 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2550 address.string(), "remote-submix");
2551 }
2552 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2553 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2554 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2555 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2556 address.string(), "remote-submix");
2557 }
2558 rSubmixModule->removeOutputProfile(address);
2559 rSubmixModule->removeInputProfile(address);
2560
2561 } if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2562 if (mPolicyMixes.unregisterMix(mixes[i].mDeviceAddress) != NO_ERROR) {
2563 res = INVALID_OPERATION;
2564 continue;
2565 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002566 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002567 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002568 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002569}
2570
Eric Laurente552edb2014-03-10 17:42:56 -07002571
Eric Laurente0720872014-03-11 09:30:41 -07002572status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002573{
2574 const size_t SIZE = 256;
2575 char buffer[SIZE];
2576 String8 result;
2577
2578 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2579 result.append(buffer);
2580
Eric Laurent87ffa392015-05-22 10:32:38 -07002581 snprintf(buffer, SIZE, " Primary Output: %d\n",
2582 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Eric Laurente552edb2014-03-10 17:42:56 -07002583 result.append(buffer);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002584 std::string stateLiteral;
2585 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
2586 snprintf(buffer, SIZE, " Phone state: %s\n", stateLiteral.c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002587 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002588 snprintf(buffer, SIZE, " Force use for communications %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002589 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07002590 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002591 snprintf(buffer, SIZE, " Force use for media %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA));
Eric Laurente552edb2014-03-10 17:42:56 -07002592 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002593 snprintf(buffer, SIZE, " Force use for record %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD));
Eric Laurente552edb2014-03-10 17:42:56 -07002594 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002595 snprintf(buffer, SIZE, " Force use for dock %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_DOCK));
Eric Laurente552edb2014-03-10 17:42:56 -07002596 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002597 snprintf(buffer, SIZE, " Force use for system %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM));
Eric Laurente552edb2014-03-10 17:42:56 -07002598 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002599 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002600 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO));
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002601 result.append(buffer);
Phil Burk09bc4612016-02-24 15:58:15 -08002602 snprintf(buffer, SIZE, " Force use for encoded surround output %d\n",
2603 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND));
2604 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002605 snprintf(buffer, SIZE, " TTS output %s\n", mTtsOutputAvailable ? "available" : "not available");
2606 result.append(buffer);
Andy Hung2ddee192015-12-18 17:34:44 -08002607 snprintf(buffer, SIZE, " Master mono: %s\n", mMasterMono ? "on" : "off");
2608 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002609
François Gaffie2110e042015-03-24 08:41:51 +01002610 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002611
François Gaffie112b0af2015-11-19 16:13:25 +01002612 mAvailableOutputDevices.dump(fd, String8("Available output"));
2613 mAvailableInputDevices.dump(fd, String8("Available input"));
François Gaffie53615e22015-03-19 09:24:12 +01002614 mHwModules.dump(fd);
2615 mOutputs.dump(fd);
2616 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002617 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002618 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002619 mAudioPatches.dump(fd);
Mikhail Naganov44344b02016-12-13 11:21:02 -08002620 mPolicyMixes.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002621
2622 return NO_ERROR;
2623}
2624
2625// This function checks for the parameters which can be offloaded.
2626// This can be enhanced depending on the capability of the DSP and policy
2627// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002628bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002629{
2630 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002631 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002632 offloadInfo.sample_rate, offloadInfo.channel_mask,
2633 offloadInfo.format,
2634 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2635 offloadInfo.has_video);
2636
Andy Hung2ddee192015-12-18 17:34:44 -08002637 if (mMasterMono) {
2638 return false; // no offloading if mono is set.
2639 }
2640
Eric Laurente552edb2014-03-10 17:42:56 -07002641 // Check if offload has been disabled
2642 char propValue[PROPERTY_VALUE_MAX];
2643 if (property_get("audio.offload.disable", propValue, "0")) {
2644 if (atoi(propValue) != 0) {
2645 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2646 return false;
2647 }
2648 }
2649
2650 // Check if stream type is music, then only allow offload as of now.
2651 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2652 {
2653 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2654 return false;
2655 }
2656
2657 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002658 const bool allowOffloadWithVideo =
2659 property_get_bool("audio.offload.video", false /* default_value */);
2660 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002661 ALOGV("isOffloadSupported: has_video == true, returning false");
2662 return false;
2663 }
2664
2665 //If duration is less than minimum value defined in property, return false
2666 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2667 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2668 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2669 return false;
2670 }
2671 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2672 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2673 return false;
2674 }
2675
2676 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2677 // creating an offloaded track and tearing it down immediately after start when audioflinger
2678 // detects there is an active non offloadable effect.
2679 // FIXME: We should check the audio session here but we do not have it in this context.
2680 // This may prevent offloading in rare situations where effects are left active by apps
2681 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002682 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002683 return false;
2684 }
2685
2686 // See if there is a profile to support this.
2687 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002688 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002689 offloadInfo.sample_rate,
2690 offloadInfo.format,
2691 offloadInfo.channel_mask,
2692 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002693 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2694 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002695}
2696
Eric Laurent6a94d692014-05-20 11:18:06 -07002697status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2698 audio_port_type_t type,
2699 unsigned int *num_ports,
2700 struct audio_port *ports,
2701 unsigned int *generation)
2702{
2703 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2704 generation == NULL) {
2705 return BAD_VALUE;
2706 }
2707 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2708 if (ports == NULL) {
2709 *num_ports = 0;
2710 }
2711
2712 size_t portsWritten = 0;
2713 size_t portsMax = *num_ports;
2714 *num_ports = 0;
2715 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002716 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2717 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002718 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002719 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
2720 if (mAvailableOutputDevices[i]->type() == AUDIO_DEVICE_OUT_STUB) {
2721 continue;
2722 }
2723 if (portsWritten < portsMax) {
2724 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2725 }
2726 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002727 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002728 }
2729 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002730 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2731 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_STUB) {
2732 continue;
2733 }
2734 if (portsWritten < portsMax) {
2735 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2736 }
2737 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002738 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002739 }
2740 }
2741 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2742 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2743 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2744 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2745 }
2746 *num_ports += mInputs.size();
2747 }
2748 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002749 size_t numOutputs = 0;
2750 for (size_t i = 0; i < mOutputs.size(); i++) {
2751 if (!mOutputs[i]->isDuplicated()) {
2752 numOutputs++;
2753 if (portsWritten < portsMax) {
2754 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2755 }
2756 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002757 }
Eric Laurent84c70242014-06-23 08:46:27 -07002758 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002759 }
2760 }
2761 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002762 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002763 return NO_ERROR;
2764}
2765
2766status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2767{
2768 return NO_ERROR;
2769}
2770
Eric Laurent6a94d692014-05-20 11:18:06 -07002771status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2772 audio_patch_handle_t *handle,
2773 uid_t uid)
2774{
2775 ALOGV("createAudioPatch()");
2776
2777 if (handle == NULL || patch == NULL) {
2778 return BAD_VALUE;
2779 }
2780 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2781
Eric Laurent874c42872014-08-08 15:13:39 -07002782 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2783 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2784 return BAD_VALUE;
2785 }
2786 // only one source per audio patch supported for now
2787 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002788 return INVALID_OPERATION;
2789 }
Eric Laurent874c42872014-08-08 15:13:39 -07002790
2791 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002792 return INVALID_OPERATION;
2793 }
Eric Laurent874c42872014-08-08 15:13:39 -07002794 for (size_t i = 0; i < patch->num_sinks; i++) {
2795 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2796 return INVALID_OPERATION;
2797 }
2798 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002799
2800 sp<AudioPatch> patchDesc;
2801 ssize_t index = mAudioPatches.indexOfKey(*handle);
2802
Eric Laurent6a94d692014-05-20 11:18:06 -07002803 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2804 patch->sources[0].role,
2805 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002806#if LOG_NDEBUG == 0
2807 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002808 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002809 patch->sinks[i].role,
2810 patch->sinks[i].type);
2811 }
2812#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002813
2814 if (index >= 0) {
2815 patchDesc = mAudioPatches.valueAt(index);
2816 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2817 mUidCached, patchDesc->mUid, uid);
2818 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2819 return INVALID_OPERATION;
2820 }
2821 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002822 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002823 }
2824
2825 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002826 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002827 if (outputDesc == NULL) {
2828 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2829 return BAD_VALUE;
2830 }
Eric Laurent84c70242014-06-23 08:46:27 -07002831 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2832 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002833 if (patchDesc != 0) {
2834 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2835 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2836 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2837 return BAD_VALUE;
2838 }
2839 }
Eric Laurent874c42872014-08-08 15:13:39 -07002840 DeviceVector devices;
2841 for (size_t i = 0; i < patch->num_sinks; i++) {
2842 // Only support mix to devices connection
2843 // TODO add support for mix to mix connection
2844 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2845 ALOGV("createAudioPatch() source mix but sink is not a device");
2846 return INVALID_OPERATION;
2847 }
2848 sp<DeviceDescriptor> devDesc =
2849 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2850 if (devDesc == 0) {
2851 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2852 return BAD_VALUE;
2853 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002854
François Gaffie53615e22015-03-19 09:24:12 +01002855 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002856 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002857 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002858 NULL, // updatedSamplingRate
2859 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002860 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002861 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002862 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002863 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002864 ALOGV("createAudioPatch() profile not supported for device %08x",
2865 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002866 return INVALID_OPERATION;
2867 }
2868 devices.add(devDesc);
2869 }
2870 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002871 return INVALID_OPERATION;
2872 }
Eric Laurent874c42872014-08-08 15:13:39 -07002873
Eric Laurent6a94d692014-05-20 11:18:06 -07002874 // TODO: reconfigure output format and channels here
2875 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002876 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002877 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002878 index = mAudioPatches.indexOfKey(*handle);
2879 if (index >= 0) {
2880 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2881 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2882 }
2883 patchDesc = mAudioPatches.valueAt(index);
2884 patchDesc->mUid = uid;
2885 ALOGV("createAudioPatch() success");
2886 } else {
2887 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2888 return INVALID_OPERATION;
2889 }
2890 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2891 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2892 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002893 // only one sink supported when connecting an input device to a mix
2894 if (patch->num_sinks > 1) {
2895 return INVALID_OPERATION;
2896 }
François Gaffie53615e22015-03-19 09:24:12 +01002897 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002898 if (inputDesc == NULL) {
2899 return BAD_VALUE;
2900 }
2901 if (patchDesc != 0) {
2902 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2903 return BAD_VALUE;
2904 }
2905 }
2906 sp<DeviceDescriptor> devDesc =
2907 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2908 if (devDesc == 0) {
2909 return BAD_VALUE;
2910 }
2911
François Gaffie53615e22015-03-19 09:24:12 +01002912 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002913 devDesc->mAddress,
2914 patch->sinks[0].sample_rate,
2915 NULL, /*updatedSampleRate*/
2916 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002917 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002918 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002919 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002920 // FIXME for the parameter type,
2921 // and the NONE
2922 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002923 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002924 return INVALID_OPERATION;
2925 }
2926 // TODO: reconfigure output format and channels here
2927 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01002928 devDesc->type(), inputDesc->mIoHandle);
2929 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002930 index = mAudioPatches.indexOfKey(*handle);
2931 if (index >= 0) {
2932 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2933 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2934 }
2935 patchDesc = mAudioPatches.valueAt(index);
2936 patchDesc->mUid = uid;
2937 ALOGV("createAudioPatch() success");
2938 } else {
2939 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2940 return INVALID_OPERATION;
2941 }
2942 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2943 // device to device connection
2944 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002945 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002946 return BAD_VALUE;
2947 }
2948 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002949 sp<DeviceDescriptor> srcDeviceDesc =
2950 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002951 if (srcDeviceDesc == 0) {
2952 return BAD_VALUE;
2953 }
Eric Laurent874c42872014-08-08 15:13:39 -07002954
Eric Laurent6a94d692014-05-20 11:18:06 -07002955 //update source and sink with our own data as the data passed in the patch may
2956 // be incomplete.
2957 struct audio_patch newPatch = *patch;
2958 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002959
Eric Laurent874c42872014-08-08 15:13:39 -07002960 for (size_t i = 0; i < patch->num_sinks; i++) {
2961 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2962 ALOGV("createAudioPatch() source device but one sink is not a device");
2963 return INVALID_OPERATION;
2964 }
2965
2966 sp<DeviceDescriptor> sinkDeviceDesc =
2967 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2968 if (sinkDeviceDesc == 0) {
2969 return BAD_VALUE;
2970 }
2971 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2972
Eric Laurent3bcf8592015-04-03 12:13:24 -07002973 // create a software bridge in PatchPanel if:
2974 // - source and sink devices are on differnt HW modules OR
2975 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08002976 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07002977 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07002978 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07002979 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002980 return INVALID_OPERATION;
2981 }
Eric Laurent874c42872014-08-08 15:13:39 -07002982 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01002983 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07002984 // if the sink device is reachable via an opened output stream, request to go via
2985 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002986 audio_io_handle_t output = selectOutput(outputs,
2987 AUDIO_OUTPUT_FLAG_NONE,
2988 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002989 if (output != AUDIO_IO_HANDLE_NONE) {
2990 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2991 if (outputDesc->isDuplicated()) {
2992 return INVALID_OPERATION;
2993 }
2994 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07002995 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07002996 newPatch.num_sources = 2;
2997 }
Eric Laurent83b88082014-06-20 18:31:16 -07002998 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002999 }
3000 // TODO: check from routing capabilities in config file and other conflicting patches
3001
3002 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3003 if (index >= 0) {
3004 afPatchHandle = patchDesc->mAfPatchHandle;
3005 }
3006
3007 status_t status = mpClientInterface->createAudioPatch(&newPatch,
3008 &afPatchHandle,
3009 0);
3010 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
3011 status, afPatchHandle);
3012 if (status == NO_ERROR) {
3013 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01003014 patchDesc = new AudioPatch(&newPatch, uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003015 addAudioPatch(patchDesc->mHandle, patchDesc);
3016 } else {
3017 patchDesc->mPatch = newPatch;
3018 }
3019 patchDesc->mAfPatchHandle = afPatchHandle;
3020 *handle = patchDesc->mHandle;
3021 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003022 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003023 } else {
3024 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3025 status);
3026 return INVALID_OPERATION;
3027 }
3028 } else {
3029 return BAD_VALUE;
3030 }
3031 } else {
3032 return BAD_VALUE;
3033 }
3034 return NO_ERROR;
3035}
3036
3037status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3038 uid_t uid)
3039{
3040 ALOGV("releaseAudioPatch() patch %d", handle);
3041
3042 ssize_t index = mAudioPatches.indexOfKey(handle);
3043
3044 if (index < 0) {
3045 return BAD_VALUE;
3046 }
3047 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3048 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3049 mUidCached, patchDesc->mUid, uid);
3050 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3051 return INVALID_OPERATION;
3052 }
3053
3054 struct audio_patch *patch = &patchDesc->mPatch;
3055 patchDesc->mUid = mUidCached;
3056 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003057 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003058 if (outputDesc == NULL) {
3059 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3060 return BAD_VALUE;
3061 }
3062
Eric Laurentc75307b2015-03-17 15:29:32 -07003063 setOutputDevice(outputDesc,
3064 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07003065 true,
3066 0,
3067 NULL);
3068 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3069 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003070 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003071 if (inputDesc == NULL) {
3072 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3073 return BAD_VALUE;
3074 }
3075 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003076 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003077 true,
3078 NULL);
3079 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003080 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3081 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3082 status, patchDesc->mAfPatchHandle);
3083 removeAudioPatch(patchDesc->mHandle);
3084 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003085 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003086 } else {
3087 return BAD_VALUE;
3088 }
3089 } else {
3090 return BAD_VALUE;
3091 }
3092 return NO_ERROR;
3093}
3094
3095status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3096 struct audio_patch *patches,
3097 unsigned int *generation)
3098{
François Gaffie53615e22015-03-19 09:24:12 +01003099 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003100 return BAD_VALUE;
3101 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003102 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003103 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003104}
3105
Eric Laurente1715a42014-05-20 11:30:42 -07003106status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003107{
Eric Laurente1715a42014-05-20 11:30:42 -07003108 ALOGV("setAudioPortConfig()");
3109
3110 if (config == NULL) {
3111 return BAD_VALUE;
3112 }
3113 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3114 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003115 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3116 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003117 }
3118
Eric Laurenta121f902014-06-03 13:32:54 -07003119 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003120 if (config->type == AUDIO_PORT_TYPE_MIX) {
3121 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003122 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003123 if (outputDesc == NULL) {
3124 return BAD_VALUE;
3125 }
Eric Laurent84c70242014-06-23 08:46:27 -07003126 ALOG_ASSERT(!outputDesc->isDuplicated(),
3127 "setAudioPortConfig() called on duplicated output %d",
3128 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003129 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003130 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003131 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003132 if (inputDesc == NULL) {
3133 return BAD_VALUE;
3134 }
Eric Laurenta121f902014-06-03 13:32:54 -07003135 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003136 } else {
3137 return BAD_VALUE;
3138 }
3139 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3140 sp<DeviceDescriptor> deviceDesc;
3141 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3142 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3143 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3144 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3145 } else {
3146 return BAD_VALUE;
3147 }
3148 if (deviceDesc == NULL) {
3149 return BAD_VALUE;
3150 }
Eric Laurenta121f902014-06-03 13:32:54 -07003151 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003152 } else {
3153 return BAD_VALUE;
3154 }
3155
Eric Laurenta121f902014-06-03 13:32:54 -07003156 struct audio_port_config backupConfig;
3157 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3158 if (status == NO_ERROR) {
3159 struct audio_port_config newConfig;
3160 audioPortConfig->toAudioPortConfig(&newConfig, config);
3161 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003162 }
Eric Laurenta121f902014-06-03 13:32:54 -07003163 if (status != NO_ERROR) {
3164 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003165 }
Eric Laurente1715a42014-05-20 11:30:42 -07003166
3167 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003168}
3169
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003170void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3171{
Eric Laurentd60560a2015-04-10 11:31:20 -07003172 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003173 clearAudioPatches(uid);
3174 clearSessionRoutes(uid);
3175}
3176
Eric Laurent6a94d692014-05-20 11:18:06 -07003177void AudioPolicyManager::clearAudioPatches(uid_t uid)
3178{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003179 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003180 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3181 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003182 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003183 }
3184 }
3185}
3186
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003187void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3188 audio_io_handle_t ouptutToSkip)
3189{
3190 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3191 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3192 for (size_t j = 0; j < mOutputs.size(); j++) {
3193 if (mOutputs.keyAt(j) == ouptutToSkip) {
3194 continue;
3195 }
3196 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3197 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3198 continue;
3199 }
3200 // If the default device for this strategy is on another output mix,
3201 // invalidate all tracks in this strategy to force re connection.
3202 // Otherwise select new device on the output mix.
3203 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003204 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003205 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3206 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3207 }
3208 }
3209 } else {
3210 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3211 setOutputDevice(outputDesc, newDevice, false);
3212 }
3213 }
3214}
3215
3216void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3217{
3218 // remove output routes associated with this uid
3219 SortedVector<routing_strategy> affectedStrategies;
3220 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
3221 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
3222 if (route->mUid == uid) {
3223 mOutputRoutes.removeItemsAt(i);
3224 if (route->mDeviceDescriptor != 0) {
3225 affectedStrategies.add(getStrategy(route->mStreamType));
3226 }
3227 }
3228 }
3229 // reroute outputs if necessary
3230 for (size_t i = 0; i < affectedStrategies.size(); i++) {
3231 checkStrategyRoute(affectedStrategies[i], AUDIO_IO_HANDLE_NONE);
3232 }
3233
3234 // remove input routes associated with this uid
3235 SortedVector<audio_source_t> affectedSources;
3236 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
3237 sp<SessionRoute> route = mInputRoutes.valueAt(i);
3238 if (route->mUid == uid) {
3239 mInputRoutes.removeItemsAt(i);
3240 if (route->mDeviceDescriptor != 0) {
3241 affectedSources.add(route->mSource);
3242 }
3243 }
3244 }
3245 // reroute inputs if necessary
3246 SortedVector<audio_io_handle_t> inputsToClose;
3247 for (size_t i = 0; i < mInputs.size(); i++) {
3248 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003249 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003250 inputsToClose.add(inputDesc->mIoHandle);
3251 }
3252 }
3253 for (size_t i = 0; i < inputsToClose.size(); i++) {
3254 closeInput(inputsToClose[i]);
3255 }
3256}
3257
Eric Laurentd60560a2015-04-10 11:31:20 -07003258void AudioPolicyManager::clearAudioSources(uid_t uid)
3259{
3260 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
3261 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3262 if (sourceDesc->mUid == uid) {
3263 stopAudioSource(mAudioSources.keyAt(i));
3264 }
3265 }
3266}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003267
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003268status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3269 audio_io_handle_t *ioHandle,
3270 audio_devices_t *device)
3271{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003272 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3273 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003274 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003275
François Gaffiedf372692015-03-19 10:43:27 +01003276 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003277}
3278
Eric Laurentd60560a2015-04-10 11:31:20 -07003279status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
3280 const audio_attributes_t *attributes,
Glenn Kasten559d4392016-03-29 13:42:57 -07003281 audio_patch_handle_t *handle,
Eric Laurentd60560a2015-04-10 11:31:20 -07003282 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003283{
Eric Laurentd60560a2015-04-10 11:31:20 -07003284 ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle);
3285 if (source == NULL || attributes == NULL || handle == NULL) {
3286 return BAD_VALUE;
3287 }
3288
Glenn Kasten559d4392016-03-29 13:42:57 -07003289 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003290
3291 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3292 source->type != AUDIO_PORT_TYPE_DEVICE) {
3293 ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type);
3294 return INVALID_OPERATION;
3295 }
3296
3297 sp<DeviceDescriptor> srcDeviceDesc =
3298 mAvailableInputDevices.getDevice(source->ext.device.type,
3299 String8(source->ext.device.address));
3300 if (srcDeviceDesc == 0) {
3301 ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
3302 return BAD_VALUE;
3303 }
3304 sp<AudioSourceDescriptor> sourceDesc =
3305 new AudioSourceDescriptor(srcDeviceDesc, attributes, uid);
3306
3307 struct audio_patch dummyPatch;
3308 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
3309 sourceDesc->mPatchDesc = patchDesc;
3310
3311 status_t status = connectAudioSource(sourceDesc);
3312 if (status == NO_ERROR) {
3313 mAudioSources.add(sourceDesc->getHandle(), sourceDesc);
3314 *handle = sourceDesc->getHandle();
3315 }
3316 return status;
3317}
3318
3319status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3320{
3321 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3322
3323 // make sure we only have one patch per source.
3324 disconnectAudioSource(sourceDesc);
3325
3326 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
Eric Laurent28d09f02016-03-08 10:43:05 -08003327 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003328 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice;
3329
3330 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3331 sp<DeviceDescriptor> sinkDeviceDesc =
3332 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3333
3334 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3335 struct audio_patch *patch = &sourceDesc->mPatchDesc->mPatch;
3336
3337 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3338 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003339 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003340 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3341 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3342 // create patch between src device and output device
3343 // create Hwoutput and add to mHwOutputs
3344 } else {
3345 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3346 audio_io_handle_t output =
3347 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3348 if (output == AUDIO_IO_HANDLE_NONE) {
3349 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3350 return INVALID_OPERATION;
3351 }
3352 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3353 if (outputDesc->isDuplicated()) {
3354 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3355 return INVALID_OPERATION;
3356 }
3357 // create a special patch with no sink and two sources:
3358 // - the second source indicates to PatchPanel through which output mix this patch should
3359 // be connected as well as the stream type for volume control
3360 // - the sink is defined by whatever output device is currently selected for the output
3361 // though which this patch is routed.
3362 patch->num_sinks = 0;
3363 patch->num_sources = 2;
3364 srcDeviceDesc->toAudioPortConfig(&patch->sources[0], NULL);
3365 outputDesc->toAudioPortConfig(&patch->sources[1], NULL);
3366 patch->sources[1].ext.mix.usecase.stream = stream;
3367 status_t status = mpClientInterface->createAudioPatch(patch,
3368 &afPatchHandle,
3369 0);
3370 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3371 status, afPatchHandle);
3372 if (status != NO_ERROR) {
3373 ALOGW("%s patch panel could not connect device patch, error %d",
3374 __FUNCTION__, status);
3375 return INVALID_OPERATION;
3376 }
3377 uint32_t delayMs = 0;
Eric Laurentc40d9692016-04-13 19:14:13 -07003378 status = startSource(outputDesc, stream, sinkDevice, NULL, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003379
3380 if (status != NO_ERROR) {
3381 mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0);
3382 return status;
3383 }
3384 sourceDesc->mSwOutput = outputDesc;
3385 if (delayMs != 0) {
3386 usleep(delayMs * 1000);
3387 }
3388 }
3389
3390 sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle;
3391 addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc);
3392
3393 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003394}
3395
Glenn Kasten559d4392016-03-29 13:42:57 -07003396status_t AudioPolicyManager::stopAudioSource(audio_patch_handle_t handle __unused)
Eric Laurent554a2772015-04-10 11:29:24 -07003397{
Eric Laurentd60560a2015-04-10 11:31:20 -07003398 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle);
3399 ALOGV("%s handle %d", __FUNCTION__, handle);
3400 if (sourceDesc == 0) {
3401 ALOGW("%s unknown source for handle %d", __FUNCTION__, handle);
3402 return BAD_VALUE;
3403 }
3404 status_t status = disconnectAudioSource(sourceDesc);
3405
3406 mAudioSources.removeItem(handle);
3407 return status;
3408}
3409
Andy Hung2ddee192015-12-18 17:34:44 -08003410status_t AudioPolicyManager::setMasterMono(bool mono)
3411{
3412 if (mMasterMono == mono) {
3413 return NO_ERROR;
3414 }
3415 mMasterMono = mono;
3416 // if enabling mono we close all offloaded devices, which will invalidate the
3417 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3418 // for recreating the new AudioTrack as non-offloaded PCM.
3419 //
3420 // If disabling mono, we leave all tracks as is: we don't know which clients
3421 // and tracks are able to be recreated as offloaded. The next "song" should
3422 // play back offloaded.
3423 if (mMasterMono) {
3424 Vector<audio_io_handle_t> offloaded;
3425 for (size_t i = 0; i < mOutputs.size(); ++i) {
3426 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3427 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3428 offloaded.push(desc->mIoHandle);
3429 }
3430 }
3431 for (size_t i = 0; i < offloaded.size(); ++i) {
3432 closeOutput(offloaded[i]);
3433 }
3434 }
3435 // update master mono for all remaining outputs
3436 for (size_t i = 0; i < mOutputs.size(); ++i) {
3437 updateMono(mOutputs.keyAt(i));
3438 }
3439 return NO_ERROR;
3440}
3441
3442status_t AudioPolicyManager::getMasterMono(bool *mono)
3443{
3444 *mono = mMasterMono;
3445 return NO_ERROR;
3446}
3447
Eric Laurentac9cef52017-06-09 15:46:26 -07003448float AudioPolicyManager::getStreamVolumeDB(
3449 audio_stream_type_t stream, int index, audio_devices_t device)
3450{
3451 return computeVolume(stream, index, device);
3452}
3453
Eric Laurentd60560a2015-04-10 11:31:20 -07003454status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3455{
3456 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3457
3458 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle);
3459 if (patchDesc == 0) {
3460 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
3461 sourceDesc->mPatchDesc->mHandle);
3462 return BAD_VALUE;
3463 }
3464 removeAudioPatch(sourceDesc->mPatchDesc->mHandle);
3465
Eric Laurent28d09f02016-03-08 10:43:05 -08003466 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003467 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote();
3468 if (swOutputDesc != 0) {
3469 stopSource(swOutputDesc, stream, false);
3470 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3471 } else {
3472 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote();
3473 if (hwOutputDesc != 0) {
3474 // release patch between src device and output device
3475 // close Hwoutput and remove from mHwOutputs
3476 } else {
3477 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3478 }
3479 }
3480 return NO_ERROR;
3481}
3482
3483sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
3484 audio_io_handle_t output, routing_strategy strategy)
3485{
3486 sp<AudioSourceDescriptor> source;
3487 for (size_t i = 0; i < mAudioSources.size(); i++) {
3488 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3489 routing_strategy sourceStrategy =
3490 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
3491 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote();
3492 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3493 source = sourceDesc;
3494 break;
3495 }
3496 }
3497 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003498}
3499
Eric Laurente552edb2014-03-10 17:42:56 -07003500// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003501// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003502// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003503uint32_t AudioPolicyManager::nextAudioPortGeneration()
3504{
3505 return android_atomic_inc(&mAudioPortGeneration);
3506}
3507
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003508#ifdef USE_XML_AUDIO_POLICY_CONF
3509// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3510static const char *kConfigLocationList[] =
3511 {"/odm/etc", "/vendor/etc", "/system/etc"};
3512static const int kConfigLocationListSize =
3513 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3514
3515static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3516 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
3517 status_t ret;
3518
3519 for (int i = 0; i < kConfigLocationListSize; i++) {
3520 PolicySerializer serializer;
3521 snprintf(audioPolicyXmlConfigFile,
3522 sizeof(audioPolicyXmlConfigFile),
3523 "%s/%s",
3524 kConfigLocationList[i],
3525 AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3526 ret = serializer.deserialize(audioPolicyXmlConfigFile, config);
3527 if (ret == NO_ERROR) {
3528 break;
3529 }
3530 }
3531 return ret;
3532}
3533#endif
3534
Eric Laurente0720872014-03-11 09:30:41 -07003535AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07003536 :
Eric Laurente552edb2014-03-10 17:42:56 -07003537 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003538 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003539 mAudioPortGeneration(1),
3540 mBeaconMuteRefCount(0),
3541 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003542 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003543 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003544 mMasterMono(false),
Chris Thornton2b864642017-06-27 21:26:07 -07003545 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE),
3546 mHasComputedSoundTriggerSupportsConcurrentCapture(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003547{
François Gaffied1ab2bd2015-12-02 18:20:06 +01003548 mUidCached = getuid();
3549 mpClientInterface = clientInterface;
3550
3551 // TODO: remove when legacy conf file is removed. true on devices that use DRC on the
3552 // DEVICE_CATEGORY_SPEAKER path to boost soft sounds, used to adjust volume curves accordingly.
3553 // Note: remove also speaker_drc_enabled from global configuration of XML config file.
3554 bool speakerDrcEnabled = false;
3555
3556#ifdef USE_XML_AUDIO_POLICY_CONF
3557 mVolumeCurves = new VolumeCurvesCollection();
3558 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3559 mDefaultOutputDevice, speakerDrcEnabled,
3560 static_cast<VolumeCurvesCollection *>(mVolumeCurves));
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003561 if (deserializeAudioPolicyXmlConfig(config) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003562#else
3563 mVolumeCurves = new StreamDescriptorCollection();
3564 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3565 mDefaultOutputDevice, speakerDrcEnabled);
3566 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, config) != NO_ERROR) &&
3567 (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, config) != NO_ERROR)) {
3568#endif
3569 ALOGE("could not load audio policy configuration file, setting defaults");
3570 config.setDefault();
3571 }
3572 // must be done after reading the policy (since conditionned by Speaker Drc Enabling)
3573 mVolumeCurves->initializeVolumeCurves(speakerDrcEnabled);
3574
3575 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003576 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3577 if (!engineInstance) {
3578 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
3579 return;
3580 }
3581 // Retrieve the Policy Manager Interface
3582 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3583 if (mEngine == NULL) {
3584 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
3585 return;
3586 }
3587 mEngine->setObserver(this);
3588 status_t status = mEngine->initCheck();
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07003589 (void) status;
François Gaffie2110e042015-03-24 08:41:51 +01003590 ALOG_ASSERT(status == NO_ERROR, "Policy engine not initialized(err=%d)", status);
3591
Eric Laurent3a4311c2014-03-17 12:00:47 -07003592 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003593 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003594 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3595 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003596 for (size_t i = 0; i < mHwModules.size(); i++) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003597 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003598 if (mHwModules[i]->mHandle == 0) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003599 ALOGW("could not open HW module %s", mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003600 continue;
3601 }
3602 // open all output streams needed to access attached devices
3603 // except for direct output streams that are only opened when they are actually
3604 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003605 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07003606 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3607 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003608 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003609
Eric Laurentf05fc902017-11-21 12:08:15 -08003610 if (!outProfile->canOpenNewIo()) {
3611 ALOGE("Invalid Output profile max open count %u for profile %s",
3612 outProfile->maxOpenCount, outProfile->getTagName().c_str());
3613 continue;
3614 }
3615
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003616 if (!outProfile->hasSupportedDevices()) {
3617 ALOGW("Output profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003618 continue;
3619 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003620 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003621 mTtsOutputAvailable = true;
3622 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003623
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003624 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003625 continue;
3626 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003627 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003628 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3629 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003630 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003631 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003632 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003633 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003634 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003635 if ((profileType & outputDeviceTypes) == 0) {
3636 continue;
3637 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003638 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3639 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003640 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
3641 const DeviceVector &devicesForType = supportedDevices.getDevicesFromType(profileType);
3642 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3643 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003644 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08003645 status_t status = outputDesc->open(nullptr, profileType, address,
3646 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07003647
3648 if (status != NO_ERROR) {
3649 ALOGW("Cannot open output stream for device %08x on hw module %s",
3650 outputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003651 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003652 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003653 for (size_t k = 0; k < supportedDevices.size(); k++) {
3654 ssize_t index = mAvailableOutputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003655 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003656 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
3657 mAvailableOutputDevices[index]->attach(mHwModules[i]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003658 }
3659 }
3660 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003661 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003662 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003663 }
3664 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003665 setOutputDevice(outputDesc,
Eric Laurentfe231122017-11-17 17:48:06 -08003666 profileType,
Eric Laurentc40d9692016-04-13 19:14:13 -07003667 true,
3668 0,
3669 NULL,
Eric Laurentfe231122017-11-17 17:48:06 -08003670 address);
Eric Laurentd78f1532014-09-16 16:38:20 -07003671 }
Eric Laurente552edb2014-03-10 17:42:56 -07003672 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003673 // open input streams needed to access attached devices to validate
3674 // mAvailableInputDevices list
3675 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3676 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003677 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003678
Eric Laurentf05fc902017-11-21 12:08:15 -08003679 if (!inProfile->canOpenNewIo()) {
3680 ALOGE("Invalid Input profile max open count %u for profile %s",
3681 inProfile->maxOpenCount, inProfile->getTagName().c_str());
3682 continue;
3683 }
3684
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003685 if (!inProfile->hasSupportedDevices()) {
3686 ALOGW("Input profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003687 continue;
3688 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003689 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003690 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003691 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
3692
Eric Laurentd78f1532014-09-16 16:38:20 -07003693 if ((profileType & inputDeviceTypes) == 0) {
3694 continue;
3695 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08003696 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08003697 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07003698
Eric Laurentd78f1532014-09-16 16:38:20 -07003699 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08003700 status_t status = inputDesc->open(nullptr,
3701 profileType,
3702 String8(""),
3703 AUDIO_SOURCE_MIC,
3704 AUDIO_INPUT_FLAG_NONE,
3705 &input);
Eric Laurentd78f1532014-09-16 16:38:20 -07003706
3707 if (status == NO_ERROR) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003708 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
3709 for (size_t k = 0; k < supportedDevices.size(); k++) {
3710 ssize_t index = mAvailableInputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003711 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07003712 if (index >= 0) {
3713 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
3714 if (!devDesc->isAttached()) {
3715 devDesc->attach(mHwModules[i]);
Eric Laurent83efe1c2017-07-09 16:51:08 -07003716 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07003717 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003718 }
3719 }
Eric Laurentfe231122017-11-17 17:48:06 -08003720 inputDesc->close();
Eric Laurentd78f1532014-09-16 16:38:20 -07003721 } else {
3722 ALOGW("Cannot open input stream for device %08x on hw module %s",
Eric Laurentfe231122017-11-17 17:48:06 -08003723 profileType,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003724 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003725 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003726 }
3727 }
3728 // make sure all attached devices have been allocated a unique ID
3729 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003730 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003731 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003732 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
3733 continue;
3734 }
François Gaffie2110e042015-03-24 08:41:51 +01003735 // The device is now validated and can be appended to the available devices of the engine
3736 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
3737 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003738 i++;
3739 }
3740 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003741 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01003742 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003743 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
3744 continue;
3745 }
François Gaffie2110e042015-03-24 08:41:51 +01003746 // The device is now validated and can be appended to the available devices of the engine
3747 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
3748 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003749 i++;
3750 }
3751 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003752 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01003753 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003754 }
Eric Laurente552edb2014-03-10 17:42:56 -07003755
3756 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
3757
3758 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -07003759}
3760
Eric Laurente0720872014-03-11 09:30:41 -07003761AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07003762{
Eric Laurente552edb2014-03-10 17:42:56 -07003763 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08003764 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07003765 }
3766 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08003767 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07003768 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003769 mAvailableOutputDevices.clear();
3770 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003771 mOutputs.clear();
3772 mInputs.clear();
3773 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07003774}
3775
Eric Laurente0720872014-03-11 09:30:41 -07003776status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07003777{
Eric Laurent87ffa392015-05-22 10:32:38 -07003778 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003779}
3780
Eric Laurente552edb2014-03-10 17:42:56 -07003781// ---
3782
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003783void AudioPolicyManager::addOutput(audio_io_handle_t output, const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003784{
Eric Laurent1c333e22014-05-20 10:48:17 -07003785 mOutputs.add(output, outputDesc);
Andy Hung2ddee192015-12-18 17:34:44 -08003786 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07003787 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07003788 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003789}
3790
François Gaffie53615e22015-03-19 09:24:12 +01003791void AudioPolicyManager::removeOutput(audio_io_handle_t output)
3792{
3793 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07003794 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01003795}
3796
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003797void AudioPolicyManager::addInput(audio_io_handle_t input, const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003798{
Eric Laurent1c333e22014-05-20 10:48:17 -07003799 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003800 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003801}
Eric Laurente552edb2014-03-10 17:42:56 -07003802
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003803void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08003804 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003805 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003806 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08003807 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003808 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08003809 if (devDesc != 0) {
3810 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
3811 desc->mIoHandle, address.string());
3812 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003813 }
3814}
3815
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003816status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01003817 audio_policy_dev_state_t state,
3818 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003819 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07003820{
François Gaffie53615e22015-03-19 09:24:12 +01003821 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07003822 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07003823
3824 if (audio_device_is_digital(device)) {
3825 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08003826 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07003827 }
Eric Laurente552edb2014-03-10 17:42:56 -07003828
Eric Laurent3b73df72014-03-11 09:06:29 -07003829 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003830 // first list already open outputs that can be routed to this device
3831 for (size_t i = 0; i < mOutputs.size(); i++) {
3832 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07003833 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003834 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003835 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3836 outputs.add(mOutputs.keyAt(i));
3837 } else {
3838 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08003839 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003840 }
Eric Laurente552edb2014-03-10 17:42:56 -07003841 }
3842 }
3843 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003844 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003845 for (size_t i = 0; i < mHwModules.size(); i++)
3846 {
3847 if (mHwModules[i]->mHandle == 0) {
3848 continue;
3849 }
3850 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3851 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003852 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003853 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003854 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003855 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003856 profiles.add(profile);
3857 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
3858 }
Eric Laurente552edb2014-03-10 17:42:56 -07003859 }
3860 }
3861 }
3862
Eric Laurent7b279bb2015-12-14 10:18:23 -08003863 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003864
Eric Laurente552edb2014-03-10 17:42:56 -07003865 if (profiles.isEmpty() && outputs.isEmpty()) {
3866 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3867 return BAD_VALUE;
3868 }
3869
3870 // open outputs for matching profiles if needed. Direct outputs are also opened to
3871 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3872 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003873 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003874
3875 // nothing to do if one output is already opened for this profile
3876 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003877 for (j = 0; j < outputs.size(); j++) {
3878 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003879 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003880 // matching profile: save the sample rates, format and channel masks supported
3881 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07003882 if (audio_device_is_digital(device)) {
3883 devDesc->importAudioPort(profile);
3884 }
Eric Laurente552edb2014-03-10 17:42:56 -07003885 break;
3886 }
3887 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003888 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003889 continue;
3890 }
3891
Eric Laurentf05fc902017-11-21 12:08:15 -08003892 if (!profile->canOpenNewIo()) {
3893 ALOGW("Max Output number %u already opened for this profile %s",
3894 profile->maxOpenCount, profile->getTagName().c_str());
3895 continue;
3896 }
3897
Eric Laurent83efe1c2017-07-09 16:51:08 -07003898 ALOGV("opening output for device %08x with params %s profile %p name %s",
3899 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07003900 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003901 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08003902 status_t status = desc->open(nullptr, device, address,
3903 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07003904
Eric Laurentfe231122017-11-17 17:48:06 -08003905 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07003906 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003907 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003908 char *param = audio_device_address_to_parameter(device, address);
3909 mpClientInterface->setParameters(output, String8(param));
3910 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003911 }
Phil Burk00eeb322016-03-31 12:41:00 -07003912 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01003913 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003914 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08003915 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003916 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01003917 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08003918 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08003919 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08003920 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3921 profile->pickAudioProfile(
3922 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003923 config.offload_info.sample_rate = config.sample_rate;
3924 config.offload_info.channel_mask = config.channel_mask;
3925 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08003926
3927 status_t status = desc->open(&config, device, address, AUDIO_STREAM_DEFAULT,
3928 AUDIO_OUTPUT_FLAG_NONE, &output);
3929 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003930 output = AUDIO_IO_HANDLE_NONE;
3931 }
Eric Laurentd4692962014-05-05 18:13:44 -07003932 }
3933
Eric Laurentcf2c0212014-07-25 16:20:43 -07003934 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003935 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01003936 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01003937 sp<AudioPolicyMix> policyMix;
3938 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003939 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
3940 address.string());
3941 }
François Gaffie036e1e92015-03-19 10:16:24 +01003942 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07003943 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01003944
Eric Laurent87ffa392015-05-22 10:32:38 -07003945 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
3946 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08003947 // no duplicated output for direct outputs and
3948 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07003949 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003950
Eric Laurentd4692962014-05-05 18:13:44 -07003951 // set initial stream volume for device
Eric Laurentc75307b2015-03-17 15:29:32 -07003952 applyStreamVolumes(desc, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003953
Eric Laurentd4692962014-05-05 18:13:44 -07003954 //TODO: configure audio effect output stage here
3955
3956 // open a duplicating output thread for the new output and the primary output
Eric Laurentc75307b2015-03-17 15:29:32 -07003957 duplicatedOutput =
3958 mpClientInterface->openDuplicateOutput(output,
3959 mPrimaryOutput->mIoHandle);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003960 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003961 // add duplicated output descriptor
Eric Laurentc75307b2015-03-17 15:29:32 -07003962 sp<SwAudioOutputDescriptor> dupOutputDesc =
3963 new SwAudioOutputDescriptor(NULL, mpClientInterface);
3964 dupOutputDesc->mOutput1 = mPrimaryOutput;
3965 dupOutputDesc->mOutput2 = desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003966 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3967 dupOutputDesc->mFormat = desc->mFormat;
3968 dupOutputDesc->mChannelMask = desc->mChannelMask;
3969 dupOutputDesc->mLatency = desc->mLatency;
3970 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003971 applyStreamVolumes(dupOutputDesc, device, 0, true);
Eric Laurentd4692962014-05-05 18:13:44 -07003972 } else {
3973 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07003974 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08003975 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01003976 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003977 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003978 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003979 }
Eric Laurente552edb2014-03-10 17:42:56 -07003980 }
3981 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003982 } else {
3983 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003984 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003985 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003986 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003987 profiles.removeAt(profile_index);
3988 profile_index--;
3989 } else {
3990 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07003991 // Load digital format info only for digital devices
3992 if (audio_device_is_digital(device)) {
3993 devDesc->importAudioPort(profile);
3994 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003995
François Gaffie53615e22015-03-19 09:24:12 +01003996 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003997 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3998 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07003999 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004000 NULL/*patch handle*/, address.string());
4001 }
Eric Laurente552edb2014-03-10 17:42:56 -07004002 ALOGV("checkOutputsForDevice(): adding output %d", output);
4003 }
4004 }
4005
4006 if (profiles.isEmpty()) {
4007 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4008 return BAD_VALUE;
4009 }
Eric Laurentd4692962014-05-05 18:13:44 -07004010 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004011 // check if one opened output is not needed any more after disconnecting one device
4012 for (size_t i = 0; i < mOutputs.size(); i++) {
4013 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004014 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004015 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004016 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004017 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004018 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004019 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004020 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4021 mOutputs.keyAt(i));
4022 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004023 }
Eric Laurente552edb2014-03-10 17:42:56 -07004024 }
4025 }
Eric Laurentd4692962014-05-05 18:13:44 -07004026 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07004027 for (size_t i = 0; i < mHwModules.size(); i++)
4028 {
4029 if (mHwModules[i]->mHandle == 0) {
4030 continue;
4031 }
4032 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
4033 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004034 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004035 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004036 ALOGV("checkOutputsForDevice(): "
4037 "clearing direct output profile %zu on module %zu", j, i);
François Gaffie112b0af2015-11-19 16:13:25 +01004038 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004039 }
4040 }
4041 }
4042 }
4043 return NO_ERROR;
4044}
4045
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004046status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004047 audio_policy_dev_state_t state,
4048 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004049 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004050{
Paul McLean9080a4c2015-06-18 08:24:02 -07004051 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004052 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004053
4054 if (audio_device_is_digital(device)) {
4055 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004056 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004057 }
4058
Eric Laurentd4692962014-05-05 18:13:44 -07004059 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4060 // first list already open inputs that can be routed to this device
4061 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4062 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004063 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004064 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4065 inputs.add(mInputs.keyAt(input_index));
4066 }
4067 }
4068
4069 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004070 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07004071 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
4072 {
4073 if (mHwModules[module_idx]->mHandle == 0) {
4074 continue;
4075 }
4076 for (size_t profile_index = 0;
4077 profile_index < mHwModules[module_idx]->mInputProfiles.size();
4078 profile_index++)
4079 {
Eric Laurent275e8e92014-11-30 15:14:47 -08004080 sp<IOProfile> profile = mHwModules[module_idx]->mInputProfiles[profile_index];
4081
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004082 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004083 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004084 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004085 profiles.add(profile);
4086 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
4087 profile_index, module_idx);
4088 }
Eric Laurentd4692962014-05-05 18:13:44 -07004089 }
4090 }
4091 }
4092
4093 if (profiles.isEmpty() && inputs.isEmpty()) {
4094 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4095 return BAD_VALUE;
4096 }
4097
4098 // open inputs for matching profiles if needed. Direct inputs are also opened to
4099 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4100 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4101
Eric Laurent1c333e22014-05-20 10:48:17 -07004102 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentf05fc902017-11-21 12:08:15 -08004103
Eric Laurentd4692962014-05-05 18:13:44 -07004104 // nothing to do if one input is already opened for this profile
4105 size_t input_index;
4106 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4107 desc = mInputs.valueAt(input_index);
4108 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004109 if (audio_device_is_digital(device)) {
4110 devDesc->importAudioPort(profile);
4111 }
Eric Laurentd4692962014-05-05 18:13:44 -07004112 break;
4113 }
4114 }
4115 if (input_index != mInputs.size()) {
4116 continue;
4117 }
4118
Eric Laurentf05fc902017-11-21 12:08:15 -08004119 if (!profile->canOpenNewIo()) {
4120 ALOGW("Max Input number %u already opened for this profile %s",
4121 profile->maxOpenCount, profile->getTagName().c_str());
4122 continue;
4123 }
4124
Eric Laurentfe231122017-11-17 17:48:06 -08004125 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004126 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004127 status_t status = desc->open(nullptr,
4128 device,
4129 address,
4130 AUDIO_SOURCE_MIC,
4131 AUDIO_INPUT_FLAG_NONE,
4132 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004133
Eric Laurentcf2c0212014-07-25 16:20:43 -07004134 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004135 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004136 char *param = audio_device_address_to_parameter(device, address);
4137 mpClientInterface->setParameters(input, String8(param));
4138 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004139 }
Phil Burk00eeb322016-03-31 12:41:00 -07004140 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004141 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004142 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004143 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004144 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004145 }
4146
4147 if (input != 0) {
4148 addInput(input, desc);
4149 }
4150 } // endif input != 0
4151
Eric Laurentcf2c0212014-07-25 16:20:43 -07004152 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004153 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004154 profiles.removeAt(profile_index);
4155 profile_index--;
4156 } else {
4157 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004158 if (audio_device_is_digital(device)) {
4159 devDesc->importAudioPort(profile);
4160 }
Eric Laurentd4692962014-05-05 18:13:44 -07004161 ALOGV("checkInputsForDevice(): adding input %d", input);
4162 }
4163 } // end scan profiles
4164
4165 if (profiles.isEmpty()) {
4166 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4167 return BAD_VALUE;
4168 }
4169 } else {
4170 // Disconnect
4171 // check if one opened input is not needed any more after disconnecting one device
4172 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4173 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004174 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004175 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4176 mInputs.keyAt(input_index));
4177 inputs.add(mInputs.keyAt(input_index));
4178 }
4179 }
4180 // Clear any profiles associated with the disconnected device.
4181 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
4182 if (mHwModules[module_index]->mHandle == 0) {
4183 continue;
4184 }
4185 for (size_t profile_index = 0;
4186 profile_index < mHwModules[module_index]->mInputProfiles.size();
4187 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004188 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004189 if (profile->supportDevice(device)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004190 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07004191 profile_index, module_index);
François Gaffie112b0af2015-11-19 16:13:25 +01004192 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004193 }
4194 }
4195 }
4196 } // end disconnect
4197
4198 return NO_ERROR;
4199}
4200
4201
Eric Laurente0720872014-03-11 09:30:41 -07004202void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004203{
4204 ALOGV("closeOutput(%d)", output);
4205
Eric Laurentc75307b2015-03-17 15:29:32 -07004206 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004207 if (outputDesc == NULL) {
4208 ALOGW("closeOutput() unknown output %d", output);
4209 return;
4210 }
François Gaffie036e1e92015-03-19 10:16:24 +01004211 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004212
Eric Laurente552edb2014-03-10 17:42:56 -07004213 // look for duplicated outputs connected to the output being removed.
4214 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004215 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004216 if (dupOutputDesc->isDuplicated() &&
4217 (dupOutputDesc->mOutput1 == outputDesc ||
4218 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004219 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004220 if (dupOutputDesc->mOutput1 == outputDesc) {
4221 outputDesc2 = dupOutputDesc->mOutput2;
4222 } else {
4223 outputDesc2 = dupOutputDesc->mOutput1;
4224 }
4225 // As all active tracks on duplicated output will be deleted,
4226 // and as they were also referenced on the other output, the reference
4227 // count for their stream type must be adjusted accordingly on
4228 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07004229 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004230 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07004231 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004232 }
4233 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4234 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4235
4236 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004237 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004238 }
4239 }
4240
Eric Laurent05b90f82014-08-27 15:32:29 -07004241 nextAudioPortGeneration();
4242
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004243 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004244 if (index >= 0) {
4245 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004246 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004247 mAudioPatches.removeItemsAt(index);
4248 mpClientInterface->onAudioPatchListUpdate();
4249 }
4250
Eric Laurentfe231122017-11-17 17:48:06 -08004251 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004252
François Gaffie53615e22015-03-19 09:24:12 +01004253 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004254 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004255}
4256
4257void AudioPolicyManager::closeInput(audio_io_handle_t input)
4258{
4259 ALOGV("closeInput(%d)", input);
4260
4261 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4262 if (inputDesc == NULL) {
4263 ALOGW("closeInput() unknown input %d", input);
4264 return;
4265 }
4266
Eric Laurent6a94d692014-05-20 11:18:06 -07004267 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004268
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004269 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004270 if (index >= 0) {
4271 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004272 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004273 mAudioPatches.removeItemsAt(index);
4274 mpClientInterface->onAudioPatchListUpdate();
4275 }
4276
Eric Laurentfe231122017-11-17 17:48:06 -08004277 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004278 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004279}
4280
Eric Laurentc75307b2015-03-17 15:29:32 -07004281SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4282 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004283 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004284{
4285 SortedVector<audio_io_handle_t> outputs;
4286
4287 ALOGVV("getOutputsForDevice() device %04x", device);
4288 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004289 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004290 i, openOutputs.valueAt(i)->isDuplicated(),
4291 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004292 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4293 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4294 outputs.add(openOutputs.keyAt(i));
4295 }
4296 }
4297 return outputs;
4298}
4299
Eric Laurente0720872014-03-11 09:30:41 -07004300bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
François Gaffie53615e22015-03-19 09:24:12 +01004301 SortedVector<audio_io_handle_t>& outputs2)
Eric Laurente552edb2014-03-10 17:42:56 -07004302{
4303 if (outputs1.size() != outputs2.size()) {
4304 return false;
4305 }
4306 for (size_t i = 0; i < outputs1.size(); i++) {
4307 if (outputs1[i] != outputs2[i]) {
4308 return false;
4309 }
4310 }
4311 return true;
4312}
4313
Eric Laurente0720872014-03-11 09:30:41 -07004314void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004315{
4316 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4317 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4318 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4319 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4320
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004321 // also take into account external policy-related changes: add all outputs which are
4322 // associated with policies in the "before" and "after" output vectors
4323 ALOGVV("checkOutputForStrategy(): policy related outputs");
4324 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004325 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004326 if (desc != 0 && desc->mPolicyMix != NULL) {
4327 srcOutputs.add(desc->mIoHandle);
4328 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4329 }
4330 }
4331 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004332 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004333 if (desc != 0 && desc->mPolicyMix != NULL) {
4334 dstOutputs.add(desc->mIoHandle);
4335 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4336 }
4337 }
4338
Eric Laurente552edb2014-03-10 17:42:56 -07004339 if (!vectorsEqual(srcOutputs,dstOutputs)) {
4340 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4341 strategy, srcOutputs[0], dstOutputs[0]);
4342 // mute strategy while moving tracks from one output to another
4343 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004344 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
François Gaffiead3183e2015-03-18 16:55:35 +01004345 if (isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004346 setStrategyMute(strategy, true, desc);
4347 setStrategyMute(strategy, false, desc, MUTE_TIME_MS, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004348 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004349 sp<AudioSourceDescriptor> source =
4350 getSourceForStrategyOnOutput(srcOutputs[i], strategy);
4351 if (source != 0){
4352 connectAudioSource(source);
4353 }
Eric Laurente552edb2014-03-10 17:42:56 -07004354 }
4355
4356 // Move effects associated to this strategy from previous output to new output
4357 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004358 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004359 }
4360 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004361 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004362 if (getStrategy((audio_stream_type_t)i) == strategy) {
4363 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004364 }
4365 }
4366 }
4367}
4368
Eric Laurente0720872014-03-11 09:30:41 -07004369void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004370{
François Gaffie2110e042015-03-24 08:41:51 +01004371 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004372 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004373 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004374 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004375 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004376 checkOutputForStrategy(STRATEGY_SONIFICATION);
4377 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004378 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004379 checkOutputForStrategy(STRATEGY_MEDIA);
4380 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004381 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004382}
4383
Eric Laurente0720872014-03-11 09:30:41 -07004384void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004385{
François Gaffie53615e22015-03-19 09:24:12 +01004386 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Eric Laurente552edb2014-03-10 17:42:56 -07004387 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004388 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004389 return;
4390 }
4391
Eric Laurent3a4311c2014-03-17 12:00:47 -07004392 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004393 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4394 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4395 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004396
4397 // if suspended, restore A2DP output if:
4398 // ((SCO device is NOT connected) ||
4399 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4400 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004401 //
Eric Laurentf732e072016-08-03 19:30:28 -07004402 // if not suspended, suspend A2DP output if:
4403 // (SCO device is connected) &&
4404 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4405 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004406 //
4407 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004408 if (!isScoConnected ||
4409 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4410 AUDIO_POLICY_FORCE_BT_SCO) &&
4411 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4412 AUDIO_POLICY_FORCE_BT_SCO) &&
4413 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004414 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004415
4416 mpClientInterface->restoreOutput(a2dpOutput);
4417 mA2dpSuspended = false;
4418 }
4419 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004420 if (isScoConnected &&
4421 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4422 AUDIO_POLICY_FORCE_BT_SCO) ||
4423 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4424 AUDIO_POLICY_FORCE_BT_SCO) ||
4425 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004426 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004427
4428 mpClientInterface->suspendOutput(a2dpOutput);
4429 mA2dpSuspended = true;
4430 }
4431 }
4432}
4433
Eric Laurentc75307b2015-03-17 15:29:32 -07004434audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4435 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004436{
4437 audio_devices_t device = AUDIO_DEVICE_NONE;
4438
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004439 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004440 if (index >= 0) {
4441 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4442 if (patchDesc->mUid != mUidCached) {
4443 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004444 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004445 return outputDesc->device();
4446 }
4447 }
4448
Eric Laurente552edb2014-03-10 17:42:56 -07004449 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004450 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004451 // use device for strategy enforced audible
4452 // 2: we are in call or the strategy phone is active on the output:
4453 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004454 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004455 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004456 // 4: the strategy for enforced audible is active but not enforced on the output:
4457 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004458 // 5: the strategy accessibility is active on the output:
4459 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004460 // 6: the strategy "respectful" sonification is active on the output:
4461 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004462 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004463 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004464 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004465 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004466 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004467 // use device for strategy t-t-s
François Gaffiead3183e2015-03-18 16:55:35 +01004468 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004469 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004470 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4471 } else if (isInCall() ||
François Gaffiead3183e2015-03-18 16:55:35 +01004472 isStrategyActive(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004473 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004474 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004475 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004476 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
4477 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004478 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4479 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004480 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004481 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004482 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004483 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004484 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004485 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004486 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004487 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004488 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004489 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004490 }
4491
Eric Laurent1c333e22014-05-20 10:48:17 -07004492 ALOGV("getNewOutputDevice() selected device %x", device);
4493 return device;
4494}
4495
Eric Laurentfb66dd92016-01-28 18:32:03 -08004496audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004497{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004498 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004499
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004500 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004501 if (index >= 0) {
4502 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4503 if (patchDesc->mUid != mUidCached) {
4504 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004505 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004506 return inputDesc->mDevice;
4507 }
4508 }
4509
Eric Laurentfb66dd92016-01-28 18:32:03 -08004510 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
4511 if (isInCall()) {
4512 device = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
4513 } else if (source != AUDIO_SOURCE_DEFAULT) {
4514 device = getDeviceAndMixForInputSource(source);
4515 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004516
Eric Laurente552edb2014-03-10 17:42:56 -07004517 return device;
4518}
4519
Eric Laurent794fde22016-03-11 09:50:45 -08004520bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4521 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004522 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004523}
4524
Eric Laurente0720872014-03-11 09:30:41 -07004525uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004526 return (uint32_t)getStrategy(stream);
4527}
4528
Eric Laurente0720872014-03-11 09:30:41 -07004529audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004530 // By checking the range of stream before calling getStrategy, we avoid
4531 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4532 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004533 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004534 return AUDIO_DEVICE_NONE;
4535 }
Eric Laurent28d09f02016-03-08 10:43:05 -08004536 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004537 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4538 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004539 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004540 }
Eric Laurent794fde22016-03-11 09:50:45 -08004541 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004542 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004543 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Eric Laurent28d09f02016-03-08 10:43:05 -08004544 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(curDevices, mOutputs);
4545 for (size_t i = 0; i < outputs.size(); i++) {
4546 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent794fde22016-03-11 09:50:45 -08004547 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004548 curDevices |= outputDesc->device();
4549 }
4550 }
4551 devices |= curDevices;
Eric Laurente552edb2014-03-10 17:42:56 -07004552 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004553
4554 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4555 and doesn't really need to.*/
4556 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4557 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4558 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4559 }
Eric Laurente552edb2014-03-10 17:42:56 -07004560 return devices;
4561}
4562
François Gaffie2110e042015-03-24 08:41:51 +01004563routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4564{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004565 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004566 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004567}
4568
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004569uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4570 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004571 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4572 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4573 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004574 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4575 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4576 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004577 // usage to strategy mapping
François Gaffie2110e042015-03-24 08:41:51 +01004578 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004579}
4580
Eric Laurente0720872014-03-11 09:30:41 -07004581void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004582 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004583 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004584 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4585 updateDevicesAndOutputs();
4586 break;
4587 default:
4588 break;
4589 }
4590}
4591
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004592uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004593
4594 // skip beacon mute management if a dedicated TTS output is available
4595 if (mTtsOutputAvailable) {
4596 return 0;
4597 }
4598
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004599 switch(event) {
4600 case STARTING_OUTPUT:
4601 mBeaconMuteRefCount++;
4602 break;
4603 case STOPPING_OUTPUT:
4604 if (mBeaconMuteRefCount > 0) {
4605 mBeaconMuteRefCount--;
4606 }
4607 break;
4608 case STARTING_BEACON:
4609 mBeaconPlayingRefCount++;
4610 break;
4611 case STOPPING_BEACON:
4612 if (mBeaconPlayingRefCount > 0) {
4613 mBeaconPlayingRefCount--;
4614 }
4615 break;
4616 }
4617
4618 if (mBeaconMuteRefCount > 0) {
4619 // any playback causes beacon to be muted
4620 return setBeaconMute(true);
4621 } else {
4622 // no other playback: unmute when beacon starts playing, mute when it stops
4623 return setBeaconMute(mBeaconPlayingRefCount == 0);
4624 }
4625}
4626
4627uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4628 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4629 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4630 // keep track of muted state to avoid repeating mute/unmute operations
4631 if (mBeaconMuted != mute) {
4632 // mute/unmute AUDIO_STREAM_TTS on all outputs
4633 ALOGV("\t muting %d", mute);
4634 uint32_t maxLatency = 0;
4635 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004636 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004637 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07004638 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004639 0 /*delay*/, AUDIO_DEVICE_NONE);
4640 const uint32_t latency = desc->latency() * 2;
4641 if (latency > maxLatency) {
4642 maxLatency = latency;
4643 }
4644 }
4645 mBeaconMuted = mute;
4646 return maxLatency;
4647 }
4648 return 0;
4649}
4650
Eric Laurente0720872014-03-11 09:30:41 -07004651audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01004652 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004653{
Paul McLeanaa981192015-03-21 09:55:15 -07004654 // Routing
4655 // see if we have an explicit route
4656 // scan the whole RouteMap, for each entry, convert the stream type to a strategy
4657 // (getStrategy(stream)).
4658 // if the strategy from the stream type in the RouteMap is the same as the argument above,
Eric Laurentad2e7b92017-09-14 20:06:42 -07004659 // and activity count is non-zero and the device in the route descriptor is available
4660 // then select this device.
Paul McLeanaa981192015-03-21 09:55:15 -07004661 for (size_t routeIndex = 0; routeIndex < mOutputRoutes.size(); routeIndex++) {
4662 sp<SessionRoute> route = mOutputRoutes.valueAt(routeIndex);
Eric Laurent28d09f02016-03-08 10:43:05 -08004663 routing_strategy routeStrategy = getStrategy(route->mStreamType);
Eric Laurentad2e7b92017-09-14 20:06:42 -07004664 if ((routeStrategy == strategy) && route->isActive() &&
4665 (mAvailableOutputDevices.indexOf(route->mDeviceDescriptor) >= 0)) {
Paul McLeanaa981192015-03-21 09:55:15 -07004666 return route->mDeviceDescriptor->type();
4667 }
4668 }
4669
Eric Laurente552edb2014-03-10 17:42:56 -07004670 if (fromCache) {
4671 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4672 strategy, mDeviceForStrategy[strategy]);
4673 return mDeviceForStrategy[strategy];
4674 }
François Gaffie2110e042015-03-24 08:41:51 +01004675 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07004676}
4677
Eric Laurente0720872014-03-11 09:30:41 -07004678void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004679{
4680 for (int i = 0; i < NUM_STRATEGIES; i++) {
4681 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4682 }
4683 mPreviousOutputs = mOutputs;
4684}
4685
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004686uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004687 audio_devices_t prevDevice,
4688 uint32_t delayMs)
4689{
4690 // mute/unmute strategies using an incompatible device combination
4691 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4692 // if unmuting, unmute only after the specified delay
4693 if (outputDesc->isDuplicated()) {
4694 return 0;
4695 }
4696
4697 uint32_t muteWaitMs = 0;
4698 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004699 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004700
4701 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4702 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07004703 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07004704 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4705 bool doMute = false;
4706
4707 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4708 doMute = true;
4709 outputDesc->mStrategyMutedByDevice[i] = true;
4710 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4711 doMute = true;
4712 outputDesc->mStrategyMutedByDevice[i] = false;
4713 }
Eric Laurent99401132014-05-07 19:48:15 -07004714 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004715 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004716 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004717 // skip output if it does not share any device with current output
4718 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4719 == AUDIO_DEVICE_NONE) {
4720 continue;
4721 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07004722 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07004723 mute ? "muting" : "unmuting", i, curDevice);
4724 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01004725 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004726 if (mute) {
4727 // FIXME: should not need to double latency if volume could be applied
4728 // immediately by the audioflinger mixer. We must account for the delay
4729 // between now and the next time the audioflinger thread for this output
4730 // will process a buffer (which corresponds to one buffer size,
4731 // usually 1/2 or 1/4 of the latency).
4732 if (muteWaitMs < desc->latency() * 2) {
4733 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004734 }
4735 }
4736 }
4737 }
4738 }
4739 }
4740
Eric Laurent99401132014-05-07 19:48:15 -07004741 // temporary mute output if device selection changes to avoid volume bursts due to
4742 // different per device volumes
4743 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07004744 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
4745 // temporary mute duration is conservatively set to 4 times the reported latency
4746 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
4747 if (muteWaitMs < tempMuteWaitMs) {
4748 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07004749 }
Eric Laurentdc462862016-07-19 12:29:53 -07004750
Eric Laurent99401132014-05-07 19:48:15 -07004751 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01004752 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07004753 // make sure that we do not start the temporary mute period too early in case of
4754 // delayed device change
4755 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004756 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07004757 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07004758 }
4759 }
4760 }
4761
Eric Laurente552edb2014-03-10 17:42:56 -07004762 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4763 if (muteWaitMs > delayMs) {
4764 muteWaitMs -= delayMs;
4765 usleep(muteWaitMs * 1000);
4766 return muteWaitMs;
4767 }
4768 return 0;
4769}
4770
Eric Laurentc75307b2015-03-17 15:29:32 -07004771uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004772 audio_devices_t device,
4773 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004774 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004775 audio_patch_handle_t *patchHandle,
Andy Hung7c7124e2017-10-20 12:03:34 -07004776 const char *address,
4777 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07004778{
Eric Laurentc75307b2015-03-17 15:29:32 -07004779 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004780 AudioParameter param;
4781 uint32_t muteWaitMs;
4782
4783 if (outputDesc->isDuplicated()) {
Andy Hung7c7124e2017-10-20 12:03:34 -07004784 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs,
4785 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
4786 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs,
4787 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07004788 return muteWaitMs;
4789 }
4790 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4791 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07004792 if ((device != AUDIO_DEVICE_NONE) &&
Andy Hung7c7124e2017-10-20 12:03:34 -07004793 ((device & outputDesc->supportedDevices()) == AUDIO_DEVICE_NONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004794 return 0;
4795 }
4796
4797 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07004798 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004799
4800 audio_devices_t prevDevice = outputDesc->mDevice;
4801
Paul McLeanaa981192015-03-21 09:55:15 -07004802 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004803
4804 if (device != AUDIO_DEVICE_NONE) {
4805 outputDesc->mDevice = device;
4806 }
Andy Hung7c7124e2017-10-20 12:03:34 -07004807
4808 // if the outputs are not materially active, there is no need to mute.
4809 if (requiresMuteCheck) {
4810 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4811 } else {
4812 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
4813 muteWaitMs = 0;
4814 }
Eric Laurente552edb2014-03-10 17:42:56 -07004815
4816 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07004817 // the requested device is AUDIO_DEVICE_NONE
4818 // OR the requested device is the same as current device
4819 // AND force is not specified
4820 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07004821 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07004822 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
4823 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004824 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004825 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004826 return muteWaitMs;
4827 }
4828
4829 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004830
Eric Laurente552edb2014-03-10 17:42:56 -07004831 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004832 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004833 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004834 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07004835 DeviceVector deviceList;
4836 if ((address == NULL) || (strlen(address) == 0)) {
4837 deviceList = mAvailableOutputDevices.getDevicesFromType(device);
4838 } else {
4839 deviceList = mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
4840 }
4841
Eric Laurent1c333e22014-05-20 10:48:17 -07004842 if (!deviceList.isEmpty()) {
4843 struct audio_patch patch;
4844 outputDesc->toAudioPortConfig(&patch.sources[0]);
4845 patch.num_sources = 1;
4846 patch.num_sinks = 0;
4847 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4848 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004849 patch.num_sinks++;
4850 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004851 ssize_t index;
4852 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4853 index = mAudioPatches.indexOfKey(*patchHandle);
4854 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004855 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004856 }
4857 sp< AudioPatch> patchDesc;
4858 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4859 if (index >= 0) {
4860 patchDesc = mAudioPatches.valueAt(index);
4861 afPatchHandle = patchDesc->mAfPatchHandle;
4862 }
4863
Eric Laurent1c333e22014-05-20 10:48:17 -07004864 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004865 &afPatchHandle,
4866 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004867 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4868 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004869 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004870 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004871 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01004872 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004873 addAudioPatch(patchDesc->mHandle, patchDesc);
4874 } else {
4875 patchDesc->mPatch = patch;
4876 }
4877 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07004878 if (patchHandle) {
4879 *patchHandle = patchDesc->mHandle;
4880 }
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004881 outputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004882 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004883 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004884 }
4885 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004886
4887 // inform all input as well
4888 for (size_t i = 0; i < mInputs.size(); i++) {
4889 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01004890 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08004891 AudioParameter inputCmd = AudioParameter();
4892 ALOGV("%s: inform input %d of device:%d", __func__,
4893 inputDescriptor->mIoHandle, device);
4894 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4895 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4896 inputCmd.toString(),
4897 delayMs);
4898 }
4899 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004900 }
Eric Laurente552edb2014-03-10 17:42:56 -07004901
4902 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07004903 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004904
4905 return muteWaitMs;
4906}
4907
Eric Laurentc75307b2015-03-17 15:29:32 -07004908status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07004909 int delayMs,
4910 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004911{
Eric Laurent6a94d692014-05-20 11:18:06 -07004912 ssize_t index;
4913 if (patchHandle) {
4914 index = mAudioPatches.indexOfKey(*patchHandle);
4915 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004916 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004917 }
4918 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004919 return INVALID_OPERATION;
4920 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004921 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4922 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004923 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07004924 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07004925 removeAudioPatch(patchDesc->mHandle);
4926 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004927 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004928 return status;
4929}
4930
4931status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4932 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004933 bool force,
4934 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004935{
4936 status_t status = NO_ERROR;
4937
Eric Laurent1f2f2232014-06-02 12:01:23 -07004938 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004939 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4940 inputDesc->mDevice = device;
4941
4942 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4943 if (!deviceList.isEmpty()) {
4944 struct audio_patch patch;
4945 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004946 // AUDIO_SOURCE_HOTWORD is for internal use only:
4947 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004948 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
Eric Laurent599c7582015-12-07 18:05:55 -08004949 !inputDesc->isSoundTrigger()) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004950 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4951 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004952 patch.num_sinks = 1;
4953 //only one input device for now
4954 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004955 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004956 ssize_t index;
4957 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4958 index = mAudioPatches.indexOfKey(*patchHandle);
4959 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004960 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004961 }
4962 sp< AudioPatch> patchDesc;
4963 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4964 if (index >= 0) {
4965 patchDesc = mAudioPatches.valueAt(index);
4966 afPatchHandle = patchDesc->mAfPatchHandle;
4967 }
4968
Eric Laurent1c333e22014-05-20 10:48:17 -07004969 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004970 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004971 0);
4972 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004973 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004974 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004975 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01004976 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004977 addAudioPatch(patchDesc->mHandle, patchDesc);
4978 } else {
4979 patchDesc->mPatch = patch;
4980 }
4981 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07004982 if (patchHandle) {
4983 *patchHandle = patchDesc->mHandle;
4984 }
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004985 inputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004986 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004987 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004988 }
4989 }
4990 }
4991 return status;
4992}
4993
Eric Laurent6a94d692014-05-20 11:18:06 -07004994status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4995 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004996{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004997 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004998 ssize_t index;
4999 if (patchHandle) {
5000 index = mAudioPatches.indexOfKey(*patchHandle);
5001 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005002 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005003 }
5004 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005005 return INVALID_OPERATION;
5006 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005007 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5008 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005009 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005010 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005011 removeAudioPatch(patchDesc->mHandle);
5012 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005013 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005014 return status;
5015}
5016
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005017sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005018 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005019 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005020 audio_format_t& format,
5021 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005022 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005023{
5024 // Choose an input profile based on the requested capture parameters: select the first available
5025 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005026 //
5027 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5028 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005029
5030 for (size_t i = 0; i < mHwModules.size(); i++)
5031 {
5032 if (mHwModules[i]->mHandle == 0) {
5033 continue;
5034 }
5035 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
5036 {
Eric Laurent1c333e22014-05-20 10:48:17 -07005037 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07005038 // profile->log();
Eric Laurent275e8e92014-11-30 15:14:47 -08005039 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07005040 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005041 format,
5042 &format /*updatedFormat*/,
5043 channelMask,
5044 &channelMask /*updatedChannelMask*/,
5045 (audio_output_flags_t) flags)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005046
Eric Laurente552edb2014-03-10 17:42:56 -07005047 return profile;
5048 }
5049 }
5050 }
5051 return NULL;
5052}
5053
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005054
5055audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005056 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005057{
François Gaffie036e1e92015-03-19 10:16:24 +01005058 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5059 audio_devices_t selectedDeviceFromMix =
5060 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005061
François Gaffie036e1e92015-03-19 10:16:24 +01005062 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5063 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005064 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005065 return getDeviceForInputSource(inputSource);
5066}
5067
5068audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5069{
Eric Laurentad2e7b92017-09-14 20:06:42 -07005070 // Routing
5071 // Scan the whole RouteMap to see if we have an explicit route:
5072 // if the input source in the RouteMap is the same as the argument above,
5073 // and activity count is non-zero and the device in the route descriptor is available
5074 // then select this device.
Paul McLean466dc8e2015-04-17 13:15:36 -06005075 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
5076 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
Eric Laurentad2e7b92017-09-14 20:06:42 -07005077 if ((inputSource == route->mSource) && route->isActive() &&
5078 (mAvailableInputDevices.indexOf(route->mDeviceDescriptor) >= 0)) {
Paul McLean466dc8e2015-04-17 13:15:36 -06005079 return route->mDeviceDescriptor->type();
5080 }
5081 }
5082
5083 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005084}
5085
Eric Laurente0720872014-03-11 09:30:41 -07005086float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005087 int index,
5088 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005089{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005090 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005091
5092 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5093 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5094 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5095 // the ringtone volume
5096 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5097 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5098 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5099 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5100 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5101 }
5102
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005103 // in-call: always cap earpiece volume by voice volume + some low headroom
5104 if ((stream != AUDIO_STREAM_VOICE_CALL) && (device & AUDIO_DEVICE_OUT_EARPIECE) && isInCall()) {
5105 switch (stream) {
5106 case AUDIO_STREAM_SYSTEM:
5107 case AUDIO_STREAM_RING:
5108 case AUDIO_STREAM_MUSIC:
5109 case AUDIO_STREAM_ALARM:
5110 case AUDIO_STREAM_NOTIFICATION:
5111 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5112 case AUDIO_STREAM_DTMF:
5113 case AUDIO_STREAM_ACCESSIBILITY: {
5114 const float maxVoiceVolDb = computeVolume(AUDIO_STREAM_VOICE_CALL, index, device)
5115 + IN_CALL_EARPIECE_HEADROOM_DB;
5116 if (volumeDB > maxVoiceVolDb) {
5117 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5118 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5119 volumeDB = maxVoiceVolDb;
5120 }
5121 } break;
5122 default:
5123 break;
5124 }
5125 }
5126
Eric Laurente552edb2014-03-10 17:42:56 -07005127 // if a headset is connected, apply the following rules to ring tones and notifications
5128 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005129 // - always attenuate notifications volume by 6dB
5130 // - attenuate ring tones volume by 6dB unless music is not playing and
5131 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005132 // - if music is playing, always limit the volume to current music volume,
5133 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005134 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005135 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5136 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5137 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005138 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
5139 AUDIO_DEVICE_OUT_USB_HEADSET)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005140 ((stream_strategy == STRATEGY_SONIFICATION)
5141 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005142 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005143 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005144 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005145 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005146 // when the phone is ringing we must consider that music could have been paused just before
5147 // by the music application and behave as if music was active if the last music track was
5148 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005149 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005150 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005151 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005152 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005153 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005154 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5155 musicDevice),
5156 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005157 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5158 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005159 if (volumeDB > minVolDB) {
5160 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005161 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005162 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005163 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5164 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5165 // on A2DP, also ensure notification volume is not too low compared to media when
5166 // intended to be played
5167 if ((volumeDB > -96.0f) &&
5168 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5169 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5170 stream, device,
5171 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5172 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5173 }
5174 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005175 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5176 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005177 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005178 }
5179 }
5180
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005181 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005182}
5183
Eric Laurente0720872014-03-11 09:30:41 -07005184status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005185 int index,
5186 const sp<AudioOutputDescriptor>& outputDesc,
5187 audio_devices_t device,
5188 int delayMs,
5189 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005190{
Eric Laurente552edb2014-03-10 17:42:56 -07005191 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005192 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005193 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005194 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005195 return NO_ERROR;
5196 }
François Gaffie2110e042015-03-24 08:41:51 +01005197 audio_policy_forced_cfg_t forceUseForComm =
5198 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005199 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005200 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5201 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005202 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005203 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005204 return INVALID_OPERATION;
5205 }
5206
Eric Laurentc75307b2015-03-17 15:29:32 -07005207 if (device == AUDIO_DEVICE_NONE) {
5208 device = outputDesc->device();
5209 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005210
Eric Laurentffbc80f2015-03-18 18:30:19 -07005211 float volumeDb = computeVolume(stream, index, device);
Eric Laurentc75307b2015-03-17 15:29:32 -07005212 if (outputDesc->isFixedVolume(device)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005213 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005214 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005215
Eric Laurentffbc80f2015-03-18 18:30:19 -07005216 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005217
Eric Laurent3b73df72014-03-11 09:06:29 -07005218 if (stream == AUDIO_STREAM_VOICE_CALL ||
5219 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005220 float voiceVolume;
5221 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005222 if (stream == AUDIO_STREAM_VOICE_CALL) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005223 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005224 } else {
5225 voiceVolume = 1.0;
5226 }
5227
Eric Laurent18fba842016-03-31 14:41:26 -07005228 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005229 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5230 mLastVoiceVolume = voiceVolume;
5231 }
5232 }
5233
5234 return NO_ERROR;
5235}
5236
Eric Laurentc75307b2015-03-17 15:29:32 -07005237void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5238 audio_devices_t device,
5239 int delayMs,
5240 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005241{
Eric Laurentc75307b2015-03-17 15:29:32 -07005242 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005243
Eric Laurent794fde22016-03-11 09:50:45 -08005244 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005245 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005246 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005247 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005248 device,
5249 delayMs,
5250 force);
5251 }
5252}
5253
Eric Laurente0720872014-03-11 09:30:41 -07005254void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005255 bool on,
5256 const sp<AudioOutputDescriptor>& outputDesc,
5257 int delayMs,
5258 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005259{
Eric Laurent72249d52015-06-08 11:12:15 -07005260 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5261 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005262 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005263 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005264 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005265 }
5266 }
5267}
5268
Eric Laurente0720872014-03-11 09:30:41 -07005269void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005270 bool on,
5271 const sp<AudioOutputDescriptor>& outputDesc,
5272 int delayMs,
5273 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005274{
Eric Laurente552edb2014-03-10 17:42:56 -07005275 if (device == AUDIO_DEVICE_NONE) {
5276 device = outputDesc->device();
5277 }
5278
Eric Laurentc75307b2015-03-17 15:29:32 -07005279 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5280 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005281
5282 if (on) {
5283 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005284 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005285 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005286 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005287 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005288 }
5289 }
5290 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5291 outputDesc->mMuteCount[stream]++;
5292 } else {
5293 if (outputDesc->mMuteCount[stream] == 0) {
5294 ALOGV("setStreamMute() unmuting non muted stream!");
5295 return;
5296 }
5297 if (--outputDesc->mMuteCount[stream] == 0) {
5298 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005299 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005300 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005301 device,
5302 delayMs);
5303 }
5304 }
5305}
5306
Eric Laurente0720872014-03-11 09:30:41 -07005307void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005308 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005309{
Eric Laurent87ffa392015-05-22 10:32:38 -07005310 if(!hasPrimaryOutput()) {
5311 return;
5312 }
5313
Eric Laurente552edb2014-03-10 17:42:56 -07005314 // if the stream pertains to sonification strategy and we are in call we must
5315 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5316 // in the device used for phone strategy and play the tone if the selected device does not
5317 // interfere with the device used for phone strategy
5318 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5319 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005320 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005321 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5322 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005323 sp<SwAudioOutputDescriptor> outputDesc = mPrimaryOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07005324 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5325 stream, starting, outputDesc->mDevice, stateChange);
5326 if (outputDesc->mRefCount[stream]) {
5327 int muteCount = 1;
5328 if (stateChange) {
5329 muteCount = outputDesc->mRefCount[stream];
5330 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005331 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005332 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5333 for (int i = 0; i < muteCount; i++) {
5334 setStreamMute(stream, starting, mPrimaryOutput);
5335 }
5336 } else {
5337 ALOGV("handleIncallSonification() high visibility");
5338 if (outputDesc->device() &
5339 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5340 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5341 for (int i = 0; i < muteCount; i++) {
5342 setStreamMute(stream, starting, mPrimaryOutput);
5343 }
5344 }
5345 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005346 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5347 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005348 } else {
5349 mpClientInterface->stopTone();
5350 }
5351 }
5352 }
5353 }
5354}
5355
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005356audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5357{
5358 // flags to stream type mapping
5359 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5360 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5361 }
5362 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5363 return AUDIO_STREAM_BLUETOOTH_SCO;
5364 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005365 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5366 return AUDIO_STREAM_TTS;
5367 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005368
5369 // usage to stream type mapping
5370 switch (attr->usage) {
5371 case AUDIO_USAGE_MEDIA:
5372 case AUDIO_USAGE_GAME:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005373 case AUDIO_USAGE_ASSISTANT:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005374 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5375 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005376 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5377 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005378 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5379 return AUDIO_STREAM_SYSTEM;
5380 case AUDIO_USAGE_VOICE_COMMUNICATION:
5381 return AUDIO_STREAM_VOICE_CALL;
5382
5383 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5384 return AUDIO_STREAM_DTMF;
5385
5386 case AUDIO_USAGE_ALARM:
5387 return AUDIO_STREAM_ALARM;
5388 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5389 return AUDIO_STREAM_RING;
5390
5391 case AUDIO_USAGE_NOTIFICATION:
5392 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5393 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5394 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5395 case AUDIO_USAGE_NOTIFICATION_EVENT:
5396 return AUDIO_STREAM_NOTIFICATION;
5397
5398 case AUDIO_USAGE_UNKNOWN:
5399 default:
5400 return AUDIO_STREAM_MUSIC;
5401 }
5402}
Eric Laurente83b55d2014-11-14 10:06:21 -08005403
François Gaffie53615e22015-03-19 09:24:12 +01005404bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5405{
Eric Laurente83b55d2014-11-14 10:06:21 -08005406 // has flags that map to a strategy?
5407 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5408 return true;
5409 }
5410
5411 // has known usage?
5412 switch (paa->usage) {
5413 case AUDIO_USAGE_UNKNOWN:
5414 case AUDIO_USAGE_MEDIA:
5415 case AUDIO_USAGE_VOICE_COMMUNICATION:
5416 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5417 case AUDIO_USAGE_ALARM:
5418 case AUDIO_USAGE_NOTIFICATION:
5419 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5420 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5421 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5422 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5423 case AUDIO_USAGE_NOTIFICATION_EVENT:
5424 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5425 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5426 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5427 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005428 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005429 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005430 break;
5431 default:
5432 return false;
5433 }
5434 return true;
5435}
5436
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005437bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005438 routing_strategy strategy, uint32_t inPastMs,
5439 nsecs_t sysTime) const
5440{
5441 if ((sysTime == 0) && (inPastMs != 0)) {
5442 sysTime = systemTime();
5443 }
Eric Laurent794fde22016-03-11 09:50:45 -08005444 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005445 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5446 (NUM_STRATEGIES == strategy)) &&
5447 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5448 return true;
5449 }
5450 }
5451 return false;
5452}
5453
François Gaffie2110e042015-03-24 08:41:51 +01005454audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5455{
5456 return mEngine->getForceUse(usage);
5457}
5458
5459bool AudioPolicyManager::isInCall()
5460{
5461 return isStateInCall(mEngine->getPhoneState());
5462}
5463
5464bool AudioPolicyManager::isStateInCall(int state)
5465{
5466 return is_state_in_call(state);
5467}
5468
Eric Laurentd60560a2015-04-10 11:31:20 -07005469void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5470{
5471 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5472 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
5473 if (sourceDesc->mDevice->equals(deviceDesc)) {
5474 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle());
5475 stopAudioSource(sourceDesc->getHandle());
5476 }
5477 }
5478
5479 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5480 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5481 bool release = false;
5482 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5483 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5484 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5485 source->ext.device.type == deviceDesc->type()) {
5486 release = true;
5487 }
5488 }
5489 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5490 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5491 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5492 sink->ext.device.type == deviceDesc->type()) {
5493 release = true;
5494 }
5495 }
5496 if (release) {
5497 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5498 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5499 }
5500 }
5501}
5502
Phil Burk09bc4612016-02-24 15:58:15 -08005503// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005504void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5505 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005506 // TODO Set this based on Config properties.
5507 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005508
5509 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5510 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005511 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005512
5513 // Analyze original support for various formats.
Phil Burk07ac1142016-03-25 13:39:29 -07005514 bool supportsAC3 = false;
5515 bool supportsOtherSurround = false;
Phil Burk09bc4612016-02-24 15:58:15 -08005516 bool supportsIEC61937 = false;
5517 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
5518 audio_format_t format = formats[formatIndex];
Phil Burk09bc4612016-02-24 15:58:15 -08005519 switch (format) {
5520 case AUDIO_FORMAT_AC3:
Phil Burk07ac1142016-03-25 13:39:29 -07005521 supportsAC3 = true;
5522 break;
Phil Burk09bc4612016-02-24 15:58:15 -08005523 case AUDIO_FORMAT_E_AC3:
5524 case AUDIO_FORMAT_DTS:
5525 case AUDIO_FORMAT_DTS_HD:
Phil Burk07ac1142016-03-25 13:39:29 -07005526 supportsOtherSurround = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005527 break;
5528 case AUDIO_FORMAT_IEC61937:
5529 supportsIEC61937 = true;
5530 break;
5531 default:
5532 break;
5533 }
5534 }
Phil Burk09bc4612016-02-24 15:58:15 -08005535
5536 // Modify formats based on surround preferences.
5537 // If NEVER, remove support for surround formats.
Phil Burk07ac1142016-03-25 13:39:29 -07005538 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5539 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5540 // Remove surround sound related formats.
5541 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5542 audio_format_t format = formats[formatIndex];
5543 switch(format) {
5544 case AUDIO_FORMAT_AC3:
5545 case AUDIO_FORMAT_E_AC3:
5546 case AUDIO_FORMAT_DTS:
5547 case AUDIO_FORMAT_DTS_HD:
5548 case AUDIO_FORMAT_IEC61937:
Phil Burk07ac1142016-03-25 13:39:29 -07005549 formats.removeAt(formatIndex);
5550 break;
5551 default:
5552 formatIndex++; // keep it
5553 break;
5554 }
Phil Burk09bc4612016-02-24 15:58:15 -08005555 }
Phil Burk07ac1142016-03-25 13:39:29 -07005556 supportsAC3 = false;
5557 supportsOtherSurround = false;
5558 supportsIEC61937 = false;
Phil Burk09bc4612016-02-24 15:58:15 -08005559 }
Phil Burk07ac1142016-03-25 13:39:29 -07005560 } else { // AUTO or ALWAYS
5561 // Most TVs support AC3 even if they do not report it in the EDID.
5562 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
5563 && !supportsAC3) {
5564 formats.add(AUDIO_FORMAT_AC3);
5565 supportsAC3 = true;
5566 }
5567
5568 // If ALWAYS, add support for raw surround formats if all are missing.
5569 // This assumes that if any of these formats are reported by the HAL
5570 // then the report is valid and should not be modified.
5571 if ((forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS)
5572 && !supportsOtherSurround) {
5573 formats.add(AUDIO_FORMAT_E_AC3);
5574 formats.add(AUDIO_FORMAT_DTS);
5575 formats.add(AUDIO_FORMAT_DTS_HD);
5576 supportsOtherSurround = true;
5577 }
5578
5579 // Add support for IEC61937 if any raw surround supported.
5580 // The HAL could do this but add it here, just in case.
5581 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
5582 formats.add(AUDIO_FORMAT_IEC61937);
5583 supportsIEC61937 = true;
5584 }
Phil Burk09bc4612016-02-24 15:58:15 -08005585 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005586}
5587
5588// Modify the list of channel masks supported.
5589void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
5590 ChannelsVector &channelMasks = *channelMasksPtr;
5591 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5592 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5593
5594 // If NEVER, then remove support for channelMasks > stereo.
5595 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5596 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5597 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5598 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5599 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5600 channelMasks.removeAt(maskIndex);
5601 } else {
5602 maskIndex++;
5603 }
5604 }
5605 // If ALWAYS, then make sure we at least support 5.1
5606 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5607 bool supports5dot1 = false;
5608 // Are there any channel masks that can be considered "surround"?
5609 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); maskIndex++) {
5610 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5611 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5612 supports5dot1 = true;
5613 break;
5614 }
5615 }
5616 // If not then add 5.1 support.
5617 if (!supports5dot1) {
5618 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
5619 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
5620 }
Phil Burk09bc4612016-02-24 15:58:15 -08005621 }
5622}
5623
Phil Burk00eeb322016-03-31 12:41:00 -07005624void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
5625 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005626 AudioProfileVector &profiles)
5627{
5628 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07005629
François Gaffie112b0af2015-11-19 16:13:25 +01005630 // Format MUST be checked first to update the list of AudioProfile
5631 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005632 reply = mpClientInterface->getParameters(
5633 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
Phil Burk0709b0a2016-03-31 12:54:57 -07005634 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005635 AudioParameter repliedParameters(reply);
5636 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005637 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005638 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5639 return;
5640 }
Phil Burk09bc4612016-02-24 15:58:15 -08005641 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07005642 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005643 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005644 }
Phil Burk09bc4612016-02-24 15:58:15 -08005645 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005646 }
5647 const FormatVector &supportedFormats = profiles.getSupportedFormats();
5648
Eric Laurent20eb3a42016-01-26 18:39:17 -08005649 for (size_t formatIndex = 0; formatIndex < supportedFormats.size(); formatIndex++) {
François Gaffie112b0af2015-11-19 16:13:25 +01005650 audio_format_t format = supportedFormats[formatIndex];
Eric Laurent20eb3a42016-01-26 18:39:17 -08005651 ChannelsVector channelMasks;
5652 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005653 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07005654 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01005655
5656 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005657 reply = mpClientInterface->getParameters(
5658 ioHandle,
5659 requestedParameters.toString() + ";" +
5660 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01005661 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005662 AudioParameter repliedParameters(reply);
5663 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005664 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005665 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005666 }
5667 }
5668 if (profiles.hasDynamicChannelsFor(format)) {
5669 reply = mpClientInterface->getParameters(ioHandle,
5670 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07005671 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01005672 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005673 AudioParameter repliedParameters(reply);
5674 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005675 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005676 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07005677 if (device == AUDIO_DEVICE_OUT_HDMI) {
5678 filterSurroundChannelMasks(&channelMasks);
5679 }
François Gaffie112b0af2015-11-19 16:13:25 +01005680 }
5681 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08005682 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01005683 }
5684}
Eric Laurentd60560a2015-04-10 11:31:20 -07005685
Eric Laurente552edb2014-03-10 17:42:56 -07005686}; // namespace android