blob: bdfaf2f811e7aa29e0e71e870d5903b27f8ec32f [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070017#define LOG_TAG "APM_AudioPolicyManager"
Eric Laurente552edb2014-03-10 17:42:56 -070018//#define LOG_NDEBUG 0
19
20//#define VERY_VERBOSE_LOGGING
21#ifdef VERY_VERBOSE_LOGGING
22#define ALOGVV ALOGV
23#else
24#define ALOGVV(a...) do { } while(0)
25#endif
26
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +090027#define AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH 128
28#define AUDIO_POLICY_XML_CONFIG_FILE_NAME "audio_policy_configuration.xml"
François Gaffief4ad6e52015-11-19 16:59:57 +010029
Eric Laurentd4692962014-05-05 18:13:44 -070030#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070031#include <math.h>
Eric Laurentd4692962014-05-05 18:13:44 -070032
François Gaffie2110e042015-03-24 08:41:51 +010033#include <AudioPolicyManagerInterface.h>
34#include <AudioPolicyEngineInstance.h>
Mathias Agopian05d19b02017-02-28 16:28:19 -080035#include <cutils/atomic.h>
Eric Laurente552edb2014-03-10 17:42:56 -070036#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070037#include <utils/Log.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070038#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080039#include <media/AudioPolicyHelper.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070040#include <soundtrigger/SoundTrigger.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070041#include <system/audio.h>
Mikhail Naganov9ee05402016-10-13 15:58:17 -070042#include <audio_policy_conf.h>
Eric Laurentd4692962014-05-05 18:13:44 -070043#include "AudioPolicyManager.h"
François Gaffied1ab2bd2015-12-02 18:20:06 +010044#ifndef USE_XML_AUDIO_POLICY_CONF
François Gaffie53615e22015-03-19 09:24:12 +010045#include <ConfigParsingUtils.h>
François Gaffied1ab2bd2015-12-02 18:20:06 +010046#include <StreamDescriptor.h>
François Gaffief4ad6e52015-11-19 16:59:57 +010047#endif
François Gaffied1ab2bd2015-12-02 18:20:06 +010048#include <Serializer.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010049#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010050#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070051
Eric Laurent3b73df72014-03-11 09:06:29 -070052namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070053
Eric Laurentdc462862016-07-19 12:29:53 -070054//FIXME: workaround for truncated touch sounds
55// to be removed when the problem is handled by system UI
56#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070057
58// Largest difference in dB on earpiece in call between the voice volume and another
59// media / notification / system volume.
60constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
61
Eric Laurente552edb2014-03-10 17:42:56 -070062// ----------------------------------------------------------------------------
63// AudioPolicyInterface implementation
64// ----------------------------------------------------------------------------
65
Eric Laurente0720872014-03-11 09:30:41 -070066status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -080067 audio_policy_dev_state_t state,
68 const char *device_address,
69 const char *device_name)
Eric Laurente552edb2014-03-10 17:42:56 -070070{
Paul McLeane743a472015-01-28 11:07:31 -080071 return setDeviceConnectionStateInt(device, state, device_address, device_name);
Eric Laurentc73ca6e2014-12-12 14:34:22 -080072}
73
François Gaffie44481e72016-04-20 07:49:57 +020074void AudioPolicyManager::broadcastDeviceConnectionState(audio_devices_t device,
75 audio_policy_dev_state_t state,
76 const String8 &device_address)
77{
78 AudioParameter param(device_address);
79 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganov388360c2016-10-17 17:09:41 -070080 AudioParameter::keyStreamConnect : AudioParameter::keyStreamDisconnect);
François Gaffie44481e72016-04-20 07:49:57 +020081 param.addInt(key, device);
82 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
83}
84
Eric Laurentc73ca6e2014-12-12 14:34:22 -080085status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
Eric Laurenta1d525f2015-01-29 13:36:45 -080086 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -080087 const char *device_address,
88 const char *device_name)
Eric Laurentc73ca6e2014-12-12 14:34:22 -080089{
Paul McLeane743a472015-01-28 11:07:31 -080090 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s",
91- device, state, device_address, device_name);
Eric Laurente552edb2014-03-10 17:42:56 -070092
93 // connect/disconnect only 1 device at a time
94 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
95
François Gaffie53615e22015-03-19 09:24:12 +010096 sp<DeviceDescriptor> devDesc =
97 mHwModules.getDeviceDescriptor(device, device_address, device_name);
Paul McLeane743a472015-01-28 11:07:31 -080098
Eric Laurente552edb2014-03-10 17:42:56 -070099 // handle output devices
100 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700101 SortedVector <audio_io_handle_t> outputs;
102
Eric Laurent3a4311c2014-03-17 12:00:47 -0700103 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
104
Eric Laurente552edb2014-03-10 17:42:56 -0700105 // save a copy of the opened output descriptors before any output is opened or closed
106 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
107 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700108 switch (state)
109 {
110 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800111 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700112 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700113 ALOGW("setDeviceConnectionState() device already connected: %x", device);
114 return INVALID_OPERATION;
115 }
116 ALOGV("setDeviceConnectionState() connecting device %x", device);
117
Eric Laurente552edb2014-03-10 17:42:56 -0700118 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700119 index = mAvailableOutputDevices.add(devDesc);
120 if (index >= 0) {
François Gaffie53615e22015-03-19 09:24:12 +0100121 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700122 if (module == 0) {
123 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
124 device);
125 mAvailableOutputDevices.remove(devDesc);
126 return INVALID_OPERATION;
127 }
Paul McLeane743a472015-01-28 11:07:31 -0800128 mAvailableOutputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700129 } else {
130 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700131 }
132
François Gaffie44481e72016-04-20 07:49:57 +0200133 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
134 // parameters on newly connected devices (instead of opening the outputs...)
135 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
136
Eric Laurenta1d525f2015-01-29 13:36:45 -0800137 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700138 mAvailableOutputDevices.remove(devDesc);
François Gaffie44481e72016-04-20 07:49:57 +0200139
140 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
141 devDesc->mAddress);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700142 return INVALID_OPERATION;
143 }
François Gaffie2110e042015-03-24 08:41:51 +0100144 // Propagate device availability to Engine
145 mEngine->setDeviceConnectionState(devDesc, state);
146
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700147 // outputs should never be empty here
148 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
149 "checkOutputsForDevice() returned no outputs but status OK");
150 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
151 outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800152
Eric Laurent3ae5f312015-02-03 17:12:08 -0800153 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700154 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700155 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700156 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700157 ALOGW("setDeviceConnectionState() device not connected: %x", device);
158 return INVALID_OPERATION;
159 }
160
Paul McLean5c477aa2014-08-20 16:47:57 -0700161 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
162
Paul McLeane743a472015-01-28 11:07:31 -0800163 // Send Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200164 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700165
Eric Laurente552edb2014-03-10 17:42:56 -0700166 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700167 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700168
Eric Laurenta1d525f2015-01-29 13:36:45 -0800169 checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress);
François Gaffie2110e042015-03-24 08:41:51 +0100170
171 // Propagate device availability to Engine
172 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700173 } break;
174
175 default:
176 ALOGE("setDeviceConnectionState() invalid state: %x", state);
177 return BAD_VALUE;
178 }
179
Eric Laurent3a4311c2014-03-17 12:00:47 -0700180 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
181 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700182 checkA2dpSuspend();
183 checkOutputForAllStrategies();
184 // outputs must be closed after checkOutputForAllStrategies() is executed
185 if (!outputs.isEmpty()) {
186 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700187 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700188 // close unused outputs after device disconnection or direct outputs that have been
189 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700190 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700191 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
192 (desc->mDirectOpenCount == 0))) {
193 closeOutput(outputs[i]);
194 }
195 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700196 // check again after closing A2DP output to reset mA2dpSuspended if needed
197 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700198 }
199
200 updateDevicesAndOutputs();
Eric Laurent87ffa392015-05-22 10:32:38 -0700201 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700202 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
203 updateCallRouting(newDevice);
204 }
Eric Laurente552edb2014-03-10 17:42:56 -0700205 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700206 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
207 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
208 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700209 // do not force device change on duplicated output because if device is 0, it will
210 // also force a device 0 for the two outputs it is duplicated to which may override
211 // a valid device selection on those outputs.
Eric Laurentc75307b2015-03-17 15:29:32 -0700212 bool force = !desc->isDuplicated()
François Gaffie53615e22015-03-19 09:24:12 +0100213 && (!device_distinguishes_on_address(device)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700214 // always force when disconnecting (a non-duplicated device)
215 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
Eric Laurentc75307b2015-03-17 15:29:32 -0700216 setOutputDevice(desc, newDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700217 }
Eric Laurente552edb2014-03-10 17:42:56 -0700218 }
219
Eric Laurentd60560a2015-04-10 11:31:20 -0700220 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
221 cleanUpForDevice(devDesc);
222 }
223
Eric Laurent72aa32f2014-05-30 18:51:48 -0700224 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700225 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700226 } // end if is output device
227
Eric Laurente552edb2014-03-10 17:42:56 -0700228 // handle input devices
229 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700230 SortedVector <audio_io_handle_t> inputs;
231
Eric Laurent3a4311c2014-03-17 12:00:47 -0700232 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700233 switch (state)
234 {
235 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700236 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700237 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700238 ALOGW("setDeviceConnectionState() device already connected: %d", device);
239 return INVALID_OPERATION;
240 }
François Gaffie53615e22015-03-19 09:24:12 +0100241 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700242 if (module == NULL) {
243 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
244 device);
245 return INVALID_OPERATION;
246 }
François Gaffie44481e72016-04-20 07:49:57 +0200247
248 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
249 // parameters on newly connected devices (instead of opening the inputs...)
250 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
251
Paul McLean9080a4c2015-06-18 08:24:02 -0700252 if (checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress) != NO_ERROR) {
François Gaffie44481e72016-04-20 07:49:57 +0200253 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
254 devDesc->mAddress);
Eric Laurentd4692962014-05-05 18:13:44 -0700255 return INVALID_OPERATION;
256 }
257
Eric Laurent3a4311c2014-03-17 12:00:47 -0700258 index = mAvailableInputDevices.add(devDesc);
259 if (index >= 0) {
Paul McLeane743a472015-01-28 11:07:31 -0800260 mAvailableInputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700261 } else {
262 return NO_MEMORY;
263 }
Eric Laurent3ae5f312015-02-03 17:12:08 -0800264
François Gaffie2110e042015-03-24 08:41:51 +0100265 // Propagate device availability to Engine
266 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700267 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700268
269 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700270 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700271 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700272 ALOGW("setDeviceConnectionState() device not connected: %d", device);
273 return INVALID_OPERATION;
274 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700275
276 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
277
278 // Set Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200279 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700280
Paul McLean9080a4c2015-06-18 08:24:02 -0700281 checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700282 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700283
François Gaffie2110e042015-03-24 08:41:51 +0100284 // Propagate device availability to Engine
285 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700286 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700287
288 default:
289 ALOGE("setDeviceConnectionState() invalid state: %x", state);
290 return BAD_VALUE;
291 }
292
Eric Laurentd4692962014-05-05 18:13:44 -0700293 closeAllInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700294 // As the input device list can impact the output device selection, update
295 // getDeviceForStrategy() cache
296 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700297
Eric Laurent87ffa392015-05-22 10:32:38 -0700298 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700299 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
300 updateCallRouting(newDevice);
301 }
302
Eric Laurentd60560a2015-04-10 11:31:20 -0700303 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
304 cleanUpForDevice(devDesc);
305 }
306
Eric Laurentb52c1522014-05-20 11:27:36 -0700307 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700308 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700309 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700310
311 ALOGW("setDeviceConnectionState() invalid device: %x", device);
312 return BAD_VALUE;
313}
314
Eric Laurente0720872014-03-11 09:30:41 -0700315audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100316 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700317{
Eric Laurent634b7142016-04-20 13:48:02 -0700318 sp<DeviceDescriptor> devDesc =
319 mHwModules.getDeviceDescriptor(device, device_address, "",
320 (strlen(device_address) != 0)/*matchAddress*/);
321
322 if (devDesc == 0) {
323 ALOGW("getDeviceConnectionState() undeclared device, type %08x, address: %s",
324 device, device_address);
325 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
326 }
François Gaffie53615e22015-03-19 09:24:12 +0100327
Eric Laurent3a4311c2014-03-17 12:00:47 -0700328 DeviceVector *deviceVector;
329
Eric Laurente552edb2014-03-10 17:42:56 -0700330 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700331 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700332 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700333 deviceVector = &mAvailableInputDevices;
334 } else {
335 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
336 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700337 }
Eric Laurent634b7142016-04-20 13:48:02 -0700338
339 return (deviceVector->getDevice(device, String8(device_address)) != 0) ?
340 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800341}
342
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800343status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
344 const char *device_address,
345 const char *device_name)
346{
347 status_t status;
348
349 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s",
350 device, device_address, device_name);
351
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800352 // connect/disconnect only 1 device at a time
353 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
354
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800355 // Check if the device is currently connected
356 sp<DeviceDescriptor> devDesc =
357 mHwModules.getDeviceDescriptor(device, device_address, device_name);
358 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
359 if (index < 0) {
360 // Nothing to do: device is not connected
361 return NO_ERROR;
362 }
363
364 // Toggle the device state: UNAVAILABLE -> AVAILABLE
365 // This will force reading again the device configuration
366 status = setDeviceConnectionState(device,
367 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
368 device_address, device_name);
369 if (status != NO_ERROR) {
370 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
371 status);
372 return status;
373 }
374
375 status = setDeviceConnectionState(device,
376 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
377 device_address, device_name);
378 if (status != NO_ERROR) {
379 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
380 status);
381 return status;
382 }
383
384 return NO_ERROR;
385}
386
Eric Laurentdc462862016-07-19 12:29:53 -0700387uint32_t AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700388{
389 bool createTxPatch = false;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700390 status_t status;
391 audio_patch_handle_t afPatchHandle;
392 DeviceVector deviceList;
Eric Laurentdc462862016-07-19 12:29:53 -0700393 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700394
Andy Hunga76c7de2016-12-13 19:14:31 -0800395 if(!hasPrimaryOutput() || mPrimaryOutput->device() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurentdc462862016-07-19 12:29:53 -0700396 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700397 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800398 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700399 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
400
401 // release existing RX patch if any
402 if (mCallRxPatch != 0) {
403 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
404 mCallRxPatch.clear();
405 }
406 // release TX patch if any
407 if (mCallTxPatch != 0) {
408 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
409 mCallTxPatch.clear();
410 }
411
412 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
413 // via setOutputDevice() on primary output.
414 // Otherwise, create two audio patches for TX and RX path.
415 if (availablePrimaryOutputDevices() & rxDevice) {
Eric Laurentdc462862016-07-19 12:29:53 -0700416 muteWaitMs = setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700417 // If the TX device is also on the primary HW module, setOutputDevice() will take care
418 // of it due to legacy implementation. If not, create a patch.
419 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
420 == AUDIO_DEVICE_NONE) {
421 createTxPatch = true;
422 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700423 } else { // create RX path audio patch
424 struct audio_patch patch;
425
426 patch.num_sources = 1;
427 patch.num_sinks = 1;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700428 deviceList = mAvailableOutputDevices.getDevicesFromType(rxDevice);
429 ALOG_ASSERT(!deviceList.isEmpty(),
430 "updateCallRouting() selected device not in output device list");
431 sp<DeviceDescriptor> rxSinkDeviceDesc = deviceList.itemAt(0);
432 deviceList = mAvailableInputDevices.getDevicesFromType(AUDIO_DEVICE_IN_TELEPHONY_RX);
433 ALOG_ASSERT(!deviceList.isEmpty(),
434 "updateCallRouting() no telephony RX device");
435 sp<DeviceDescriptor> rxSourceDeviceDesc = deviceList.itemAt(0);
436
437 rxSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
438 rxSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
439
440 // request to reuse existing output stream if one is already opened to reach the RX device
441 SortedVector<audio_io_handle_t> outputs =
442 getOutputsForDevice(rxDevice, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700443 audio_io_handle_t output = selectOutput(outputs,
444 AUDIO_OUTPUT_FLAG_NONE,
445 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700446 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700447 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700448 ALOG_ASSERT(!outputDesc->isDuplicated(),
449 "updateCallRouting() RX device output is duplicated");
450 outputDesc->toAudioPortConfig(&patch.sources[1]);
Eric Laurent3bcf8592015-04-03 12:13:24 -0700451 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700452 patch.num_sources = 2;
453 }
454
455 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentdc462862016-07-19 12:29:53 -0700456 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700457 ALOGW_IF(status != NO_ERROR, "updateCallRouting() error %d creating RX audio patch",
458 status);
459 if (status == NO_ERROR) {
François Gaffie98cc1912015-03-18 17:52:40 +0100460 mCallRxPatch = new AudioPatch(&patch, mUidCached);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700461 mCallRxPatch->mAfPatchHandle = afPatchHandle;
462 mCallRxPatch->mUid = mUidCached;
463 }
464 createTxPatch = true;
465 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700466 if (createTxPatch) { // create TX path audio patch
Eric Laurentc2730ba2014-07-20 15:47:07 -0700467 struct audio_patch patch;
Eric Laurent8ae73122016-04-12 10:13:29 -0700468
Eric Laurentc2730ba2014-07-20 15:47:07 -0700469 patch.num_sources = 1;
470 patch.num_sinks = 1;
471 deviceList = mAvailableInputDevices.getDevicesFromType(txDevice);
472 ALOG_ASSERT(!deviceList.isEmpty(),
473 "updateCallRouting() selected device not in input device list");
474 sp<DeviceDescriptor> txSourceDeviceDesc = deviceList.itemAt(0);
475 txSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
476 deviceList = mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_TELEPHONY_TX);
477 ALOG_ASSERT(!deviceList.isEmpty(),
478 "updateCallRouting() no telephony TX device");
479 sp<DeviceDescriptor> txSinkDeviceDesc = deviceList.itemAt(0);
480 txSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
481
482 SortedVector<audio_io_handle_t> outputs =
483 getOutputsForDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700484 audio_io_handle_t output = selectOutput(outputs,
485 AUDIO_OUTPUT_FLAG_NONE,
486 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700487 // request to reuse existing output stream if one is already opened to reach the TX
488 // path output device
489 if (output != AUDIO_IO_HANDLE_NONE) {
490 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
491 ALOG_ASSERT(!outputDesc->isDuplicated(),
492 "updateCallRouting() RX device output is duplicated");
493 outputDesc->toAudioPortConfig(&patch.sources[1]);
Eric Laurent3bcf8592015-04-03 12:13:24 -0700494 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700495 patch.num_sources = 2;
496 }
497
Eric Laurentc0a889f2015-10-14 14:36:34 -0700498 // terminate active capture if on the same HW module as the call TX source device
499 // FIXME: would be better to refine to only inputs whose profile connects to the
500 // call TX device but this information is not in the audio patch and logic here must be
501 // symmetric to the one in startInput()
Eric Laurentfb66dd92016-01-28 18:32:03 -0800502 Vector<sp <AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
503 for (size_t i = 0; i < activeInputs.size(); i++) {
504 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
505 if (activeDesc->hasSameHwModuleAs(txSourceDeviceDesc)) {
506 AudioSessionCollection activeSessions =
507 activeDesc->getAudioSessions(true /*activeOnly*/);
508 for (size_t j = 0; j < activeSessions.size(); j++) {
509 audio_session_t activeSession = activeSessions.keyAt(j);
510 stopInput(activeDesc->mIoHandle, activeSession);
511 releaseInput(activeDesc->mIoHandle, activeSession);
512 }
Eric Laurentc0a889f2015-10-14 14:36:34 -0700513 }
514 }
515
Eric Laurentc2730ba2014-07-20 15:47:07 -0700516 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentdc462862016-07-19 12:29:53 -0700517 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700518 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
519 status);
520 if (status == NO_ERROR) {
François Gaffie98cc1912015-03-18 17:52:40 +0100521 mCallTxPatch = new AudioPatch(&patch, mUidCached);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700522 mCallTxPatch->mAfPatchHandle = afPatchHandle;
523 mCallTxPatch->mUid = mUidCached;
524 }
525 }
Eric Laurentdc462862016-07-19 12:29:53 -0700526
527 return muteWaitMs;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700528}
529
Eric Laurente0720872014-03-11 09:30:41 -0700530void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700531{
532 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100533 // store previous phone state for management of sonification strategy below
534 int oldState = mEngine->getPhoneState();
535
536 if (mEngine->setPhoneState(state) != NO_ERROR) {
537 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700538 return;
539 }
François Gaffie2110e042015-03-24 08:41:51 +0100540 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurente552edb2014-03-10 17:42:56 -0700541 // if leaving call state, handle special case of active streams
542 // pertaining to sonification strategy see handleIncallSonification()
Eric Laurent63dea1d2015-07-02 17:10:28 -0700543 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700544 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800545 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700546 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700547 }
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800548
Eric Laurent63dea1d2015-07-02 17:10:28 -0700549 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800550 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700551 }
552
François Gaffie2110e042015-03-24 08:41:51 +0100553 /**
554 * Switching to or from incall state or switching between telephony and VoIP lead to force
555 * routing command.
556 */
557 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
558 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700559
560 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700561 checkA2dpSuspend();
562 checkOutputForAllStrategies();
563 updateDevicesAndOutputs();
564
Eric Laurente552edb2014-03-10 17:42:56 -0700565 int delayMs = 0;
566 if (isStateInCall(state)) {
567 nsecs_t sysTime = systemTime();
568 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700569 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700570 // mute media and sonification strategies and delay device switch by the largest
571 // latency of any output where either strategy is active.
572 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100573 if ((isStrategyActive(desc, STRATEGY_MEDIA,
574 SONIFICATION_HEADSET_MUSIC_DELAY,
575 sysTime) ||
576 isStrategyActive(desc, STRATEGY_SONIFICATION,
577 SONIFICATION_HEADSET_MUSIC_DELAY,
578 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700579 (delayMs < (int)desc->latency()*2)) {
580 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700581 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700582 setStrategyMute(STRATEGY_MEDIA, true, desc);
583 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700584 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700585 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
586 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700587 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
588 }
589 }
590
Eric Laurent87ffa392015-05-22 10:32:38 -0700591 if (hasPrimaryOutput()) {
592 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
593 // the device returned is not necessarily reachable via this output
594 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
595 // force routing command to audio hardware when ending call
596 // even if no device change is needed
597 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
598 rxDevice = mPrimaryOutput->device();
599 }
Eric Laurente552edb2014-03-10 17:42:56 -0700600
Eric Laurent87ffa392015-05-22 10:32:38 -0700601 if (state == AUDIO_MODE_IN_CALL) {
602 updateCallRouting(rxDevice, delayMs);
603 } else if (oldState == AUDIO_MODE_IN_CALL) {
604 if (mCallRxPatch != 0) {
605 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
606 mCallRxPatch.clear();
607 }
608 if (mCallTxPatch != 0) {
609 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
610 mCallTxPatch.clear();
611 }
612 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
613 } else {
614 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700615 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700616 }
Eric Laurente552edb2014-03-10 17:42:56 -0700617 // if entering in call state, handle special case of active streams
618 // pertaining to sonification strategy see handleIncallSonification()
619 if (isStateInCall(state)) {
620 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800621 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700622 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700623 }
Eric Laurent63dea1d2015-07-02 17:10:28 -0700624
625 // force reevaluating accessibility routing when call starts
626 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700627 }
628
629 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700630 if (state == AUDIO_MODE_RINGTONE &&
631 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700632 mLimitRingtoneVolume = true;
633 } else {
634 mLimitRingtoneVolume = false;
635 }
636}
637
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700638audio_mode_t AudioPolicyManager::getPhoneState() {
639 return mEngine->getPhoneState();
640}
641
Eric Laurente0720872014-03-11 09:30:41 -0700642void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700643 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700644{
François Gaffie2110e042015-03-24 08:41:51 +0100645 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700646 if (config == mEngine->getForceUse(usage)) {
647 return;
648 }
Eric Laurente552edb2014-03-10 17:42:56 -0700649
François Gaffie2110e042015-03-24 08:41:51 +0100650 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
651 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
652 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700653 }
François Gaffie2110e042015-03-24 08:41:51 +0100654 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
655 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
656 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700657
658 // check for device and output changes triggered by new force usage
659 checkA2dpSuspend();
660 checkOutputForAllStrategies();
661 updateDevicesAndOutputs();
Phil Burk09bc4612016-02-24 15:58:15 -0800662
Eric Laurentdc462862016-07-19 12:29:53 -0700663 //FIXME: workaround for truncated touch sounds
664 // to be removed when the problem is handled by system UI
665 uint32_t delayMs = 0;
666 uint32_t waitMs = 0;
667 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
668 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
669 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700670 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700671 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
Eric Laurentdc462862016-07-19 12:29:53 -0700672 waitMs = updateCallRouting(newDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700673 }
Eric Laurente552edb2014-03-10 17:42:56 -0700674 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700675 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
676 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
677 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700678 waitMs = setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE),
679 delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700680 }
Eric Laurente552edb2014-03-10 17:42:56 -0700681 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700682 applyStreamVolumes(outputDesc, newDevice, waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700683 }
684 }
685
Eric Laurentfb66dd92016-01-28 18:32:03 -0800686 Vector<sp <AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
687 for (size_t i = 0; i < activeInputs.size(); i++) {
688 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
689 audio_devices_t newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700690 // Force new input selection if the new device can not be reached via current input
Eric Laurentfb66dd92016-01-28 18:32:03 -0800691 if (activeDesc->mProfile->getSupportedDevices().types() &
692 (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
693 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700694 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800695 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700696 }
Eric Laurente552edb2014-03-10 17:42:56 -0700697 }
Eric Laurente552edb2014-03-10 17:42:56 -0700698}
699
Eric Laurente0720872014-03-11 09:30:41 -0700700void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700701{
702 ALOGV("setSystemProperty() property %s, value %s", property, value);
703}
704
705// Find a direct output profile compatible with the parameters passed, even if the input flags do
706// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800707sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700708 audio_devices_t device,
709 uint32_t samplingRate,
710 audio_format_t format,
711 audio_channel_mask_t channelMask,
712 audio_output_flags_t flags)
713{
Eric Laurent861a6282015-05-18 15:40:16 -0700714 // only retain flags that will drive the direct output profile selection
715 // if explicitly requested
716 static const uint32_t kRelevantFlags =
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700717 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
718 AUDIO_OUTPUT_FLAG_VOIP_RX);
Eric Laurent861a6282015-05-18 15:40:16 -0700719 flags =
720 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
721
722 sp<IOProfile> profile;
723
Eric Laurente552edb2014-03-10 17:42:56 -0700724 for (size_t i = 0; i < mHwModules.size(); i++) {
725 if (mHwModules[i]->mHandle == 0) {
726 continue;
727 }
728 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent861a6282015-05-18 15:40:16 -0700729 sp<IOProfile> curProfile = mHwModules[i]->mOutputProfiles[j];
730 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700731 samplingRate, NULL /*updatedSamplingRate*/,
732 format, NULL /*updatedFormat*/,
733 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700734 flags)) {
735 continue;
736 }
737 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100738 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700739 continue;
740 }
741 // if several profiles are compatible, give priority to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100742 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700743 continue;
744 }
745 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100746 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700747 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700748 }
Eric Laurente552edb2014-03-10 17:42:56 -0700749 }
750 }
Eric Laurent861a6282015-05-18 15:40:16 -0700751 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700752}
753
Eric Laurente0720872014-03-11 09:30:41 -0700754audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +0100755 uint32_t samplingRate,
756 audio_format_t format,
757 audio_channel_mask_t channelMask,
758 audio_output_flags_t flags,
759 const audio_offload_info_t *offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -0700760{
Eric Laurent3b73df72014-03-11 09:06:29 -0700761 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700762 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
763 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
764 device, stream, samplingRate, format, channelMask, flags);
765
Kevin Rocard169753c2017-03-06 14:18:23 -0800766 return getOutputForDevice(device, AUDIO_SESSION_ALLOCATE, stream, samplingRate, format,
767 channelMask, flags, offloadInfo);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700768}
769
Eric Laurente83b55d2014-11-14 10:06:21 -0800770status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
771 audio_io_handle_t *output,
772 audio_session_t session,
773 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700774 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800775 const audio_config_t *config,
Eric Laurente83b55d2014-11-14 10:06:21 -0800776 audio_output_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700777 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800778 audio_port_handle_t *portId)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700779{
Eric Laurente83b55d2014-11-14 10:06:21 -0800780 audio_attributes_t attributes;
781 if (attr != NULL) {
782 if (!isValidAttributes(attr)) {
783 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
784 attr->usage, attr->content_type, attr->flags,
785 attr->tags);
786 return BAD_VALUE;
787 }
788 attributes = *attr;
789 } else {
790 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
791 ALOGE("getOutputForAttr(): invalid stream type");
792 return BAD_VALUE;
793 }
794 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700795 }
Eric Laurent20b9ef02016-12-05 11:03:16 -0800796
797 // TODO: check for existing client for this port ID
798 if (*portId == AUDIO_PORT_HANDLE_NONE) {
799 *portId = AudioPort::getNextUniqueId();
800 }
801
Eric Laurentc75307b2015-03-17 15:29:32 -0700802 sp<SwAudioOutputDescriptor> desc;
Jean-Michel Trivie8deced2016-02-11 12:50:39 -0800803 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
François Gaffie036e1e92015-03-19 10:16:24 +0100804 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
Eric Laurent20b9ef02016-12-05 11:03:16 -0800805 if (!audio_has_proportional_frames(config->format)) {
François Gaffie036e1e92015-03-19 10:16:24 +0100806 return BAD_VALUE;
Eric Laurent275e8e92014-11-30 15:14:47 -0800807 }
François Gaffie036e1e92015-03-19 10:16:24 +0100808 *stream = streamTypefromAttributesInt(&attributes);
809 *output = desc->mIoHandle;
810 ALOGV("getOutputForAttr() returns output %d", *output);
811 return NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -0800812 }
813 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
814 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
815 return BAD_VALUE;
816 }
817
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700818 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
819 " session %d selectedDeviceId %d",
820 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700821 session, *selectedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700822
823 *stream = streamTypefromAttributesInt(&attributes);
824
825 // Explicit routing?
826 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -0700827 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
828 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
829 if (mAvailableOutputDevices[i]->getId() == *selectedDeviceId) {
830 deviceDesc = mAvailableOutputDevices[i];
831 break;
832 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700833 }
834 }
835 mOutputRoutes.addRoute(session, *stream, SessionRoute::SOURCE_TYPE_NA, deviceDesc, uid);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700836
Eric Laurente83b55d2014-11-14 10:06:21 -0800837 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700838 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700839
Eric Laurente83b55d2014-11-14 10:06:21 -0800840 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Eric Laurent93c3d412014-08-01 14:48:35 -0700841 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
842 }
843
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700844 ALOGV("getOutputForAttr() device 0x%x, samplingRate %d, format %x, channelMask %x, flags %x",
Eric Laurent20b9ef02016-12-05 11:03:16 -0800845 device, config->sample_rate, config->format, config->channel_mask, flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700846
Kevin Rocard169753c2017-03-06 14:18:23 -0800847 *output = getOutputForDevice(device, session, *stream,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800848 config->sample_rate, config->format, config->channel_mask,
849 flags, &config->offload_info);
Eric Laurente83b55d2014-11-14 10:06:21 -0800850 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700851 mOutputRoutes.removeRoute(session);
Eric Laurente83b55d2014-11-14 10:06:21 -0800852 return INVALID_OPERATION;
853 }
Paul McLeanaa981192015-03-21 09:55:15 -0700854
Eric Laurent2ac76942017-06-22 17:17:09 -0700855 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromType(device);
856 *selectedDeviceId = outputDevices.size() > 0 ? outputDevices.itemAt(0)->getId()
857 : AUDIO_PORT_HANDLE_NONE;
858
859 ALOGV(" getOutputForAttr() returns output %d selectedDeviceId %d", *output, *selectedDeviceId);
860
Eric Laurente83b55d2014-11-14 10:06:21 -0800861 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700862}
863
864audio_io_handle_t AudioPolicyManager::getOutputForDevice(
865 audio_devices_t device,
Kevin Rocard169753c2017-03-06 14:18:23 -0800866 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700867 audio_stream_type_t stream,
868 uint32_t samplingRate,
869 audio_format_t format,
870 audio_channel_mask_t channelMask,
871 audio_output_flags_t flags,
872 const audio_offload_info_t *offloadInfo)
873{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700874 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700875 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700876
Eric Laurente552edb2014-03-10 17:42:56 -0700877#ifdef AUDIO_POLICY_TEST
878 if (mCurOutput != 0) {
879 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
880 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
881
882 if (mTestOutputs[mCurOutput] == 0) {
883 ALOGV("getOutput() opening test output");
Eric Laurentc75307b2015-03-17 15:29:32 -0700884 sp<AudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(NULL,
885 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -0700886 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700887 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700888 outputDesc->mFlags =
889 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700890 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700891 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
892 config.sample_rate = mTestSamplingRate;
893 config.channel_mask = mTestChannels;
894 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700895 if (offloadInfo != NULL) {
896 config.offload_info = *offloadInfo;
897 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700898 status = mpClientInterface->openOutput(0,
899 &mTestOutputs[mCurOutput],
900 &config,
901 &outputDesc->mDevice,
902 String8(""),
903 &outputDesc->mLatency,
904 outputDesc->mFlags);
905 if (status == NO_ERROR) {
906 outputDesc->mSamplingRate = config.sample_rate;
907 outputDesc->mFormat = config.format;
908 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700909 AudioParameter outputCmd = AudioParameter();
910 outputCmd.addInt(String8("set_id"),mCurOutput);
911 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
912 addOutput(mTestOutputs[mCurOutput], outputDesc);
913 }
914 }
915 return mTestOutputs[mCurOutput];
916 }
917#endif //AUDIO_POLICY_TEST
918
919 // open a direct output if required by specified parameters
920 //force direct flag if offload flag is set: offloading implies a direct output stream
921 // and all common behaviors are driven by checking only the direct flag
922 // this should normally be set appropriately in the policy configuration file
923 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700924 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700925 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700926 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
927 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
928 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800929 // only allow deep buffering for music stream type
930 if (stream != AUDIO_STREAM_MUSIC) {
931 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700932 } else if (/* stream == AUDIO_STREAM_MUSIC && */
933 flags == AUDIO_OUTPUT_FLAG_NONE &&
934 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
935 // use DEEP_BUFFER as default output for music stream type
936 flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800937 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700938 if (stream == AUDIO_STREAM_TTS) {
939 flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700940 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700941 audio_is_linear_pcm(format)) {
942 flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
943 AUDIO_OUTPUT_FLAG_DIRECT);
944 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700945 }
Eric Laurente552edb2014-03-10 17:42:56 -0700946
Eric Laurentb732cf52014-09-24 19:08:21 -0700947 sp<IOProfile> profile;
948
949 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700950 // and not explicitly requested
951 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Glenn Kasten05ddca52016-02-11 08:17:12 -0800952 audio_is_linear_pcm(format) && samplingRate <= SAMPLE_RATE_HZ_MAX &&
Eric Laurentb732cf52014-09-24 19:08:21 -0700953 audio_channel_count_from_out_mask(channelMask) <= 2) {
954 goto non_direct_output;
955 }
956
Andy Hung2ddee192015-12-18 17:34:44 -0800957 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
958 // This prevents creating an offloaded track and tearing it down immediately after start
959 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700960 // FIXME: We should check the audio session here but we do not have it in this context.
961 // This may prevent offloading in rare situations where effects are left active by apps
962 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700963
Eric Laurente552edb2014-03-10 17:42:56 -0700964 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800965 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700966 profile = getProfileForDirectOutput(device,
967 samplingRate,
968 format,
969 channelMask,
970 (audio_output_flags_t)flags);
971 }
972
Eric Laurent1c333e22014-05-20 10:48:17 -0700973 if (profile != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700974 sp<SwAudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700975
976 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700977 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700978 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
979 outputDesc = desc;
Kevin Rocard551061a2017-02-06 15:59:29 -0800980 // reuse direct output if currently open by the same client
981 // and configured with same parameters
Eric Laurente552edb2014-03-10 17:42:56 -0700982 if ((samplingRate == outputDesc->mSamplingRate) &&
Kevin Rocard551061a2017-02-06 15:59:29 -0800983 audio_formats_match(format, outputDesc->mFormat) &&
984 (channelMask == outputDesc->mChannelMask)) {
Kevin Rocard169753c2017-03-06 14:18:23 -0800985 if (session == outputDesc->mDirectClientSession) {
Kevin Rocard551061a2017-02-06 15:59:29 -0800986 outputDesc->mDirectOpenCount++;
Kevin Rocard169753c2017-03-06 14:18:23 -0800987 ALOGV("getOutput() reusing direct output %d for session %d",
988 mOutputs.keyAt(i), session);
Kevin Rocard551061a2017-02-06 15:59:29 -0800989 return mOutputs.keyAt(i);
990 } else {
Kevin Rocard169753c2017-03-06 14:18:23 -0800991 ALOGV("getOutput() do not reuse direct output because current client (%d) "
992 "is not the same as requesting client (%d)",
993 outputDesc->mDirectClientSession, session);
Kevin Rocard551061a2017-02-06 15:59:29 -0800994 goto non_direct_output;
995 }
Eric Laurente552edb2014-03-10 17:42:56 -0700996 }
997 }
998 }
999 // close direct output if currently open and configured with different parameters
1000 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07001001 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001002 }
Eric Laurent861a6282015-05-18 15:40:16 -07001003
1004 // if the selected profile is offloaded and no offload info was specified,
1005 // create a default one
1006 audio_offload_info_t defaultOffloadInfo = AUDIO_INFO_INITIALIZER;
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001007 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) && !offloadInfo) {
Eric Laurent861a6282015-05-18 15:40:16 -07001008 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
1009 defaultOffloadInfo.sample_rate = samplingRate;
1010 defaultOffloadInfo.channel_mask = channelMask;
1011 defaultOffloadInfo.format = format;
1012 defaultOffloadInfo.stream_type = stream;
1013 defaultOffloadInfo.bit_rate = 0;
1014 defaultOffloadInfo.duration_us = -1;
1015 defaultOffloadInfo.has_video = true; // conservative
1016 defaultOffloadInfo.is_streaming = true; // likely
1017 offloadInfo = &defaultOffloadInfo;
1018 }
1019
Eric Laurentc75307b2015-03-17 15:29:32 -07001020 outputDesc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07001021 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -07001022 outputDesc->mLatency = 0;
Eric Laurent861a6282015-05-18 15:40:16 -07001023 outputDesc->mFlags = (audio_output_flags_t)(outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001024 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1025 config.sample_rate = samplingRate;
1026 config.channel_mask = channelMask;
1027 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -07001028 if (offloadInfo != NULL) {
1029 config.offload_info = *offloadInfo;
1030 }
Eric Laurente3014102017-05-03 11:15:43 -07001031 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromType(device);
1032 String8 address = outputDevices.size() > 0 ? outputDevices.itemAt(0)->mAddress
1033 : String8("");
Eric Laurent322b4d22015-04-03 15:57:54 -07001034 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07001035 &output,
1036 &config,
1037 &outputDesc->mDevice,
Eric Laurente3014102017-05-03 11:15:43 -07001038 address,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001039 &outputDesc->mLatency,
1040 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001041
1042 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001043 if (status != NO_ERROR ||
1044 (samplingRate != 0 && samplingRate != config.sample_rate) ||
Eric Laurente6930022016-02-11 10:20:40 -08001045 (format != AUDIO_FORMAT_DEFAULT && !audio_formats_match(format, config.format)) ||
Eric Laurentcf2c0212014-07-25 16:20:43 -07001046 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001047 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
1048 "format %d %d, channelMask %04x %04x", output, samplingRate,
1049 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
1050 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001051 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001052 mpClientInterface->closeOutput(output);
1053 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001054 // fall back to mixer output if possible when the direct output could not be open
Glenn Kasten05ddca52016-02-11 08:17:12 -08001055 if (audio_is_linear_pcm(format) && samplingRate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -08001056 goto non_direct_output;
1057 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001058 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001059 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001060 outputDesc->mSamplingRate = config.sample_rate;
1061 outputDesc->mChannelMask = config.channel_mask;
1062 outputDesc->mFormat = config.format;
1063 outputDesc->mRefCount[stream] = 0;
1064 outputDesc->mStopTime[stream] = 0;
1065 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -08001066 outputDesc->mDirectClientSession = session;
1067
Eric Laurente552edb2014-03-10 17:42:56 -07001068 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001069 mPreviousOutputs = mOutputs;
1070 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001071 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001072 return output;
1073 }
1074
Eric Laurentb732cf52014-09-24 19:08:21 -07001075non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001076
1077 // A request for HW A/V sync cannot fallback to a mixed output because time
1078 // stamps are embedded in audio data
1079 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1080 return AUDIO_IO_HANDLE_NONE;
1081 }
1082
Eric Laurente552edb2014-03-10 17:42:56 -07001083 // ignoring channel mask due to downmix capability in mixer
1084
1085 // open a non direct output
1086
1087 // for non direct outputs, only PCM is supported
1088 if (audio_is_linear_pcm(format)) {
1089 // get which output is suitable for the specified stream. The actual
1090 // routing change will happen when startOutput() will be called
1091 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1092
Eric Laurent8838a382014-09-08 16:44:28 -07001093 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
1094 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1095 output = selectOutput(outputs, flags, format);
Eric Laurente552edb2014-03-10 17:42:56 -07001096 }
1097 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
1098 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
1099
Eric Laurente552edb2014-03-10 17:42:56 -07001100 return output;
1101}
1102
Eric Laurente0720872014-03-11 09:30:41 -07001103audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001104 audio_output_flags_t flags,
1105 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001106{
1107 // select one output among several that provide a path to a particular device or set of
1108 // devices (the list was previously build by getOutputsForDevice()).
1109 // The priority is as follows:
1110 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001111 // 2: the output with the bit depth the closest to the requested one
1112 // 3: the primary output
1113 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001114
1115 if (outputs.size() == 0) {
1116 return 0;
1117 }
1118 if (outputs.size() == 1) {
1119 return outputs[0];
1120 }
1121
1122 int maxCommonFlags = 0;
Eric Laurente6930022016-02-11 10:20:40 -08001123 audio_io_handle_t outputForFlags = 0;
1124 audio_io_handle_t outputForPrimary = 0;
1125 audio_io_handle_t outputForFormat = 0;
1126 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1127 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001128
1129 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001130 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001131 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001132 // if a valid format is specified, skip output if not compatible
1133 if (format != AUDIO_FORMAT_INVALID) {
1134 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente6930022016-02-11 10:20:40 -08001135 if (!audio_formats_match(format, outputDesc->mFormat)) {
Eric Laurent8838a382014-09-08 16:44:28 -07001136 continue;
1137 }
1138 } else if (!audio_is_linear_pcm(format)) {
1139 continue;
1140 }
Eric Laurente6930022016-02-11 10:20:40 -08001141 if (AudioPort::isBetterFormatMatch(
1142 outputDesc->mFormat, bestFormat, format)) {
1143 outputForFormat = outputs[i];
1144 bestFormat = outputDesc->mFormat;
1145 }
Eric Laurent8838a382014-09-08 16:44:28 -07001146 }
1147
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001148 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001149 if (commonFlags >= maxCommonFlags) {
1150 if (commonFlags == maxCommonFlags) {
1151 if (AudioPort::isBetterFormatMatch(
1152 outputDesc->mFormat, bestFormatForFlags, format)) {
1153 outputForFlags = outputs[i];
1154 bestFormatForFlags = outputDesc->mFormat;
1155 }
1156 } else {
1157 outputForFlags = outputs[i];
1158 maxCommonFlags = commonFlags;
1159 bestFormatForFlags = outputDesc->mFormat;
1160 }
Eric Laurente552edb2014-03-10 17:42:56 -07001161 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1162 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001163 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurente6930022016-02-11 10:20:40 -08001164 outputForPrimary = outputs[i];
Eric Laurente552edb2014-03-10 17:42:56 -07001165 }
1166 }
1167 }
1168
Eric Laurente6930022016-02-11 10:20:40 -08001169 if (outputForFlags != 0) {
1170 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001171 }
Eric Laurente6930022016-02-11 10:20:40 -08001172 if (outputForFormat != 0) {
1173 return outputForFormat;
1174 }
1175 if (outputForPrimary != 0) {
1176 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001177 }
1178
1179 return outputs[0];
1180}
1181
Eric Laurente0720872014-03-11 09:30:41 -07001182status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001183 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001184 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001185{
Paul McLeanaa981192015-03-21 09:55:15 -07001186 ALOGV("startOutput() output %d, stream %d, session %d",
1187 output, stream, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001188 ssize_t index = mOutputs.indexOfKey(output);
1189 if (index < 0) {
1190 ALOGW("startOutput() unknown output %d", output);
1191 return BAD_VALUE;
1192 }
1193
Eric Laurentc75307b2015-03-17 15:29:32 -07001194 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1195
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001196 // Routing?
1197 mOutputRoutes.incRouteActivity(session);
1198
Eric Laurentc75307b2015-03-17 15:29:32 -07001199 audio_devices_t newDevice;
Eric Laurentc40d9692016-04-13 19:14:13 -07001200 AudioMix *policyMix = NULL;
1201 const char *address = NULL;
Eric Laurentc75307b2015-03-17 15:29:32 -07001202 if (outputDesc->mPolicyMix != NULL) {
Eric Laurentc40d9692016-04-13 19:14:13 -07001203 policyMix = outputDesc->mPolicyMix;
1204 address = policyMix->mDeviceAddress.string();
1205 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1206 newDevice = policyMix->mDeviceType;
1207 } else {
1208 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1209 }
Eric Laurent493404d2015-04-21 15:07:36 -07001210 } else if (mOutputRoutes.hasRouteChanged(session)) {
1211 newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001212 checkStrategyRoute(getStrategy(stream), output);
Eric Laurentc75307b2015-03-17 15:29:32 -07001213 } else {
1214 newDevice = AUDIO_DEVICE_NONE;
1215 }
1216
1217 uint32_t delayMs = 0;
1218
Eric Laurentc40d9692016-04-13 19:14:13 -07001219 status_t status = startSource(outputDesc, stream, newDevice, address, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001220
1221 if (status != NO_ERROR) {
1222 mOutputRoutes.decRouteActivity(session);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001223 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001224 }
1225 // Automatically enable the remote submix input when output is started on a re routing mix
1226 // of type MIX_TYPE_RECORDERS
Eric Laurentc40d9692016-04-13 19:14:13 -07001227 if (audio_is_remote_submix_device(newDevice) && policyMix != NULL &&
1228 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001229 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1230 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Eric Laurentc40d9692016-04-13 19:14:13 -07001231 address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001232 "remote-submix");
1233 }
1234
1235 if (delayMs != 0) {
1236 usleep(delayMs * 1000);
1237 }
1238
1239 return status;
1240}
1241
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001242status_t AudioPolicyManager::startSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurentc75307b2015-03-17 15:29:32 -07001243 audio_stream_type_t stream,
1244 audio_devices_t device,
Eric Laurentc40d9692016-04-13 19:14:13 -07001245 const char *address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001246 uint32_t *delayMs)
1247{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001248 // cannot start playback of STREAM_TTS if any other output is being used
1249 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001250
1251 *delayMs = 0;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001252 if (stream == AUDIO_STREAM_TTS) {
1253 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001254 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001255 return INVALID_OPERATION;
1256 } else {
1257 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1258 }
1259 } else {
1260 // some playback other than beacon starts
1261 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1262 }
1263
Eric Laurent77305a62016-07-25 16:39:22 -07001264 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001265 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001266 bool force = !outputDesc->isActive() &&
1267 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001268
Eric Laurente552edb2014-03-10 17:42:56 -07001269 // increment usage count for this stream on the requested output:
1270 // NOTE that the usage count is the same for duplicated output and hardware output which is
1271 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1272 outputDesc->changeRefCount(stream, 1);
1273
Eric Laurent36829f92017-04-07 19:04:42 -07001274 if (stream == AUDIO_STREAM_MUSIC) {
1275 selectOutputForMusicEffects();
1276 }
1277
Eric Laurent493404d2015-04-21 15:07:36 -07001278 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001279 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001280 if (device == AUDIO_DEVICE_NONE) {
1281 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001282 }
Eric Laurent36829f92017-04-07 19:04:42 -07001283
Eric Laurente552edb2014-03-10 17:42:56 -07001284 routing_strategy strategy = getStrategy(stream);
1285 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001286 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1287 (beaconMuteLatency > 0);
1288 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001289 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001290 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001291 if (desc != outputDesc) {
Eric Laurent77305a62016-07-25 16:39:22 -07001292 // force a device change if any other output is:
1293 // - managed by the same hw module
1294 // - has a current device selection that differs from selected device.
1295 // - supports currently selected device
1296 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001297 // In this case, the audio HAL must receive the new device selection so that it can
1298 // change the device currently selected by the other active output.
1299 if (outputDesc->sharesHwModuleWith(desc) &&
Eric Laurent77305a62016-07-25 16:39:22 -07001300 desc->device() != device &&
1301 desc->supportedDevices() & device &&
1302 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001303 force = true;
1304 }
1305 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001306 // a notification so that audio focus effect can propagate, or that a mute/unmute
1307 // event occurred for beacon
Eric Laurente552edb2014-03-10 17:42:56 -07001308 uint32_t latency = desc->latency();
1309 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1310 waitMs = latency;
1311 }
1312 }
1313 }
Eric Laurentdc462862016-07-19 12:29:53 -07001314 uint32_t muteWaitMs = setOutputDevice(outputDesc, device, force, 0, NULL, address);
Eric Laurente552edb2014-03-10 17:42:56 -07001315
1316 // handle special case for sonification while in call
1317 if (isInCall()) {
1318 handleIncallSonification(stream, true, false);
1319 }
1320
1321 // apply volume rules for current stream and device if necessary
1322 checkAndSetVolume(stream,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001323 mVolumeCurves->getVolumeIndex(stream, outputDesc->device()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001324 outputDesc,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001325 outputDesc->device());
Eric Laurente552edb2014-03-10 17:42:56 -07001326
1327 // update the outputs if starting an output with a stream that can affect notification
1328 // routing
1329 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001330
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001331 // force reevaluating accessibility routing when ringtone or alarm starts
1332 if (strategy == STRATEGY_SONIFICATION) {
1333 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1334 }
Eric Laurentdc462862016-07-19 12:29:53 -07001335
1336 if (waitMs > muteWaitMs) {
1337 *delayMs = waitMs - muteWaitMs;
1338 }
Eric Laurente552edb2014-03-10 17:42:56 -07001339 }
Eric Laurentdc462862016-07-19 12:29:53 -07001340
Eric Laurente552edb2014-03-10 17:42:56 -07001341 return NO_ERROR;
1342}
1343
1344
Eric Laurente0720872014-03-11 09:30:41 -07001345status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001346 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001347 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001348{
1349 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1350 ssize_t index = mOutputs.indexOfKey(output);
1351 if (index < 0) {
1352 ALOGW("stopOutput() unknown output %d", output);
1353 return BAD_VALUE;
1354 }
1355
Eric Laurentc75307b2015-03-17 15:29:32 -07001356 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001357
Eric Laurentc75307b2015-03-17 15:29:32 -07001358 if (outputDesc->mRefCount[stream] == 1) {
1359 // Automatically disable the remote submix input when output is stopped on a
1360 // re routing mix of type MIX_TYPE_RECORDERS
1361 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1362 outputDesc->mPolicyMix != NULL &&
1363 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1364 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1365 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001366 outputDesc->mPolicyMix->mDeviceAddress,
Eric Laurentc75307b2015-03-17 15:29:32 -07001367 "remote-submix");
1368 }
1369 }
1370
1371 // Routing?
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001372 bool forceDeviceUpdate = false;
Eric Laurentc75307b2015-03-17 15:29:32 -07001373 if (outputDesc->mRefCount[stream] > 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001374 int activityCount = mOutputRoutes.decRouteActivity(session);
1375 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1376
1377 if (forceDeviceUpdate) {
1378 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1379 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001380 }
1381
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001382 return stopSource(outputDesc, stream, forceDeviceUpdate);
Eric Laurentc75307b2015-03-17 15:29:32 -07001383}
1384
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001385status_t AudioPolicyManager::stopSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001386 audio_stream_type_t stream,
1387 bool forceDeviceUpdate)
Eric Laurentc75307b2015-03-17 15:29:32 -07001388{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001389 // always handle stream stop, check which stream type is stopping
1390 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1391
Eric Laurente552edb2014-03-10 17:42:56 -07001392 // handle special case for sonification while in call
1393 if (isInCall()) {
1394 handleIncallSonification(stream, false, false);
1395 }
1396
1397 if (outputDesc->mRefCount[stream] > 0) {
1398 // decrement usage count of this stream on the output
1399 outputDesc->changeRefCount(stream, -1);
Paul McLeanaa981192015-03-21 09:55:15 -07001400
Eric Laurente552edb2014-03-10 17:42:56 -07001401 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001402 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001403 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001404 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001405 // delay the device switch by twice the latency because stopOutput() is executed when
1406 // the track stop() command is received and at that time the audio track buffer can
1407 // still contain data that needs to be drained. The latency only covers the audio HAL
1408 // and kernel buffers. Also the latency does not always include additional delay in the
1409 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001410 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001411
1412 // force restoring the device selection on other active outputs if it differs from the
1413 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001414 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001415 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001416 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001417 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001418 desc->isActive() &&
1419 outputDesc->sharesHwModuleWith(desc) &&
1420 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001421 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1422 bool force = desc->device() != newDevice2;
Eric Laurentc75307b2015-03-17 15:29:32 -07001423 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001424 newDevice2,
1425 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001426 delayMs);
1427 // re-apply device specific volume if not done by setOutputDevice()
1428 if (!force) {
1429 applyStreamVolumes(desc, newDevice2, delayMs);
1430 }
Eric Laurente552edb2014-03-10 17:42:56 -07001431 }
1432 }
1433 // update the outputs if stopping one with a stream that can affect notification routing
1434 handleNotificationRoutingForStream(stream);
1435 }
Eric Laurent36829f92017-04-07 19:04:42 -07001436 if (stream == AUDIO_STREAM_MUSIC) {
1437 selectOutputForMusicEffects();
1438 }
Eric Laurente552edb2014-03-10 17:42:56 -07001439 return NO_ERROR;
1440 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001441 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001442 return INVALID_OPERATION;
1443 }
1444}
1445
Eric Laurente83b55d2014-11-14 10:06:21 -08001446void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001447 audio_stream_type_t stream __unused,
1448 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001449{
1450 ALOGV("releaseOutput() %d", output);
1451 ssize_t index = mOutputs.indexOfKey(output);
1452 if (index < 0) {
1453 ALOGW("releaseOutput() releasing unknown output %d", output);
1454 return;
1455 }
1456
1457#ifdef AUDIO_POLICY_TEST
1458 int testIndex = testOutputIndex(output);
1459 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001460 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001461 if (outputDesc->isActive()) {
1462 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01001463 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001464 mTestOutputs[testIndex] = 0;
1465 }
1466 return;
1467 }
1468#endif //AUDIO_POLICY_TEST
1469
Paul McLeanaa981192015-03-21 09:55:15 -07001470 // Routing
1471 mOutputRoutes.removeRoute(session);
1472
Eric Laurentc75307b2015-03-17 15:29:32 -07001473 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001474 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001475 if (desc->mDirectOpenCount <= 0) {
1476 ALOGW("releaseOutput() invalid open count %d for output %d",
1477 desc->mDirectOpenCount, output);
1478 return;
1479 }
1480 if (--desc->mDirectOpenCount == 0) {
1481 closeOutput(output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001482 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001483 }
1484 }
1485}
1486
1487
Eric Laurentcaf7f482014-11-25 17:50:47 -08001488status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1489 audio_io_handle_t *input,
1490 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001491 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001492 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001493 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001494 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001495 input_type_t *inputType,
1496 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001497{
Eric Laurentcaf7f482014-11-25 17:50:47 -08001498 ALOGV("getInputForAttr() source %d, samplingRate %d, format %d, channelMask %x,"
1499 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001500 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001501
Eric Laurentad2e7b92017-09-14 20:06:42 -07001502 status_t status = NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -08001503 // handle legacy remote submix case where the address was not always specified
1504 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001505 audio_source_t halInputSource;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001506 audio_source_t inputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001507 AudioMix *policyMix = NULL;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001508 DeviceVector inputDevices;
Eric Laurent20b9ef02016-12-05 11:03:16 -08001509
Paul McLean466dc8e2015-04-17 13:15:36 -06001510 // Explicit routing?
1511 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -07001512 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
1513 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
1514 if (mAvailableInputDevices[i]->getId() == *selectedDeviceId) {
1515 deviceDesc = mAvailableInputDevices[i];
1516 break;
1517 }
Paul McLean466dc8e2015-04-17 13:15:36 -06001518 }
1519 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001520 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
Paul McLean466dc8e2015-04-17 13:15:36 -06001521
Eric Laurentad2e7b92017-09-14 20:06:42 -07001522 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1523 // possible
1524 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1525 *input != AUDIO_IO_HANDLE_NONE) {
1526 ssize_t index = mInputs.indexOfKey(*input);
1527 if (index < 0) {
1528 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1529 status = BAD_VALUE;
1530 goto error;
1531 }
1532 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1533 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1534 if (audioSession == 0) {
1535 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1536 status = BAD_VALUE;
1537 goto error;
1538 }
1539 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1540 // The second call is for the first active client and sets the UID. Any further call
1541 // corresponds to a new client and is only permitted from the same UId.
1542 if (audioSession->openCount() == 1) {
1543 audioSession->setUid(uid);
1544 } else if (audioSession->uid() != uid) {
1545 ALOGW("getInputForAttr() bad uid %d for session %d uid %d",
1546 uid, session, audioSession->uid());
1547 status = INVALID_OPERATION;
1548 goto error;
1549 }
1550 audioSession->changeOpenCount(1);
1551 *inputType = API_INPUT_LEGACY;
1552 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1553 *portId = AudioPort::getNextUniqueId();
1554 }
1555 inputDevices = mAvailableInputDevices.getDevicesFromType(inputDesc->mDevice);
1556 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1557 : AUDIO_PORT_HANDLE_NONE;
1558 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
1559
1560 return NO_ERROR;
1561 }
1562
1563 *input = AUDIO_IO_HANDLE_NONE;
1564 *inputType = API_INPUT_INVALID;
1565
1566 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1567 inputSource = AUDIO_SOURCE_MIC;
1568 }
1569 halInputSource = inputSource;
1570
1571 // TODO: check for existing client for this port ID
1572 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1573 *portId = AudioPort::getNextUniqueId();
1574 }
1575
1576 audio_devices_t device;
1577
Eric Laurentc447ded2015-01-06 08:47:05 -08001578 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001579 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001580 status = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
1581 if (status != NO_ERROR) {
1582 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001583 }
1584 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001585 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1586 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001587 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001588 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001589 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001590 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001591 status = BAD_VALUE;
1592 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001593 }
Eric Laurentc722f302014-12-10 11:21:49 -08001594 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001595 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001596 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1597 // there is an external policy, but this input is attached to a mix of recorders,
1598 // meaning it receives audio injected into the framework, so the recorder doesn't
1599 // know about it and is therefore considered "legacy"
1600 *inputType = API_INPUT_LEGACY;
1601 } else {
1602 // recording a mix of players defined by an external policy, we're rerouting for
1603 // an external policy
1604 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1605 }
Eric Laurentc722f302014-12-10 11:21:49 -08001606 } else if (audio_is_remote_submix_device(device)) {
1607 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001608 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001609 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1610 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001611 } else {
1612 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001613 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001614
Eric Laurent599c7582015-12-07 18:05:55 -08001615 }
1616
1617 *input = getInputForDevice(device, address, session, uid, inputSource,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001618 config->sample_rate, config->format, config->channel_mask, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001619 policyMix);
1620 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001621 status = INVALID_OPERATION;
1622 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001623 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001624
Eric Laurentad2e7b92017-09-14 20:06:42 -07001625 inputDevices = mAvailableInputDevices.getDevicesFromType(device);
Eric Laurent2ac76942017-06-22 17:17:09 -07001626 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1627 : AUDIO_PORT_HANDLE_NONE;
1628
1629 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d",
1630 *input, *inputType, *selectedDeviceId);
1631
Eric Laurent599c7582015-12-07 18:05:55 -08001632 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001633
1634error:
1635 mInputRoutes.removeRoute(session);
1636 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001637}
1638
1639
1640audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1641 String8 address,
1642 audio_session_t session,
1643 uid_t uid,
1644 audio_source_t inputSource,
1645 uint32_t samplingRate,
1646 audio_format_t format,
1647 audio_channel_mask_t channelMask,
1648 audio_input_flags_t flags,
1649 AudioMix *policyMix)
1650{
1651 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1652 audio_source_t halInputSource = inputSource;
1653 bool isSoundTrigger = false;
1654
1655 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1656 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1657 if (index >= 0) {
1658 input = mSoundTriggerSessions.valueFor(session);
1659 isSoundTrigger = true;
1660 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1661 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1662 } else {
1663 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001664 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001665 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001666 audio_is_linear_pcm(format)) {
1667 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001668 }
1669
Andy Hungf129b032015-04-07 13:45:50 -07001670 // find a compatible input profile (not necessarily identical in parameters)
1671 sp<IOProfile> profile;
1672 // samplingRate and flags may be updated by getInputProfile
Glenn Kasten05ddca52016-02-11 08:17:12 -08001673 uint32_t profileSamplingRate = (samplingRate == 0) ? SAMPLE_RATE_HZ_DEFAULT : samplingRate;
Andy Hungf129b032015-04-07 13:45:50 -07001674 audio_format_t profileFormat = format;
1675 audio_channel_mask_t profileChannelMask = channelMask;
1676 audio_input_flags_t profileFlags = flags;
1677 for (;;) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001678 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001679 profileSamplingRate, profileFormat, profileChannelMask,
1680 profileFlags);
1681 if (profile != 0) {
1682 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001683 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1684 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001685 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1686 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1687 } else { // fail
Eric Laurent599c7582015-12-07 18:05:55 -08001688 ALOGW("getInputForDevice() could not find profile for device 0x%X,"
1689 "samplingRate %u, format %#x, channelMask 0x%X, flags %#x",
Andy Hungf129b032015-04-07 13:45:50 -07001690 device, samplingRate, format, channelMask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001691 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001692 }
Eric Laurente552edb2014-03-10 17:42:56 -07001693 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001694 // Pick input sampling rate if not specified by client
1695 if (samplingRate == 0) {
1696 samplingRate = profileSamplingRate;
1697 }
Eric Laurente552edb2014-03-10 17:42:56 -07001698
Eric Laurent322b4d22015-04-03 15:57:54 -07001699 if (profile->getModuleHandle() == 0) {
1700 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001701 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001702 }
1703
Eric Laurent599c7582015-12-07 18:05:55 -08001704 sp<AudioSession> audioSession = new AudioSession(session,
1705 inputSource,
1706 format,
1707 samplingRate,
1708 channelMask,
1709 flags,
1710 uid,
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001711 isSoundTrigger,
1712 policyMix, mpClientInterface);
Eric Laurent599c7582015-12-07 18:05:55 -08001713
Eric Laurent74708e72017-04-07 17:13:42 -07001714// FIXME: disable concurrent capture until UI is ready
1715#if 0
Eric Laurent599c7582015-12-07 18:05:55 -08001716 // reuse an open input if possible
Eric Laurent555530a2017-02-07 18:17:24 -08001717 sp<AudioInputDescriptor> reusedInputDesc;
Eric Laurent599c7582015-12-07 18:05:55 -08001718 for (size_t i = 0; i < mInputs.size(); i++) {
1719 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001720 // reuse input if:
1721 // - it shares the same profile
1722 // AND
1723 // - it is not a reroute submix input
1724 // AND
1725 // - it is: not used for sound trigger
1726 // OR
1727 // used for sound trigger and all clients use the same session ID
1728 //
1729 if ((profile == desc->mProfile) &&
1730 (isSoundTrigger == desc->isSoundTrigger()) &&
1731 !is_virtual_input_device(device)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001732
1733 sp<AudioSession> as = desc->getAudioSession(session);
1734 if (as != 0) {
1735 // do not allow unmatching properties on same session
1736 if (as->matches(audioSession)) {
1737 as->changeOpenCount(1);
1738 } else {
1739 ALOGW("getInputForDevice() record with different attributes"
1740 " exists for session %d", session);
Eric Laurent555530a2017-02-07 18:17:24 -08001741 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001742 }
Eric Laurentfb66dd92016-01-28 18:32:03 -08001743 } else if (isSoundTrigger) {
Eric Laurent555530a2017-02-07 18:17:24 -08001744 continue;
Eric Laurentfb66dd92016-01-28 18:32:03 -08001745 }
Eric Laurentbb948092017-01-23 18:33:30 -08001746
Eric Laurent555530a2017-02-07 18:17:24 -08001747 // Reuse the already opened input stream on this profile if:
1748 // - the new capture source is background OR
1749 // - the path requested configurations match OR
1750 // - the new source priority is less than the highest source priority on this input
1751 // If the input stream cannot be reused, close it before opening a new stream
1752 // on the same profile for the new client so that the requested path configuration
1753 // can be selected.
1754 if (!isConcurrentSource(inputSource) &&
Eric Laurentbb948092017-01-23 18:33:30 -08001755 ((desc->mSamplingRate != samplingRate ||
Eric Laurentfb66dd92016-01-28 18:32:03 -08001756 desc->mChannelMask != channelMask ||
Eric Laurente6930022016-02-11 10:20:40 -08001757 !audio_formats_match(desc->mFormat, format)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001758 (source_priority(desc->getHighestPrioritySource(false /*activeOnly*/)) <
Eric Laurentbb948092017-01-23 18:33:30 -08001759 source_priority(inputSource)))) {
Eric Laurent555530a2017-02-07 18:17:24 -08001760 reusedInputDesc = desc;
1761 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001762 } else {
1763 desc->addAudioSession(session, audioSession);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001764 ALOGV("%s: reusing input %d", __FUNCTION__, mInputs.keyAt(i));
1765 return mInputs.keyAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08001766 }
Eric Laurent599c7582015-12-07 18:05:55 -08001767 }
1768 }
Eric Laurent599c7582015-12-07 18:05:55 -08001769
Eric Laurent555530a2017-02-07 18:17:24 -08001770 if (reusedInputDesc != 0) {
1771 AudioSessionCollection sessions = reusedInputDesc->getAudioSessions(false /*activeOnly*/);
1772 for (size_t j = 0; j < sessions.size(); j++) {
1773 audio_session_t currentSession = sessions.keyAt(j);
1774 stopInput(reusedInputDesc->mIoHandle, currentSession);
1775 releaseInput(reusedInputDesc->mIoHandle, currentSession);
1776 }
1777 }
Eric Laurent74708e72017-04-07 17:13:42 -07001778#endif
Eric Laurent555530a2017-02-07 18:17:24 -08001779
Eric Laurentcf2c0212014-07-25 16:20:43 -07001780 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
Andy Hungf129b032015-04-07 13:45:50 -07001781 config.sample_rate = profileSamplingRate;
1782 config.channel_mask = profileChannelMask;
1783 config.format = profileFormat;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001784
Eric Laurente3014102017-05-03 11:15:43 -07001785 if (address == "") {
1786 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(device);
1787 // the inputs vector must be of size 1, but we don't want to crash here
1788 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress : String8("");
1789 }
1790
Eric Laurent322b4d22015-04-03 15:57:54 -07001791 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurent599c7582015-12-07 18:05:55 -08001792 &input,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001793 &config,
1794 &device,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001795 address,
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001796 halInputSource,
Andy Hungf129b032015-04-07 13:45:50 -07001797 profileFlags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001798
1799 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001800 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Andy Hungf129b032015-04-07 13:45:50 -07001801 (profileSamplingRate != config.sample_rate) ||
Eric Laurente6930022016-02-11 10:20:40 -08001802 !audio_formats_match(profileFormat, config.format) ||
Andy Hungf129b032015-04-07 13:45:50 -07001803 (profileChannelMask != config.channel_mask)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001804 ALOGW("getInputForAttr() failed opening input: samplingRate %d"
1805 ", format %d, channelMask %x",
Eric Laurentcf2c0212014-07-25 16:20:43 -07001806 samplingRate, format, channelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001807 if (input != AUDIO_IO_HANDLE_NONE) {
1808 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001809 }
Eric Laurent599c7582015-12-07 18:05:55 -08001810 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001811 }
1812
Eric Laurent1f2f2232014-06-02 12:01:23 -07001813 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Andy Hungf129b032015-04-07 13:45:50 -07001814 inputDesc->mSamplingRate = profileSamplingRate;
1815 inputDesc->mFormat = profileFormat;
1816 inputDesc->mChannelMask = profileChannelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001817 inputDesc->mDevice = device;
Eric Laurentc722f302014-12-10 11:21:49 -08001818 inputDesc->mPolicyMix = policyMix;
Eric Laurent599c7582015-12-07 18:05:55 -08001819 inputDesc->addAudioSession(session, audioSession);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001820
Eric Laurent599c7582015-12-07 18:05:55 -08001821 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001822 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001823
Eric Laurent599c7582015-12-07 18:05:55 -08001824 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001825}
1826
Eric Laurentbb948092017-01-23 18:33:30 -08001827//static
1828bool AudioPolicyManager::isConcurrentSource(audio_source_t source)
1829{
1830 return (source == AUDIO_SOURCE_HOTWORD) ||
1831 (source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
1832 (source == AUDIO_SOURCE_FM_TUNER);
1833}
1834
Eric Laurentfb66dd92016-01-28 18:32:03 -08001835bool AudioPolicyManager::isConcurentCaptureAllowed(const sp<AudioInputDescriptor>& inputDesc,
1836 const sp<AudioSession>& audioSession)
1837{
1838 // Do not allow capture if an active voice call is using a software patch and
1839 // the call TX source device is on the same HW module.
1840 // FIXME: would be better to refine to only inputs whose profile connects to the
1841 // call TX device but this information is not in the audio patch
1842 if (mCallTxPatch != 0 &&
1843 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1844 return false;
1845 }
1846
1847 // starting concurrent capture is enabled if:
1848 // 1) capturing for re-routing
1849 // 2) capturing for HOTWORD source
1850 // 3) capturing for FM TUNER source
1851 // 3) All other active captures are either for re-routing or HOTWORD
1852
1853 if (is_virtual_input_device(inputDesc->mDevice) ||
Eric Laurentbb948092017-01-23 18:33:30 -08001854 isConcurrentSource(audioSession->inputSource())) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001855 return true;
1856 }
1857
1858 Vector< sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
1859 for (size_t i = 0; i < activeInputs.size(); i++) {
1860 sp<AudioInputDescriptor> activeInput = activeInputs[i];
Eric Laurentbb948092017-01-23 18:33:30 -08001861 if (!isConcurrentSource(activeInput->inputSource(true)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001862 !is_virtual_input_device(activeInput->mDevice)) {
1863 return false;
1864 }
1865 }
1866
1867 return true;
1868}
1869
Chris Thornton2b864642017-06-27 21:26:07 -07001870// FIXME: remove when concurrent capture is ready. This is a hack to work around bug b/63083537.
1871bool AudioPolicyManager::soundTriggerSupportsConcurrentCapture() {
1872 if (!mHasComputedSoundTriggerSupportsConcurrentCapture) {
1873 bool soundTriggerSupportsConcurrentCapture = false;
1874 unsigned int numModules = 0;
1875 struct sound_trigger_module_descriptor* nModules = NULL;
1876
1877 status_t status = SoundTrigger::listModules(nModules, &numModules);
1878 if (status == NO_ERROR && numModules != 0) {
1879 nModules = (struct sound_trigger_module_descriptor*) calloc(
1880 numModules, sizeof(struct sound_trigger_module_descriptor));
1881 if (nModules == NULL) {
1882 // We failed to malloc the buffer, so just say no for now, and hope that we have more
1883 // ram the next time this function is called.
1884 ALOGE("Failed to allocate buffer for module descriptors");
1885 return false;
1886 }
1887
1888 status = SoundTrigger::listModules(nModules, &numModules);
1889 if (status == NO_ERROR) {
1890 soundTriggerSupportsConcurrentCapture = true;
1891 for (size_t i = 0; i < numModules; ++i) {
1892 soundTriggerSupportsConcurrentCapture &=
1893 nModules[i].properties.concurrent_capture;
1894 }
1895 }
1896 free(nModules);
1897 }
1898 mSoundTriggerSupportsConcurrentCapture = soundTriggerSupportsConcurrentCapture;
1899 mHasComputedSoundTriggerSupportsConcurrentCapture = true;
1900 }
1901 return mSoundTriggerSupportsConcurrentCapture;
1902}
1903
Eric Laurentfb66dd92016-01-28 18:32:03 -08001904
Eric Laurent4dc68062014-07-28 17:26:49 -07001905status_t AudioPolicyManager::startInput(audio_io_handle_t input,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001906 audio_session_t session,
1907 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07001908{
1909 ALOGV("startInput() input %d", input);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001910 *concurrency = API_INPUT_CONCURRENCY_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001911 ssize_t index = mInputs.indexOfKey(input);
1912 if (index < 0) {
1913 ALOGW("startInput() unknown input %d", input);
1914 return BAD_VALUE;
1915 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001916 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001917
Eric Laurent599c7582015-12-07 18:05:55 -08001918 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1919 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07001920 ALOGW("startInput() unknown session %d on input %d", session, input);
1921 return BAD_VALUE;
1922 }
1923
Eric Laurent74708e72017-04-07 17:13:42 -07001924// FIXME: disable concurrent capture until UI is ready
1925#if 0
Eric Laurentfb66dd92016-01-28 18:32:03 -08001926 if (!isConcurentCaptureAllowed(inputDesc, audioSession)) {
1927 ALOGW("startInput(%d) failed: other input already started", input);
1928 return INVALID_OPERATION;
1929 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001930
Eric Laurentfb66dd92016-01-28 18:32:03 -08001931 if (isInCall()) {
1932 *concurrency |= API_INPUT_CONCURRENCY_CALL;
1933 }
Eric Laurentf7c50102016-09-30 15:19:43 -07001934 if (mInputs.activeInputsCountOnDevices() != 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001935 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurente552edb2014-03-10 17:42:56 -07001936 }
Eric Laurent74708e72017-04-07 17:13:42 -07001937#else
1938 if (!is_virtual_input_device(inputDesc->mDevice)) {
1939 if (mCallTxPatch != 0 &&
1940 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1941 ALOGW("startInput(%d) failed: call in progress", input);
1942 return INVALID_OPERATION;
1943 }
1944
1945 Vector< sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
1946 for (size_t i = 0; i < activeInputs.size(); i++) {
1947 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
1948
1949 if (is_virtual_input_device(activeDesc->mDevice)) {
1950 continue;
1951 }
1952
Eric Laurentcb4dae22017-07-01 19:39:32 -07001953 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
1954 activeDesc->getId() == inputDesc->getId()) {
1955 continue;
1956 }
1957
Eric Laurent74708e72017-04-07 17:13:42 -07001958 audio_source_t activeSource = activeDesc->inputSource(true);
1959 if (audioSession->inputSource() == AUDIO_SOURCE_HOTWORD) {
1960 if (activeSource == AUDIO_SOURCE_HOTWORD) {
1961 if (activeDesc->hasPreemptedSession(session)) {
1962 ALOGW("startInput(%d) failed for HOTWORD: "
1963 "other input %d already started for HOTWORD",
1964 input, activeDesc->mIoHandle);
1965 return INVALID_OPERATION;
1966 }
1967 } else {
1968 ALOGV("startInput(%d) failed for HOTWORD: other input %d already started",
1969 input, activeDesc->mIoHandle);
1970 return INVALID_OPERATION;
1971 }
1972 } else {
1973 if (activeSource != AUDIO_SOURCE_HOTWORD) {
1974 ALOGW("startInput(%d) failed: other input %d already started",
1975 input, activeDesc->mIoHandle);
1976 return INVALID_OPERATION;
1977 }
1978 }
1979 }
1980
Chris Thornton2b864642017-06-27 21:26:07 -07001981 // We only need to check if the sound trigger session supports concurrent capture if the
1982 // input is also a sound trigger input. Otherwise, we should preempt any hotword stream
1983 // that's running.
1984 const bool allowConcurrentWithSoundTrigger =
1985 inputDesc->isSoundTrigger() ? soundTriggerSupportsConcurrentCapture() : false;
1986
Eric Laurent74708e72017-04-07 17:13:42 -07001987 // if capture is allowed, preempt currently active HOTWORD captures
1988 for (size_t i = 0; i < activeInputs.size(); i++) {
1989 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
1990
1991 if (is_virtual_input_device(activeDesc->mDevice)) {
1992 continue;
1993 }
1994
Chris Thornton2b864642017-06-27 21:26:07 -07001995 if (allowConcurrentWithSoundTrigger && activeDesc->isSoundTrigger()) {
1996 continue;
1997 }
1998
Eric Laurent74708e72017-04-07 17:13:42 -07001999 audio_source_t activeSource = activeDesc->inputSource(true);
2000 if (activeSource == AUDIO_SOURCE_HOTWORD) {
2001 AudioSessionCollection activeSessions =
2002 activeDesc->getAudioSessions(true /*activeOnly*/);
2003 audio_session_t activeSession = activeSessions.keyAt(0);
2004 audio_io_handle_t activeHandle = activeDesc->mIoHandle;
2005 SortedVector<audio_session_t> sessions = activeDesc->getPreemptedSessions();
2006 sessions.add(activeSession);
2007 inputDesc->setPreemptedSessions(sessions);
2008 stopInput(activeHandle, activeSession);
2009 releaseInput(activeHandle, activeSession);
2010 ALOGV("startInput(%d) for HOTWORD preempting HOTWORD input %d",
2011 input, activeDesc->mIoHandle);
2012 }
2013 }
2014 }
2015#endif
Eric Laurente552edb2014-03-10 17:42:56 -07002016
Eric Laurent313d1e72016-01-29 09:56:57 -08002017 // increment activity count before calling getNewInputDevice() below as only active sessions
2018 // are considered for device selection
2019 audioSession->changeActiveCount(1);
2020
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002021 // Routing?
2022 mInputRoutes.incRouteActivity(session);
2023
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002024 if (audioSession->activeCount() == 1 || mInputRoutes.hasRouteChanged(session)) {
Eric Laurent271a93e2016-09-29 14:47:06 -07002025 // indicate active capture to sound trigger service if starting capture from a mic on
2026 // primary HW module
Eric Laurentf7c50102016-09-30 15:19:43 -07002027 audio_devices_t device = getNewInputDevice(inputDesc);
Eric Laurent271a93e2016-09-29 14:47:06 -07002028 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002029
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002030 if (inputDesc->getAudioSessionCount(true/*activeOnly*/) == 1) {
2031 // if input maps to a dynamic policy with an activity listener, notify of state change
2032 if ((inputDesc->mPolicyMix != NULL)
2033 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2034 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2035 MIX_STATE_MIXING);
Eric Laurentc722f302014-12-10 11:21:49 -08002036 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002037
Eric Laurentf7c50102016-09-30 15:19:43 -07002038 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2039 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Eric Laurent05b345e2016-11-18 12:36:27 -08002040 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002041 SoundTrigger::setCaptureState(true);
2042 }
2043
2044 // automatically enable the remote submix output when input is started if not
2045 // used by a policy mix of type MIX_TYPE_RECORDERS
2046 // For remote submix (a virtual device), we open only one input per capture request.
2047 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2048 String8 address = String8("");
2049 if (inputDesc->mPolicyMix == NULL) {
2050 address = String8("0");
2051 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2052 address = inputDesc->mPolicyMix->mDeviceAddress;
2053 }
2054 if (address != "") {
2055 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2056 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2057 address, "remote-submix");
2058 }
Eric Laurentc722f302014-12-10 11:21:49 -08002059 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002060 }
Eric Laurente552edb2014-03-10 17:42:56 -07002061 }
2062
Eric Laurent599c7582015-12-07 18:05:55 -08002063 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
Eric Laurente552edb2014-03-10 17:42:56 -07002064
Eric Laurente552edb2014-03-10 17:42:56 -07002065 return NO_ERROR;
2066}
2067
Eric Laurent4dc68062014-07-28 17:26:49 -07002068status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
2069 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07002070{
2071 ALOGV("stopInput() input %d", input);
2072 ssize_t index = mInputs.indexOfKey(input);
2073 if (index < 0) {
2074 ALOGW("stopInput() unknown input %d", input);
2075 return BAD_VALUE;
2076 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002077 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07002078
Eric Laurent599c7582015-12-07 18:05:55 -08002079 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07002080 if (index < 0) {
2081 ALOGW("stopInput() unknown session %d on input %d", session, input);
2082 return BAD_VALUE;
2083 }
2084
Eric Laurent599c7582015-12-07 18:05:55 -08002085 if (audioSession->activeCount() == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002086 ALOGW("stopInput() input %d already stopped", input);
2087 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002088 }
2089
Eric Laurent599c7582015-12-07 18:05:55 -08002090 audioSession->changeActiveCount(-1);
Paul McLean466dc8e2015-04-17 13:15:36 -06002091
2092 // Routing?
2093 mInputRoutes.decRouteActivity(session);
2094
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002095 if (audioSession->activeCount() == 0) {
Eric Laurent84332aa2016-01-28 22:19:18 +00002096
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002097 if (inputDesc->isActive()) {
2098 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2099 } else {
2100 // if input maps to a dynamic policy with an activity listener, notify of state change
2101 if ((inputDesc->mPolicyMix != NULL)
2102 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2103 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2104 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002105 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002106
2107 // automatically disable the remote submix output when input is stopped if not
2108 // used by a policy mix of type MIX_TYPE_RECORDERS
2109 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2110 String8 address = String8("");
2111 if (inputDesc->mPolicyMix == NULL) {
2112 address = String8("0");
2113 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2114 address = inputDesc->mPolicyMix->mDeviceAddress;
2115 }
2116 if (address != "") {
2117 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2118 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2119 address, "remote-submix");
2120 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002121 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002122
Eric Laurentf7c50102016-09-30 15:19:43 -07002123 audio_devices_t device = inputDesc->mDevice;
Eric Laurentfb66dd92016-01-28 18:32:03 -08002124 resetInputDevice(input);
Eric Laurent84332aa2016-01-28 22:19:18 +00002125
Eric Laurentf7c50102016-09-30 15:19:43 -07002126 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2127 // primary HW module
2128 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2129 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2130 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08002131 SoundTrigger::setCaptureState(false);
2132 }
2133 inputDesc->clearPreemptedSessions();
Eric Laurent84332aa2016-01-28 22:19:18 +00002134 }
Eric Laurente552edb2014-03-10 17:42:56 -07002135 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002136 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002137}
2138
Eric Laurent4dc68062014-07-28 17:26:49 -07002139void AudioPolicyManager::releaseInput(audio_io_handle_t input,
2140 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07002141{
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002142
Eric Laurente552edb2014-03-10 17:42:56 -07002143 ALOGV("releaseInput() %d", input);
2144 ssize_t index = mInputs.indexOfKey(input);
2145 if (index < 0) {
2146 ALOGW("releaseInput() releasing unknown input %d", input);
2147 return;
2148 }
Paul McLean466dc8e2015-04-17 13:15:36 -06002149
2150 // Routing
2151 mInputRoutes.removeRoute(session);
2152
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002153 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
2154 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07002155
Eric Laurent599c7582015-12-07 18:05:55 -08002156 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
vivek mehta587b8df2017-01-31 14:58:44 -08002157 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07002158 ALOGW("releaseInput() unknown session %d on input %d", session, input);
2159 return;
2160 }
Eric Laurent599c7582015-12-07 18:05:55 -08002161
2162 if (audioSession->openCount() == 0) {
2163 ALOGW("releaseInput() invalid open count %d on session %d",
2164 audioSession->openCount(), session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002165 return;
2166 }
Eric Laurent599c7582015-12-07 18:05:55 -08002167
2168 if (audioSession->changeOpenCount(-1) == 0) {
2169 inputDesc->removeAudioSession(session);
2170 }
2171
Jean-Michel Trivi65bfe912015-12-04 15:56:47 -08002172 if (inputDesc->getOpenRefCount() > 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002173 ALOGV("releaseInput() exit > 0");
2174 return;
2175 }
2176
Eric Laurent05b90f82014-08-27 15:32:29 -07002177 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002178 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002179 ALOGV("releaseInput() exit");
2180}
2181
Eric Laurentd4692962014-05-05 18:13:44 -07002182void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002183 bool patchRemoved = false;
2184
Eric Laurentd4692962014-05-05 18:13:44 -07002185 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002186 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002187 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002188 if (patch_index >= 0) {
2189 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002190 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002191 mAudioPatches.removeItemsAt(patch_index);
2192 patchRemoved = true;
2193 }
Eric Laurentd4692962014-05-05 18:13:44 -07002194 mpClientInterface->closeInput(mInputs.keyAt(input_index));
2195 }
2196 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002197 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002198 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002199
2200 if (patchRemoved) {
2201 mpClientInterface->onAudioPatchListUpdate();
2202 }
Eric Laurentd4692962014-05-05 18:13:44 -07002203}
2204
Eric Laurente0720872014-03-11 09:30:41 -07002205void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002206 int indexMin,
2207 int indexMax)
2208{
2209 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002210 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002211
2212 // initialize other private stream volumes which follow this one
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;
2216 }
2217 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002218 }
Eric Laurente552edb2014-03-10 17:42:56 -07002219}
2220
Eric Laurente0720872014-03-11 09:30:41 -07002221status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002222 int index,
2223 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002224{
2225
François Gaffied1ab2bd2015-12-02 18:20:06 +01002226 if ((index < mVolumeCurves->getVolumeIndexMin(stream)) ||
2227 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002228 return BAD_VALUE;
2229 }
2230 if (!audio_is_output_device(device)) {
2231 return BAD_VALUE;
2232 }
2233
2234 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002235 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002236
Eric Laurent1fd372e2016-04-06 14:23:53 -07002237 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002238 stream, device, index);
2239
Eric Laurent28d09f02016-03-08 10:43:05 -08002240 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002241 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2242 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002243 continue;
2244 }
2245 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2246 }
Eric Laurente552edb2014-03-10 17:42:56 -07002247
Eric Laurent1fd372e2016-04-06 14:23:53 -07002248 // update volume on all outputs and streams matching the following:
2249 // - The requested stream (or a stream matching for volume control) is active on the output
2250 // - The device (or devices) selected by the strategy corresponding to this stream includes
2251 // the requested device
2252 // - For non default requested device, currently selected device on the output is either the
2253 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002254 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2255 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002256 status_t status = NO_ERROR;
2257 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002258 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2259 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08002260 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2261 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002262 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002263 }
Eric Laurentd3926fe2016-04-15 18:10:07 -07002264 if (!(desc->isStreamActive((audio_stream_type_t)curStream) ||
2265 (isInCall() && (curStream == AUDIO_STREAM_VOICE_CALL)))) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002266 continue;
2267 }
Eric Laurent794fde22016-03-11 09:50:45 -08002268 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002269 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2270 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002271 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2272 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002273 continue;
2274 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002275 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002276 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002277 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07002278 applyVolume = (curDevice & curStreamDevice) != 0;
2279 } else {
2280 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002281 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002282 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002283
Eric Laurente76f29c2016-09-14 17:17:53 -07002284 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002285 //FIXME: workaround for truncated touch sounds
2286 // delayed volume change for system stream to be removed when the problem is
2287 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002288 status_t volStatus =
Eric Laurentdc462862016-07-19 12:29:53 -07002289 checkAndSetVolume((audio_stream_type_t)curStream, index, desc, curDevice,
2290 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002291 if (volStatus != NO_ERROR) {
2292 status = volStatus;
2293 }
2294 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002295 }
Eric Laurente552edb2014-03-10 17:42:56 -07002296 }
2297 return status;
2298}
2299
Eric Laurente0720872014-03-11 09:30:41 -07002300status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002301 int *index,
2302 audio_devices_t device)
2303{
2304 if (index == NULL) {
2305 return BAD_VALUE;
2306 }
2307 if (!audio_is_output_device(device)) {
2308 return BAD_VALUE;
2309 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002310 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002311 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002312 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002313 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2314 }
François Gaffiedfd74092015-03-19 12:10:59 +01002315 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002316
François Gaffied1ab2bd2015-12-02 18:20:06 +01002317 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002318 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2319 return NO_ERROR;
2320}
2321
Eric Laurent36829f92017-04-07 19:04:42 -07002322audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002323{
2324 // select one output among several suitable for global effects.
2325 // The priority is as follows:
2326 // 1: An offloaded output. If the effect ends up not being offloadable,
2327 // AudioFlinger will invalidate the track and the offloaded output
2328 // will be closed causing the effect to be moved to a PCM output.
2329 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002330 // 3: The primary output
2331 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002332
Eric Laurent3b73df72014-03-11 09:06:29 -07002333 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002334 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent36829f92017-04-07 19:04:42 -07002335 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002336
Eric Laurent36829f92017-04-07 19:04:42 -07002337 if (outputs.size() == 0) {
2338 return AUDIO_IO_HANDLE_NONE;
2339 }
Eric Laurente552edb2014-03-10 17:42:56 -07002340
Eric Laurent36829f92017-04-07 19:04:42 -07002341 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2342 bool activeOnly = true;
2343
2344 while (output == AUDIO_IO_HANDLE_NONE) {
2345 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2346 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2347 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2348
2349 for (size_t i = 0; i < outputs.size(); i++) {
2350 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
2351 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2352 continue;
2353 }
2354 ALOGV("selectOutputForMusicEffects activeOnly %d outputs[%zu] flags 0x%08x",
2355 activeOnly, i, desc->mFlags);
2356 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
2357 outputOffloaded = outputs[i];
2358 }
2359 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
2360 outputDeepBuffer = outputs[i];
2361 }
2362 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
2363 outputPrimary = outputs[i];
2364 }
2365 }
2366 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2367 output = outputOffloaded;
2368 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2369 output = outputDeepBuffer;
2370 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2371 output = outputPrimary;
2372 } else {
2373 output = outputs[0];
2374 }
2375 activeOnly = false;
2376 }
2377
2378 if (output != mMusicEffectOutput) {
2379 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2380 mMusicEffectOutput = output;
2381 }
2382
2383 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002384 return output;
2385}
2386
Eric Laurent36829f92017-04-07 19:04:42 -07002387audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2388{
2389 return selectOutputForMusicEffects();
2390}
2391
Eric Laurente0720872014-03-11 09:30:41 -07002392status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002393 audio_io_handle_t io,
2394 uint32_t strategy,
2395 int session,
2396 int id)
2397{
2398 ssize_t index = mOutputs.indexOfKey(io);
2399 if (index < 0) {
2400 index = mInputs.indexOfKey(io);
2401 if (index < 0) {
2402 ALOGW("registerEffect() unknown io %d", io);
2403 return INVALID_OPERATION;
2404 }
2405 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002406 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002407}
2408
Eric Laurentc75307b2015-03-17 15:29:32 -07002409bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2410{
Eric Laurent28d09f02016-03-08 10:43:05 -08002411 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002412 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2413 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002414 continue;
2415 }
2416 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2417 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002418 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002419}
2420
2421bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2422{
2423 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2424}
2425
Eric Laurente0720872014-03-11 09:30:41 -07002426bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002427{
2428 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002429 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002430 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002431 return true;
2432 }
2433 }
2434 return false;
2435}
2436
Eric Laurent275e8e92014-11-30 15:14:47 -08002437// Register a list of custom mixes with their attributes and format.
2438// When a mix is registered, corresponding input and output profiles are
2439// added to the remote submix hw module. The profile contains only the
2440// parameters (sampling rate, format...) specified by the mix.
2441// The corresponding input remote submix device is also connected.
2442//
2443// When a remote submix device is connected, the address is checked to select the
2444// appropriate profile and the corresponding input or output stream is opened.
2445//
2446// When capture starts, getInputForAttr() will:
2447// - 1 look for a mix matching the address passed in attribtutes tags if any
2448// - 2 if none found, getDeviceForInputSource() will:
2449// - 2.1 look for a mix matching the attributes source
2450// - 2.2 if none found, default to device selection by policy rules
2451// At this time, the corresponding output remote submix device is also connected
2452// and active playback use cases can be transferred to this mix if needed when reconnecting
2453// after AudioTracks are invalidated
2454//
2455// When playback starts, getOutputForAttr() will:
2456// - 1 look for a mix matching the address passed in attribtutes tags if any
2457// - 2 if none found, look for a mix matching the attributes usage
2458// - 3 if none found, default to device and output selection by policy rules.
2459
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002460status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002461{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002462 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2463 status_t res = NO_ERROR;
2464
2465 sp<HwModule> rSubmixModule;
2466 // examine each mix's route type
2467 for (size_t i = 0; i < mixes.size(); i++) {
2468 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
2469 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
2470 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002471 break;
2472 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002473 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
2474 // Loop back through "remote submix"
2475 if (rSubmixModule == 0) {
2476 for (size_t j = 0; i < mHwModules.size(); j++) {
2477 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
2478 && mHwModules[j]->mHandle != 0) {
2479 rSubmixModule = mHwModules[j];
2480 break;
2481 }
2482 }
2483 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002484
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002485 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Eric Laurent275e8e92014-11-30 15:14:47 -08002486
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002487 if (rSubmixModule == 0) {
2488 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration", i);
2489 res = INVALID_OPERATION;
2490 break;
2491 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002492
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002493 String8 address = mixes[i].mDeviceAddress;
François Gaffie036e1e92015-03-19 10:16:24 +01002494
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002495 if (mPolicyMixes.registerMix(address, mixes[i], 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002496 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002497 res = INVALID_OPERATION;
2498 break;
2499 }
2500 audio_config_t outputConfig = mixes[i].mFormat;
2501 audio_config_t inputConfig = mixes[i].mFormat;
2502 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2503 // stereo and let audio flinger do the channel conversion if needed.
2504 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2505 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2506 rSubmixModule->addOutputProfile(address, &outputConfig,
2507 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2508 rSubmixModule->addInputProfile(address, &inputConfig,
2509 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002510
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002511 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
2512 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2513 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2514 address.string(), "remote-submix");
2515 } else {
2516 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2517 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2518 address.string(), "remote-submix");
2519 }
2520 } else if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002521 String8 address = mixes[i].mDeviceAddress;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002522 audio_devices_t device = mixes[i].mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002523 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2524 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002525
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002526 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002527 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2528 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2529 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2530 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2531 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2532 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002533 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2534 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002535 if (mPolicyMixes.registerMix(address, mixes[i], desc) != NO_ERROR) {
2536 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002537 } else {
2538 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002539 }
2540 break;
2541 }
2542 }
2543
2544 if (res != NO_ERROR) {
2545 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002546 i, device, address.string());
2547 res = INVALID_OPERATION;
2548 break;
2549 } else if (!foundOutput) {
2550 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2551 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002552 res = INVALID_OPERATION;
2553 break;
2554 }
Eric Laurentc722f302014-12-10 11:21:49 -08002555 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002556 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002557 if (res != NO_ERROR) {
2558 unregisterPolicyMixes(mixes);
2559 }
2560 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002561}
2562
2563status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2564{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002565 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002566 status_t res = NO_ERROR;
2567 sp<HwModule> rSubmixModule;
2568 // examine each mix's route type
Eric Laurent275e8e92014-11-30 15:14:47 -08002569 for (size_t i = 0; i < mixes.size(); i++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002570 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002571
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002572 if (rSubmixModule == 0) {
2573 for (size_t j = 0; i < mHwModules.size(); j++) {
2574 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
2575 && mHwModules[j]->mHandle != 0) {
2576 rSubmixModule = mHwModules[j];
2577 break;
2578 }
2579 }
2580 }
2581 if (rSubmixModule == 0) {
2582 res = INVALID_OPERATION;
2583 continue;
2584 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002585
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002586 String8 address = mixes[i].mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002587
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002588 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2589 res = INVALID_OPERATION;
2590 continue;
2591 }
2592
2593 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2594 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2595 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2596 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2597 address.string(), "remote-submix");
2598 }
2599 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2600 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2601 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2602 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2603 address.string(), "remote-submix");
2604 }
2605 rSubmixModule->removeOutputProfile(address);
2606 rSubmixModule->removeInputProfile(address);
2607
2608 } if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2609 if (mPolicyMixes.unregisterMix(mixes[i].mDeviceAddress) != NO_ERROR) {
2610 res = INVALID_OPERATION;
2611 continue;
2612 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002613 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002614 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002615 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002616}
2617
Eric Laurente552edb2014-03-10 17:42:56 -07002618
Eric Laurente0720872014-03-11 09:30:41 -07002619status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002620{
2621 const size_t SIZE = 256;
2622 char buffer[SIZE];
2623 String8 result;
2624
2625 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2626 result.append(buffer);
2627
Eric Laurent87ffa392015-05-22 10:32:38 -07002628 snprintf(buffer, SIZE, " Primary Output: %d\n",
2629 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Eric Laurente552edb2014-03-10 17:42:56 -07002630 result.append(buffer);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002631 std::string stateLiteral;
2632 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
2633 snprintf(buffer, SIZE, " Phone state: %s\n", stateLiteral.c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002634 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002635 snprintf(buffer, SIZE, " Force use for communications %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002636 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07002637 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002638 snprintf(buffer, SIZE, " Force use for media %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA));
Eric Laurente552edb2014-03-10 17:42:56 -07002639 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002640 snprintf(buffer, SIZE, " Force use for record %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD));
Eric Laurente552edb2014-03-10 17:42:56 -07002641 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002642 snprintf(buffer, SIZE, " Force use for dock %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_DOCK));
Eric Laurente552edb2014-03-10 17:42:56 -07002643 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002644 snprintf(buffer, SIZE, " Force use for system %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM));
Eric Laurente552edb2014-03-10 17:42:56 -07002645 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002646 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002647 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO));
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002648 result.append(buffer);
Phil Burk09bc4612016-02-24 15:58:15 -08002649 snprintf(buffer, SIZE, " Force use for encoded surround output %d\n",
2650 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND));
2651 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002652 snprintf(buffer, SIZE, " TTS output %s\n", mTtsOutputAvailable ? "available" : "not available");
2653 result.append(buffer);
Andy Hung2ddee192015-12-18 17:34:44 -08002654 snprintf(buffer, SIZE, " Master mono: %s\n", mMasterMono ? "on" : "off");
2655 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002656
François Gaffie2110e042015-03-24 08:41:51 +01002657 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002658
François Gaffie112b0af2015-11-19 16:13:25 +01002659 mAvailableOutputDevices.dump(fd, String8("Available output"));
2660 mAvailableInputDevices.dump(fd, String8("Available input"));
François Gaffie53615e22015-03-19 09:24:12 +01002661 mHwModules.dump(fd);
2662 mOutputs.dump(fd);
2663 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002664 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002665 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002666 mAudioPatches.dump(fd);
Mikhail Naganov44344b02016-12-13 11:21:02 -08002667 mPolicyMixes.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002668
2669 return NO_ERROR;
2670}
2671
2672// This function checks for the parameters which can be offloaded.
2673// This can be enhanced depending on the capability of the DSP and policy
2674// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002675bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002676{
2677 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002678 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002679 offloadInfo.sample_rate, offloadInfo.channel_mask,
2680 offloadInfo.format,
2681 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2682 offloadInfo.has_video);
2683
Andy Hung2ddee192015-12-18 17:34:44 -08002684 if (mMasterMono) {
2685 return false; // no offloading if mono is set.
2686 }
2687
Eric Laurente552edb2014-03-10 17:42:56 -07002688 // Check if offload has been disabled
2689 char propValue[PROPERTY_VALUE_MAX];
2690 if (property_get("audio.offload.disable", propValue, "0")) {
2691 if (atoi(propValue) != 0) {
2692 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2693 return false;
2694 }
2695 }
2696
2697 // Check if stream type is music, then only allow offload as of now.
2698 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2699 {
2700 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2701 return false;
2702 }
2703
2704 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002705 const bool allowOffloadWithVideo =
2706 property_get_bool("audio.offload.video", false /* default_value */);
2707 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002708 ALOGV("isOffloadSupported: has_video == true, returning false");
2709 return false;
2710 }
2711
2712 //If duration is less than minimum value defined in property, return false
2713 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2714 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2715 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2716 return false;
2717 }
2718 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2719 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2720 return false;
2721 }
2722
2723 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2724 // creating an offloaded track and tearing it down immediately after start when audioflinger
2725 // detects there is an active non offloadable effect.
2726 // FIXME: We should check the audio session here but we do not have it in this context.
2727 // This may prevent offloading in rare situations where effects are left active by apps
2728 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002729 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002730 return false;
2731 }
2732
2733 // See if there is a profile to support this.
2734 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002735 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002736 offloadInfo.sample_rate,
2737 offloadInfo.format,
2738 offloadInfo.channel_mask,
2739 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002740 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2741 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002742}
2743
Eric Laurent6a94d692014-05-20 11:18:06 -07002744status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2745 audio_port_type_t type,
2746 unsigned int *num_ports,
2747 struct audio_port *ports,
2748 unsigned int *generation)
2749{
2750 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2751 generation == NULL) {
2752 return BAD_VALUE;
2753 }
2754 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2755 if (ports == NULL) {
2756 *num_ports = 0;
2757 }
2758
2759 size_t portsWritten = 0;
2760 size_t portsMax = *num_ports;
2761 *num_ports = 0;
2762 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002763 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2764 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002765 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002766 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
2767 if (mAvailableOutputDevices[i]->type() == AUDIO_DEVICE_OUT_STUB) {
2768 continue;
2769 }
2770 if (portsWritten < portsMax) {
2771 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2772 }
2773 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002774 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002775 }
2776 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002777 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2778 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_STUB) {
2779 continue;
2780 }
2781 if (portsWritten < portsMax) {
2782 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2783 }
2784 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002785 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002786 }
2787 }
2788 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2789 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2790 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2791 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2792 }
2793 *num_ports += mInputs.size();
2794 }
2795 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002796 size_t numOutputs = 0;
2797 for (size_t i = 0; i < mOutputs.size(); i++) {
2798 if (!mOutputs[i]->isDuplicated()) {
2799 numOutputs++;
2800 if (portsWritten < portsMax) {
2801 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2802 }
2803 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002804 }
Eric Laurent84c70242014-06-23 08:46:27 -07002805 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002806 }
2807 }
2808 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002809 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002810 return NO_ERROR;
2811}
2812
2813status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2814{
2815 return NO_ERROR;
2816}
2817
Eric Laurent6a94d692014-05-20 11:18:06 -07002818status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2819 audio_patch_handle_t *handle,
2820 uid_t uid)
2821{
2822 ALOGV("createAudioPatch()");
2823
2824 if (handle == NULL || patch == NULL) {
2825 return BAD_VALUE;
2826 }
2827 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2828
Eric Laurent874c42872014-08-08 15:13:39 -07002829 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2830 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2831 return BAD_VALUE;
2832 }
2833 // only one source per audio patch supported for now
2834 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002835 return INVALID_OPERATION;
2836 }
Eric Laurent874c42872014-08-08 15:13:39 -07002837
2838 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002839 return INVALID_OPERATION;
2840 }
Eric Laurent874c42872014-08-08 15:13:39 -07002841 for (size_t i = 0; i < patch->num_sinks; i++) {
2842 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2843 return INVALID_OPERATION;
2844 }
2845 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002846
2847 sp<AudioPatch> patchDesc;
2848 ssize_t index = mAudioPatches.indexOfKey(*handle);
2849
Eric Laurent6a94d692014-05-20 11:18:06 -07002850 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2851 patch->sources[0].role,
2852 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002853#if LOG_NDEBUG == 0
2854 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002855 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002856 patch->sinks[i].role,
2857 patch->sinks[i].type);
2858 }
2859#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002860
2861 if (index >= 0) {
2862 patchDesc = mAudioPatches.valueAt(index);
2863 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2864 mUidCached, patchDesc->mUid, uid);
2865 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2866 return INVALID_OPERATION;
2867 }
2868 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002869 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002870 }
2871
2872 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002873 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002874 if (outputDesc == NULL) {
2875 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2876 return BAD_VALUE;
2877 }
Eric Laurent84c70242014-06-23 08:46:27 -07002878 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2879 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002880 if (patchDesc != 0) {
2881 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2882 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2883 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2884 return BAD_VALUE;
2885 }
2886 }
Eric Laurent874c42872014-08-08 15:13:39 -07002887 DeviceVector devices;
2888 for (size_t i = 0; i < patch->num_sinks; i++) {
2889 // Only support mix to devices connection
2890 // TODO add support for mix to mix connection
2891 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2892 ALOGV("createAudioPatch() source mix but sink is not a device");
2893 return INVALID_OPERATION;
2894 }
2895 sp<DeviceDescriptor> devDesc =
2896 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2897 if (devDesc == 0) {
2898 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2899 return BAD_VALUE;
2900 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002901
François Gaffie53615e22015-03-19 09:24:12 +01002902 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002903 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002904 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002905 NULL, // updatedSamplingRate
2906 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002907 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002908 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002909 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002910 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002911 ALOGV("createAudioPatch() profile not supported for device %08x",
2912 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002913 return INVALID_OPERATION;
2914 }
2915 devices.add(devDesc);
2916 }
2917 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002918 return INVALID_OPERATION;
2919 }
Eric Laurent874c42872014-08-08 15:13:39 -07002920
Eric Laurent6a94d692014-05-20 11:18:06 -07002921 // TODO: reconfigure output format and channels here
2922 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002923 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002924 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002925 index = mAudioPatches.indexOfKey(*handle);
2926 if (index >= 0) {
2927 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2928 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2929 }
2930 patchDesc = mAudioPatches.valueAt(index);
2931 patchDesc->mUid = uid;
2932 ALOGV("createAudioPatch() success");
2933 } else {
2934 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2935 return INVALID_OPERATION;
2936 }
2937 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2938 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2939 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002940 // only one sink supported when connecting an input device to a mix
2941 if (patch->num_sinks > 1) {
2942 return INVALID_OPERATION;
2943 }
François Gaffie53615e22015-03-19 09:24:12 +01002944 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002945 if (inputDesc == NULL) {
2946 return BAD_VALUE;
2947 }
2948 if (patchDesc != 0) {
2949 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2950 return BAD_VALUE;
2951 }
2952 }
2953 sp<DeviceDescriptor> devDesc =
2954 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2955 if (devDesc == 0) {
2956 return BAD_VALUE;
2957 }
2958
François Gaffie53615e22015-03-19 09:24:12 +01002959 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002960 devDesc->mAddress,
2961 patch->sinks[0].sample_rate,
2962 NULL, /*updatedSampleRate*/
2963 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002964 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002965 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002966 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002967 // FIXME for the parameter type,
2968 // and the NONE
2969 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002970 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002971 return INVALID_OPERATION;
2972 }
2973 // TODO: reconfigure output format and channels here
2974 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01002975 devDesc->type(), inputDesc->mIoHandle);
2976 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002977 index = mAudioPatches.indexOfKey(*handle);
2978 if (index >= 0) {
2979 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2980 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2981 }
2982 patchDesc = mAudioPatches.valueAt(index);
2983 patchDesc->mUid = uid;
2984 ALOGV("createAudioPatch() success");
2985 } else {
2986 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2987 return INVALID_OPERATION;
2988 }
2989 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2990 // device to device connection
2991 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002992 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002993 return BAD_VALUE;
2994 }
2995 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002996 sp<DeviceDescriptor> srcDeviceDesc =
2997 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002998 if (srcDeviceDesc == 0) {
2999 return BAD_VALUE;
3000 }
Eric Laurent874c42872014-08-08 15:13:39 -07003001
Eric Laurent6a94d692014-05-20 11:18:06 -07003002 //update source and sink with our own data as the data passed in the patch may
3003 // be incomplete.
3004 struct audio_patch newPatch = *patch;
3005 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003006
Eric Laurent874c42872014-08-08 15:13:39 -07003007 for (size_t i = 0; i < patch->num_sinks; i++) {
3008 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3009 ALOGV("createAudioPatch() source device but one sink is not a device");
3010 return INVALID_OPERATION;
3011 }
3012
3013 sp<DeviceDescriptor> sinkDeviceDesc =
3014 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3015 if (sinkDeviceDesc == 0) {
3016 return BAD_VALUE;
3017 }
3018 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
3019
Eric Laurent3bcf8592015-04-03 12:13:24 -07003020 // create a software bridge in PatchPanel if:
3021 // - source and sink devices are on differnt HW modules OR
3022 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08003023 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003024 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003025 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003026 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003027 return INVALID_OPERATION;
3028 }
Eric Laurent874c42872014-08-08 15:13:39 -07003029 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01003030 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003031 // if the sink device is reachable via an opened output stream, request to go via
3032 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07003033 audio_io_handle_t output = selectOutput(outputs,
3034 AUDIO_OUTPUT_FLAG_NONE,
3035 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07003036 if (output != AUDIO_IO_HANDLE_NONE) {
3037 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3038 if (outputDesc->isDuplicated()) {
3039 return INVALID_OPERATION;
3040 }
3041 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003042 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003043 newPatch.num_sources = 2;
3044 }
Eric Laurent83b88082014-06-20 18:31:16 -07003045 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003046 }
3047 // TODO: check from routing capabilities in config file and other conflicting patches
3048
3049 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3050 if (index >= 0) {
3051 afPatchHandle = patchDesc->mAfPatchHandle;
3052 }
3053
3054 status_t status = mpClientInterface->createAudioPatch(&newPatch,
3055 &afPatchHandle,
3056 0);
3057 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
3058 status, afPatchHandle);
3059 if (status == NO_ERROR) {
3060 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01003061 patchDesc = new AudioPatch(&newPatch, uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003062 addAudioPatch(patchDesc->mHandle, patchDesc);
3063 } else {
3064 patchDesc->mPatch = newPatch;
3065 }
3066 patchDesc->mAfPatchHandle = afPatchHandle;
3067 *handle = patchDesc->mHandle;
3068 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003069 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003070 } else {
3071 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3072 status);
3073 return INVALID_OPERATION;
3074 }
3075 } else {
3076 return BAD_VALUE;
3077 }
3078 } else {
3079 return BAD_VALUE;
3080 }
3081 return NO_ERROR;
3082}
3083
3084status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3085 uid_t uid)
3086{
3087 ALOGV("releaseAudioPatch() patch %d", handle);
3088
3089 ssize_t index = mAudioPatches.indexOfKey(handle);
3090
3091 if (index < 0) {
3092 return BAD_VALUE;
3093 }
3094 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3095 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3096 mUidCached, patchDesc->mUid, uid);
3097 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3098 return INVALID_OPERATION;
3099 }
3100
3101 struct audio_patch *patch = &patchDesc->mPatch;
3102 patchDesc->mUid = mUidCached;
3103 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003104 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003105 if (outputDesc == NULL) {
3106 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3107 return BAD_VALUE;
3108 }
3109
Eric Laurentc75307b2015-03-17 15:29:32 -07003110 setOutputDevice(outputDesc,
3111 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07003112 true,
3113 0,
3114 NULL);
3115 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3116 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003117 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003118 if (inputDesc == NULL) {
3119 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3120 return BAD_VALUE;
3121 }
3122 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003123 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003124 true,
3125 NULL);
3126 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003127 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3128 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3129 status, patchDesc->mAfPatchHandle);
3130 removeAudioPatch(patchDesc->mHandle);
3131 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003132 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003133 } else {
3134 return BAD_VALUE;
3135 }
3136 } else {
3137 return BAD_VALUE;
3138 }
3139 return NO_ERROR;
3140}
3141
3142status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3143 struct audio_patch *patches,
3144 unsigned int *generation)
3145{
François Gaffie53615e22015-03-19 09:24:12 +01003146 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003147 return BAD_VALUE;
3148 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003149 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003150 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003151}
3152
Eric Laurente1715a42014-05-20 11:30:42 -07003153status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003154{
Eric Laurente1715a42014-05-20 11:30:42 -07003155 ALOGV("setAudioPortConfig()");
3156
3157 if (config == NULL) {
3158 return BAD_VALUE;
3159 }
3160 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3161 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003162 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3163 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003164 }
3165
Eric Laurenta121f902014-06-03 13:32:54 -07003166 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003167 if (config->type == AUDIO_PORT_TYPE_MIX) {
3168 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003169 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003170 if (outputDesc == NULL) {
3171 return BAD_VALUE;
3172 }
Eric Laurent84c70242014-06-23 08:46:27 -07003173 ALOG_ASSERT(!outputDesc->isDuplicated(),
3174 "setAudioPortConfig() called on duplicated output %d",
3175 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003176 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003177 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003178 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003179 if (inputDesc == NULL) {
3180 return BAD_VALUE;
3181 }
Eric Laurenta121f902014-06-03 13:32:54 -07003182 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003183 } else {
3184 return BAD_VALUE;
3185 }
3186 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3187 sp<DeviceDescriptor> deviceDesc;
3188 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3189 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3190 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3191 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3192 } else {
3193 return BAD_VALUE;
3194 }
3195 if (deviceDesc == NULL) {
3196 return BAD_VALUE;
3197 }
Eric Laurenta121f902014-06-03 13:32:54 -07003198 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003199 } else {
3200 return BAD_VALUE;
3201 }
3202
Eric Laurenta121f902014-06-03 13:32:54 -07003203 struct audio_port_config backupConfig;
3204 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3205 if (status == NO_ERROR) {
3206 struct audio_port_config newConfig;
3207 audioPortConfig->toAudioPortConfig(&newConfig, config);
3208 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003209 }
Eric Laurenta121f902014-06-03 13:32:54 -07003210 if (status != NO_ERROR) {
3211 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003212 }
Eric Laurente1715a42014-05-20 11:30:42 -07003213
3214 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003215}
3216
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003217void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3218{
Eric Laurentd60560a2015-04-10 11:31:20 -07003219 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003220 clearAudioPatches(uid);
3221 clearSessionRoutes(uid);
3222}
3223
Eric Laurent6a94d692014-05-20 11:18:06 -07003224void AudioPolicyManager::clearAudioPatches(uid_t uid)
3225{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003226 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003227 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3228 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003229 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003230 }
3231 }
3232}
3233
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003234void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3235 audio_io_handle_t ouptutToSkip)
3236{
3237 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3238 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3239 for (size_t j = 0; j < mOutputs.size(); j++) {
3240 if (mOutputs.keyAt(j) == ouptutToSkip) {
3241 continue;
3242 }
3243 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3244 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3245 continue;
3246 }
3247 // If the default device for this strategy is on another output mix,
3248 // invalidate all tracks in this strategy to force re connection.
3249 // Otherwise select new device on the output mix.
3250 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003251 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003252 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3253 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3254 }
3255 }
3256 } else {
3257 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3258 setOutputDevice(outputDesc, newDevice, false);
3259 }
3260 }
3261}
3262
3263void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3264{
3265 // remove output routes associated with this uid
3266 SortedVector<routing_strategy> affectedStrategies;
3267 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
3268 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
3269 if (route->mUid == uid) {
3270 mOutputRoutes.removeItemsAt(i);
3271 if (route->mDeviceDescriptor != 0) {
3272 affectedStrategies.add(getStrategy(route->mStreamType));
3273 }
3274 }
3275 }
3276 // reroute outputs if necessary
3277 for (size_t i = 0; i < affectedStrategies.size(); i++) {
3278 checkStrategyRoute(affectedStrategies[i], AUDIO_IO_HANDLE_NONE);
3279 }
3280
3281 // remove input routes associated with this uid
3282 SortedVector<audio_source_t> affectedSources;
3283 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
3284 sp<SessionRoute> route = mInputRoutes.valueAt(i);
3285 if (route->mUid == uid) {
3286 mInputRoutes.removeItemsAt(i);
3287 if (route->mDeviceDescriptor != 0) {
3288 affectedSources.add(route->mSource);
3289 }
3290 }
3291 }
3292 // reroute inputs if necessary
3293 SortedVector<audio_io_handle_t> inputsToClose;
3294 for (size_t i = 0; i < mInputs.size(); i++) {
3295 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003296 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003297 inputsToClose.add(inputDesc->mIoHandle);
3298 }
3299 }
3300 for (size_t i = 0; i < inputsToClose.size(); i++) {
3301 closeInput(inputsToClose[i]);
3302 }
3303}
3304
Eric Laurentd60560a2015-04-10 11:31:20 -07003305void AudioPolicyManager::clearAudioSources(uid_t uid)
3306{
3307 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
3308 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3309 if (sourceDesc->mUid == uid) {
3310 stopAudioSource(mAudioSources.keyAt(i));
3311 }
3312 }
3313}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003314
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003315status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3316 audio_io_handle_t *ioHandle,
3317 audio_devices_t *device)
3318{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003319 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3320 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003321 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003322
François Gaffiedf372692015-03-19 10:43:27 +01003323 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003324}
3325
Eric Laurentd60560a2015-04-10 11:31:20 -07003326status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
3327 const audio_attributes_t *attributes,
Glenn Kasten559d4392016-03-29 13:42:57 -07003328 audio_patch_handle_t *handle,
Eric Laurentd60560a2015-04-10 11:31:20 -07003329 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003330{
Eric Laurentd60560a2015-04-10 11:31:20 -07003331 ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle);
3332 if (source == NULL || attributes == NULL || handle == NULL) {
3333 return BAD_VALUE;
3334 }
3335
Glenn Kasten559d4392016-03-29 13:42:57 -07003336 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003337
3338 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3339 source->type != AUDIO_PORT_TYPE_DEVICE) {
3340 ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type);
3341 return INVALID_OPERATION;
3342 }
3343
3344 sp<DeviceDescriptor> srcDeviceDesc =
3345 mAvailableInputDevices.getDevice(source->ext.device.type,
3346 String8(source->ext.device.address));
3347 if (srcDeviceDesc == 0) {
3348 ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
3349 return BAD_VALUE;
3350 }
3351 sp<AudioSourceDescriptor> sourceDesc =
3352 new AudioSourceDescriptor(srcDeviceDesc, attributes, uid);
3353
3354 struct audio_patch dummyPatch;
3355 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
3356 sourceDesc->mPatchDesc = patchDesc;
3357
3358 status_t status = connectAudioSource(sourceDesc);
3359 if (status == NO_ERROR) {
3360 mAudioSources.add(sourceDesc->getHandle(), sourceDesc);
3361 *handle = sourceDesc->getHandle();
3362 }
3363 return status;
3364}
3365
3366status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3367{
3368 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3369
3370 // make sure we only have one patch per source.
3371 disconnectAudioSource(sourceDesc);
3372
3373 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
Eric Laurent28d09f02016-03-08 10:43:05 -08003374 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003375 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice;
3376
3377 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3378 sp<DeviceDescriptor> sinkDeviceDesc =
3379 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3380
3381 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3382 struct audio_patch *patch = &sourceDesc->mPatchDesc->mPatch;
3383
3384 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3385 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003386 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003387 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3388 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3389 // create patch between src device and output device
3390 // create Hwoutput and add to mHwOutputs
3391 } else {
3392 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3393 audio_io_handle_t output =
3394 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3395 if (output == AUDIO_IO_HANDLE_NONE) {
3396 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3397 return INVALID_OPERATION;
3398 }
3399 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3400 if (outputDesc->isDuplicated()) {
3401 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3402 return INVALID_OPERATION;
3403 }
3404 // create a special patch with no sink and two sources:
3405 // - the second source indicates to PatchPanel through which output mix this patch should
3406 // be connected as well as the stream type for volume control
3407 // - the sink is defined by whatever output device is currently selected for the output
3408 // though which this patch is routed.
3409 patch->num_sinks = 0;
3410 patch->num_sources = 2;
3411 srcDeviceDesc->toAudioPortConfig(&patch->sources[0], NULL);
3412 outputDesc->toAudioPortConfig(&patch->sources[1], NULL);
3413 patch->sources[1].ext.mix.usecase.stream = stream;
3414 status_t status = mpClientInterface->createAudioPatch(patch,
3415 &afPatchHandle,
3416 0);
3417 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3418 status, afPatchHandle);
3419 if (status != NO_ERROR) {
3420 ALOGW("%s patch panel could not connect device patch, error %d",
3421 __FUNCTION__, status);
3422 return INVALID_OPERATION;
3423 }
3424 uint32_t delayMs = 0;
Eric Laurentc40d9692016-04-13 19:14:13 -07003425 status = startSource(outputDesc, stream, sinkDevice, NULL, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003426
3427 if (status != NO_ERROR) {
3428 mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0);
3429 return status;
3430 }
3431 sourceDesc->mSwOutput = outputDesc;
3432 if (delayMs != 0) {
3433 usleep(delayMs * 1000);
3434 }
3435 }
3436
3437 sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle;
3438 addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc);
3439
3440 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003441}
3442
Glenn Kasten559d4392016-03-29 13:42:57 -07003443status_t AudioPolicyManager::stopAudioSource(audio_patch_handle_t handle __unused)
Eric Laurent554a2772015-04-10 11:29:24 -07003444{
Eric Laurentd60560a2015-04-10 11:31:20 -07003445 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle);
3446 ALOGV("%s handle %d", __FUNCTION__, handle);
3447 if (sourceDesc == 0) {
3448 ALOGW("%s unknown source for handle %d", __FUNCTION__, handle);
3449 return BAD_VALUE;
3450 }
3451 status_t status = disconnectAudioSource(sourceDesc);
3452
3453 mAudioSources.removeItem(handle);
3454 return status;
3455}
3456
Andy Hung2ddee192015-12-18 17:34:44 -08003457status_t AudioPolicyManager::setMasterMono(bool mono)
3458{
3459 if (mMasterMono == mono) {
3460 return NO_ERROR;
3461 }
3462 mMasterMono = mono;
3463 // if enabling mono we close all offloaded devices, which will invalidate the
3464 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3465 // for recreating the new AudioTrack as non-offloaded PCM.
3466 //
3467 // If disabling mono, we leave all tracks as is: we don't know which clients
3468 // and tracks are able to be recreated as offloaded. The next "song" should
3469 // play back offloaded.
3470 if (mMasterMono) {
3471 Vector<audio_io_handle_t> offloaded;
3472 for (size_t i = 0; i < mOutputs.size(); ++i) {
3473 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3474 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3475 offloaded.push(desc->mIoHandle);
3476 }
3477 }
3478 for (size_t i = 0; i < offloaded.size(); ++i) {
3479 closeOutput(offloaded[i]);
3480 }
3481 }
3482 // update master mono for all remaining outputs
3483 for (size_t i = 0; i < mOutputs.size(); ++i) {
3484 updateMono(mOutputs.keyAt(i));
3485 }
3486 return NO_ERROR;
3487}
3488
3489status_t AudioPolicyManager::getMasterMono(bool *mono)
3490{
3491 *mono = mMasterMono;
3492 return NO_ERROR;
3493}
3494
Eric Laurentac9cef52017-06-09 15:46:26 -07003495float AudioPolicyManager::getStreamVolumeDB(
3496 audio_stream_type_t stream, int index, audio_devices_t device)
3497{
3498 return computeVolume(stream, index, device);
3499}
3500
Eric Laurentd60560a2015-04-10 11:31:20 -07003501status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3502{
3503 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3504
3505 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle);
3506 if (patchDesc == 0) {
3507 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
3508 sourceDesc->mPatchDesc->mHandle);
3509 return BAD_VALUE;
3510 }
3511 removeAudioPatch(sourceDesc->mPatchDesc->mHandle);
3512
Eric Laurent28d09f02016-03-08 10:43:05 -08003513 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003514 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote();
3515 if (swOutputDesc != 0) {
3516 stopSource(swOutputDesc, stream, false);
3517 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3518 } else {
3519 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote();
3520 if (hwOutputDesc != 0) {
3521 // release patch between src device and output device
3522 // close Hwoutput and remove from mHwOutputs
3523 } else {
3524 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3525 }
3526 }
3527 return NO_ERROR;
3528}
3529
3530sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
3531 audio_io_handle_t output, routing_strategy strategy)
3532{
3533 sp<AudioSourceDescriptor> source;
3534 for (size_t i = 0; i < mAudioSources.size(); i++) {
3535 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3536 routing_strategy sourceStrategy =
3537 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
3538 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote();
3539 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3540 source = sourceDesc;
3541 break;
3542 }
3543 }
3544 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003545}
3546
Eric Laurente552edb2014-03-10 17:42:56 -07003547// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003548// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003549// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003550uint32_t AudioPolicyManager::nextAudioPortGeneration()
3551{
3552 return android_atomic_inc(&mAudioPortGeneration);
3553}
3554
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003555#ifdef USE_XML_AUDIO_POLICY_CONF
3556// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3557static const char *kConfigLocationList[] =
3558 {"/odm/etc", "/vendor/etc", "/system/etc"};
3559static const int kConfigLocationListSize =
3560 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3561
3562static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3563 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
3564 status_t ret;
3565
3566 for (int i = 0; i < kConfigLocationListSize; i++) {
3567 PolicySerializer serializer;
3568 snprintf(audioPolicyXmlConfigFile,
3569 sizeof(audioPolicyXmlConfigFile),
3570 "%s/%s",
3571 kConfigLocationList[i],
3572 AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3573 ret = serializer.deserialize(audioPolicyXmlConfigFile, config);
3574 if (ret == NO_ERROR) {
3575 break;
3576 }
3577 }
3578 return ret;
3579}
3580#endif
3581
Eric Laurente0720872014-03-11 09:30:41 -07003582AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07003583 :
3584#ifdef AUDIO_POLICY_TEST
3585 Thread(false),
3586#endif //AUDIO_POLICY_TEST
Eric Laurente552edb2014-03-10 17:42:56 -07003587 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003588 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003589 mAudioPortGeneration(1),
3590 mBeaconMuteRefCount(0),
3591 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003592 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003593 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003594 mMasterMono(false),
Chris Thornton2b864642017-06-27 21:26:07 -07003595 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE),
3596 mHasComputedSoundTriggerSupportsConcurrentCapture(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003597{
François Gaffied1ab2bd2015-12-02 18:20:06 +01003598 mUidCached = getuid();
3599 mpClientInterface = clientInterface;
3600
3601 // TODO: remove when legacy conf file is removed. true on devices that use DRC on the
3602 // DEVICE_CATEGORY_SPEAKER path to boost soft sounds, used to adjust volume curves accordingly.
3603 // Note: remove also speaker_drc_enabled from global configuration of XML config file.
3604 bool speakerDrcEnabled = false;
3605
3606#ifdef USE_XML_AUDIO_POLICY_CONF
3607 mVolumeCurves = new VolumeCurvesCollection();
3608 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3609 mDefaultOutputDevice, speakerDrcEnabled,
3610 static_cast<VolumeCurvesCollection *>(mVolumeCurves));
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003611 if (deserializeAudioPolicyXmlConfig(config) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003612#else
3613 mVolumeCurves = new StreamDescriptorCollection();
3614 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3615 mDefaultOutputDevice, speakerDrcEnabled);
3616 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, config) != NO_ERROR) &&
3617 (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, config) != NO_ERROR)) {
3618#endif
3619 ALOGE("could not load audio policy configuration file, setting defaults");
3620 config.setDefault();
3621 }
3622 // must be done after reading the policy (since conditionned by Speaker Drc Enabling)
3623 mVolumeCurves->initializeVolumeCurves(speakerDrcEnabled);
3624
3625 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003626 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3627 if (!engineInstance) {
3628 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
3629 return;
3630 }
3631 // Retrieve the Policy Manager Interface
3632 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3633 if (mEngine == NULL) {
3634 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
3635 return;
3636 }
3637 mEngine->setObserver(this);
3638 status_t status = mEngine->initCheck();
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07003639 (void) status;
François Gaffie2110e042015-03-24 08:41:51 +01003640 ALOG_ASSERT(status == NO_ERROR, "Policy engine not initialized(err=%d)", status);
3641
Eric Laurent3a4311c2014-03-17 12:00:47 -07003642 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003643 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003644 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3645 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003646 for (size_t i = 0; i < mHwModules.size(); i++) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003647 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003648 if (mHwModules[i]->mHandle == 0) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003649 ALOGW("could not open HW module %s", mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003650 continue;
3651 }
3652 // open all output streams needed to access attached devices
3653 // except for direct output streams that are only opened when they are actually
3654 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003655 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07003656 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3657 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003658 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003659
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003660 if (!outProfile->hasSupportedDevices()) {
3661 ALOGW("Output profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003662 continue;
3663 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003664 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003665 mTtsOutputAvailable = true;
3666 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003667
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003668 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003669 continue;
3670 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003671 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003672 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3673 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003674 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003675 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003676 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003677 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003678 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003679 if ((profileType & outputDeviceTypes) == 0) {
3680 continue;
3681 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003682 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3683 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003684 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
3685 const DeviceVector &devicesForType = supportedDevices.getDevicesFromType(profileType);
3686 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3687 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003688
3689 outputDesc->mDevice = profileType;
3690 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3691 config.sample_rate = outputDesc->mSamplingRate;
3692 config.channel_mask = outputDesc->mChannelMask;
3693 config.format = outputDesc->mFormat;
3694 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003695 status_t status = mpClientInterface->openOutput(outProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003696 &output,
3697 &config,
3698 &outputDesc->mDevice,
Eric Laurentc40d9692016-04-13 19:14:13 -07003699 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003700 &outputDesc->mLatency,
3701 outputDesc->mFlags);
3702
3703 if (status != NO_ERROR) {
3704 ALOGW("Cannot open output stream for device %08x on hw module %s",
3705 outputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003706 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003707 } else {
3708 outputDesc->mSamplingRate = config.sample_rate;
3709 outputDesc->mChannelMask = config.channel_mask;
3710 outputDesc->mFormat = config.format;
3711
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003712 for (size_t k = 0; k < supportedDevices.size(); k++) {
3713 ssize_t index = mAvailableOutputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003714 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003715 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
3716 mAvailableOutputDevices[index]->attach(mHwModules[i]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003717 }
3718 }
3719 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003720 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003721 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003722 }
3723 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003724 setOutputDevice(outputDesc,
Eric Laurentd78f1532014-09-16 16:38:20 -07003725 outputDesc->mDevice,
Eric Laurentc40d9692016-04-13 19:14:13 -07003726 true,
3727 0,
3728 NULL,
3729 address.string());
Eric Laurentd78f1532014-09-16 16:38:20 -07003730 }
Eric Laurente552edb2014-03-10 17:42:56 -07003731 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003732 // open input streams needed to access attached devices to validate
3733 // mAvailableInputDevices list
3734 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3735 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003736 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003737
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003738 if (!inProfile->hasSupportedDevices()) {
3739 ALOGW("Input profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003740 continue;
3741 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003742 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003743 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003744 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
3745
Eric Laurentd78f1532014-09-16 16:38:20 -07003746 if ((profileType & inputDeviceTypes) == 0) {
3747 continue;
3748 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08003749 sp<AudioInputDescriptor> inputDesc =
3750 new AudioInputDescriptor(inProfile);
Eric Laurentd78f1532014-09-16 16:38:20 -07003751
Eric Laurentd78f1532014-09-16 16:38:20 -07003752 inputDesc->mDevice = profileType;
3753
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003754 // find the address
3755 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
3756 // the inputs vector must be of size 1, but we don't want to crash here
3757 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3758 : String8("");
3759 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
3760 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
3761
Eric Laurentd78f1532014-09-16 16:38:20 -07003762 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3763 config.sample_rate = inputDesc->mSamplingRate;
3764 config.channel_mask = inputDesc->mChannelMask;
3765 config.format = inputDesc->mFormat;
3766 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003767 status_t status = mpClientInterface->openInput(inProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003768 &input,
3769 &config,
3770 &inputDesc->mDevice,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003771 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003772 AUDIO_SOURCE_MIC,
3773 AUDIO_INPUT_FLAG_NONE);
3774
3775 if (status == NO_ERROR) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003776 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
3777 for (size_t k = 0; k < supportedDevices.size(); k++) {
3778 ssize_t index = mAvailableInputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003779 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07003780 if (index >= 0) {
3781 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
3782 if (!devDesc->isAttached()) {
3783 devDesc->attach(mHwModules[i]);
Eric Laurent83efe1c2017-07-09 16:51:08 -07003784 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07003785 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003786 }
3787 }
3788 mpClientInterface->closeInput(input);
3789 } else {
3790 ALOGW("Cannot open input stream for device %08x on hw module %s",
3791 inputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003792 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003793 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003794 }
3795 }
3796 // make sure all attached devices have been allocated a unique ID
3797 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003798 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003799 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003800 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
3801 continue;
3802 }
François Gaffie2110e042015-03-24 08:41:51 +01003803 // The device is now validated and can be appended to the available devices of the engine
3804 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
3805 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003806 i++;
3807 }
3808 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003809 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01003810 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003811 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
3812 continue;
3813 }
François Gaffie2110e042015-03-24 08:41:51 +01003814 // The device is now validated and can be appended to the available devices of the engine
3815 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
3816 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003817 i++;
3818 }
3819 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003820 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01003821 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003822 }
Eric Laurente552edb2014-03-10 17:42:56 -07003823
3824 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
3825
3826 updateDevicesAndOutputs();
3827
3828#ifdef AUDIO_POLICY_TEST
3829 if (mPrimaryOutput != 0) {
3830 AudioParameter outputCmd = AudioParameter();
3831 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07003832 mpClientInterface->setParameters(mPrimaryOutput->mIoHandle, outputCmd.toString());
Eric Laurente552edb2014-03-10 17:42:56 -07003833
3834 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
3835 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07003836 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
3837 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003838 mTestLatencyMs = 0;
3839 mCurOutput = 0;
3840 mDirectOutput = false;
3841 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3842 mTestOutputs[i] = 0;
3843 }
3844
3845 const size_t SIZE = 256;
3846 char buffer[SIZE];
3847 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
3848 run(buffer, ANDROID_PRIORITY_AUDIO);
3849 }
3850#endif //AUDIO_POLICY_TEST
3851}
3852
Eric Laurente0720872014-03-11 09:30:41 -07003853AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07003854{
3855#ifdef AUDIO_POLICY_TEST
3856 exit();
3857#endif //AUDIO_POLICY_TEST
3858 for (size_t i = 0; i < mOutputs.size(); i++) {
3859 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003860 }
3861 for (size_t i = 0; i < mInputs.size(); i++) {
3862 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003863 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003864 mAvailableOutputDevices.clear();
3865 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003866 mOutputs.clear();
3867 mInputs.clear();
3868 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07003869}
3870
Eric Laurente0720872014-03-11 09:30:41 -07003871status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07003872{
Eric Laurent87ffa392015-05-22 10:32:38 -07003873 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003874}
3875
3876#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07003877bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07003878{
3879 ALOGV("entering threadLoop()");
3880 while (!exitPending())
3881 {
3882 String8 command;
3883 int valueInt;
3884 String8 value;
3885
3886 Mutex::Autolock _l(mLock);
3887 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
3888
3889 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
3890 AudioParameter param = AudioParameter(command);
3891
3892 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
3893 valueInt != 0) {
3894 ALOGV("Test command %s received", command.string());
3895 String8 target;
3896 if (param.get(String8("target"), target) != NO_ERROR) {
3897 target = "Manager";
3898 }
3899 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
3900 param.remove(String8("test_cmd_policy_output"));
3901 mCurOutput = valueInt;
3902 }
3903 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
3904 param.remove(String8("test_cmd_policy_direct"));
3905 if (value == "false") {
3906 mDirectOutput = false;
3907 } else if (value == "true") {
3908 mDirectOutput = true;
3909 }
3910 }
3911 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
3912 param.remove(String8("test_cmd_policy_input"));
3913 mTestInput = valueInt;
3914 }
3915
3916 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
3917 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07003918 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07003919 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003920 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003921 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003922 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003923 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003924 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07003925 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003926 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07003927 if (target == "Manager") {
3928 mTestFormat = format;
3929 } else if (mTestOutputs[mCurOutput] != 0) {
3930 AudioParameter outputParam = AudioParameter();
Mikhail Naganov388360c2016-10-17 17:09:41 -07003931 outputParam.addInt(String8(AudioParameter::keyStreamSupportedFormats), format);
Eric Laurente552edb2014-03-10 17:42:56 -07003932 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3933 }
3934 }
3935 }
3936 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
3937 param.remove(String8("test_cmd_policy_channels"));
3938 int channels = 0;
3939
3940 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003941 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003942 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003943 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07003944 }
3945 if (channels != 0) {
3946 if (target == "Manager") {
3947 mTestChannels = channels;
3948 } else if (mTestOutputs[mCurOutput] != 0) {
3949 AudioParameter outputParam = AudioParameter();
Mikhail Naganov388360c2016-10-17 17:09:41 -07003950 outputParam.addInt(String8(AudioParameter::keyStreamSupportedChannels), channels);
Eric Laurente552edb2014-03-10 17:42:56 -07003951 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3952 }
3953 }
3954 }
3955 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
3956 param.remove(String8("test_cmd_policy_sampleRate"));
3957 if (valueInt >= 0 && valueInt <= 96000) {
3958 int samplingRate = valueInt;
3959 if (target == "Manager") {
3960 mTestSamplingRate = samplingRate;
3961 } else if (mTestOutputs[mCurOutput] != 0) {
3962 AudioParameter outputParam = AudioParameter();
Mikhail Naganov388360c2016-10-17 17:09:41 -07003963 outputParam.addInt(String8(AudioParameter::keyStreamSupportedSamplingRates), samplingRate);
Eric Laurente552edb2014-03-10 17:42:56 -07003964 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3965 }
3966 }
3967 }
3968
3969 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
3970 param.remove(String8("test_cmd_policy_reopen"));
3971
Eric Laurentc75307b2015-03-17 15:29:32 -07003972 mpClientInterface->closeOutput(mpClientInterface->closeOutput(mPrimaryOutput););
Eric Laurente552edb2014-03-10 17:42:56 -07003973
Eric Laurentc75307b2015-03-17 15:29:32 -07003974 audio_module_handle_t moduleHandle = mPrimaryOutput->getModuleHandle();
Eric Laurente552edb2014-03-10 17:42:56 -07003975
Eric Laurentc75307b2015-03-17 15:29:32 -07003976 removeOutput(mPrimaryOutput->mIoHandle);
3977 sp<SwAudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL,
3978 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07003979 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003980 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3981 config.sample_rate = outputDesc->mSamplingRate;
3982 config.channel_mask = outputDesc->mChannelMask;
3983 config.format = outputDesc->mFormat;
Eric Laurentc75307b2015-03-17 15:29:32 -07003984 audio_io_handle_t handle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003985 status_t status = mpClientInterface->openOutput(moduleHandle,
Eric Laurentc75307b2015-03-17 15:29:32 -07003986 &handle,
Eric Laurentcf2c0212014-07-25 16:20:43 -07003987 &config,
3988 &outputDesc->mDevice,
3989 String8(""),
3990 &outputDesc->mLatency,
3991 outputDesc->mFlags);
3992 if (status != NO_ERROR) {
3993 ALOGE("Failed to reopen hardware output stream, "
3994 "samplingRate: %d, format %d, channels %d",
3995 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07003996 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003997 outputDesc->mSamplingRate = config.sample_rate;
3998 outputDesc->mChannelMask = config.channel_mask;
3999 outputDesc->mFormat = config.format;
Eric Laurentc75307b2015-03-17 15:29:32 -07004000 mPrimaryOutput = outputDesc;
Eric Laurente552edb2014-03-10 17:42:56 -07004001 AudioParameter outputCmd = AudioParameter();
4002 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07004003 mpClientInterface->setParameters(handle, outputCmd.toString());
4004 addOutput(handle, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07004005 }
4006 }
4007
4008
4009 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
4010 }
4011 }
4012 return false;
4013}
4014
Eric Laurente0720872014-03-11 09:30:41 -07004015void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07004016{
4017 {
4018 AutoMutex _l(mLock);
4019 requestExit();
4020 mWaitWorkCV.signal();
4021 }
4022 requestExitAndWait();
4023}
4024
Eric Laurente0720872014-03-11 09:30:41 -07004025int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004026{
4027 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
4028 if (output == mTestOutputs[i]) return i;
4029 }
4030 return 0;
4031}
4032#endif //AUDIO_POLICY_TEST
4033
4034// ---
4035
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004036void AudioPolicyManager::addOutput(audio_io_handle_t output, const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004037{
François Gaffie98cc1912015-03-18 17:52:40 +01004038 outputDesc->setIoHandle(output);
Eric Laurent1c333e22014-05-20 10:48:17 -07004039 mOutputs.add(output, outputDesc);
Andy Hung2ddee192015-12-18 17:34:44 -08004040 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004041 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004042 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004043}
4044
François Gaffie53615e22015-03-19 09:24:12 +01004045void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4046{
4047 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004048 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004049}
4050
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004051void AudioPolicyManager::addInput(audio_io_handle_t input, const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004052{
François Gaffie98cc1912015-03-18 17:52:40 +01004053 inputDesc->setIoHandle(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004054 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004055 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004056}
Eric Laurente552edb2014-03-10 17:42:56 -07004057
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004058void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08004059 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004060 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004061 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08004062 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004063 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08004064 if (devDesc != 0) {
4065 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
4066 desc->mIoHandle, address.string());
4067 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004068 }
4069}
4070
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004071status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004072 audio_policy_dev_state_t state,
4073 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004074 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07004075{
François Gaffie53615e22015-03-19 09:24:12 +01004076 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07004077 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004078
4079 if (audio_device_is_digital(device)) {
4080 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004081 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004082 }
Eric Laurente552edb2014-03-10 17:42:56 -07004083
Eric Laurent3b73df72014-03-11 09:06:29 -07004084 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004085 // first list already open outputs that can be routed to this device
4086 for (size_t i = 0; i < mOutputs.size(); i++) {
4087 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07004088 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004089 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004090 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
4091 outputs.add(mOutputs.keyAt(i));
4092 } else {
4093 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08004094 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004095 }
Eric Laurente552edb2014-03-10 17:42:56 -07004096 }
4097 }
4098 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004099 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07004100 for (size_t i = 0; i < mHwModules.size(); i++)
4101 {
4102 if (mHwModules[i]->mHandle == 0) {
4103 continue;
4104 }
4105 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
4106 {
Eric Laurent275e8e92014-11-30 15:14:47 -08004107 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004108 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004109 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004110 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004111 profiles.add(profile);
4112 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
4113 }
Eric Laurente552edb2014-03-10 17:42:56 -07004114 }
4115 }
4116 }
4117
Eric Laurent7b279bb2015-12-14 10:18:23 -08004118 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004119
Eric Laurente552edb2014-03-10 17:42:56 -07004120 if (profiles.isEmpty() && outputs.isEmpty()) {
4121 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4122 return BAD_VALUE;
4123 }
4124
4125 // open outputs for matching profiles if needed. Direct outputs are also opened to
4126 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4127 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004128 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004129
4130 // nothing to do if one output is already opened for this profile
4131 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004132 for (j = 0; j < outputs.size(); j++) {
4133 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004134 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004135 // matching profile: save the sample rates, format and channel masks supported
4136 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07004137 if (audio_device_is_digital(device)) {
4138 devDesc->importAudioPort(profile);
4139 }
Eric Laurente552edb2014-03-10 17:42:56 -07004140 break;
4141 }
4142 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004143 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004144 continue;
4145 }
4146
Eric Laurent83efe1c2017-07-09 16:51:08 -07004147 ALOGV("opening output for device %08x with params %s profile %p name %s",
4148 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004149 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07004150 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07004151 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4152 config.sample_rate = desc->mSamplingRate;
4153 config.channel_mask = desc->mChannelMask;
4154 config.format = desc->mFormat;
4155 config.offload_info.sample_rate = desc->mSamplingRate;
4156 config.offload_info.channel_mask = desc->mChannelMask;
4157 config.offload_info.format = desc->mFormat;
4158 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07004159 status_t status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07004160 &output,
4161 &config,
4162 &desc->mDevice,
4163 address,
4164 &desc->mLatency,
4165 desc->mFlags);
4166 if (status == NO_ERROR) {
4167 desc->mSamplingRate = config.sample_rate;
4168 desc->mChannelMask = config.channel_mask;
4169 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07004170
Eric Laurentd4692962014-05-05 18:13:44 -07004171 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004172 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004173 char *param = audio_device_address_to_parameter(device, address);
4174 mpClientInterface->setParameters(output, String8(param));
4175 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004176 }
Phil Burk00eeb322016-03-31 12:41:00 -07004177 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004178 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004179 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07004180 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004181 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004182 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004183 mpClientInterface->closeOutput(output);
Phil Burk702b1052016-03-02 16:38:26 -08004184 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004185 profile->pickAudioProfile(config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004186 config.offload_info.sample_rate = config.sample_rate;
4187 config.offload_info.channel_mask = config.channel_mask;
4188 config.offload_info.format = config.format;
Eric Laurent322b4d22015-04-03 15:57:54 -07004189 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07004190 &output,
4191 &config,
4192 &desc->mDevice,
4193 address,
4194 &desc->mLatency,
4195 desc->mFlags);
4196 if (status == NO_ERROR) {
4197 desc->mSamplingRate = config.sample_rate;
4198 desc->mChannelMask = config.channel_mask;
4199 desc->mFormat = config.format;
4200 } else {
4201 output = AUDIO_IO_HANDLE_NONE;
4202 }
Eric Laurentd4692962014-05-05 18:13:44 -07004203 }
4204
Eric Laurentcf2c0212014-07-25 16:20:43 -07004205 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004206 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01004207 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004208 sp<AudioPolicyMix> policyMix;
4209 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004210 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
4211 address.string());
4212 }
François Gaffie036e1e92015-03-19 10:16:24 +01004213 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07004214 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01004215
Eric Laurent87ffa392015-05-22 10:32:38 -07004216 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4217 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004218 // no duplicated output for direct outputs and
4219 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004220 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004221
Eric Laurentd4692962014-05-05 18:13:44 -07004222 // set initial stream volume for device
Eric Laurentc75307b2015-03-17 15:29:32 -07004223 applyStreamVolumes(desc, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07004224
Eric Laurentd4692962014-05-05 18:13:44 -07004225 //TODO: configure audio effect output stage here
4226
4227 // open a duplicating output thread for the new output and the primary output
Eric Laurentc75307b2015-03-17 15:29:32 -07004228 duplicatedOutput =
4229 mpClientInterface->openDuplicateOutput(output,
4230 mPrimaryOutput->mIoHandle);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004231 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004232 // add duplicated output descriptor
Eric Laurentc75307b2015-03-17 15:29:32 -07004233 sp<SwAudioOutputDescriptor> dupOutputDesc =
4234 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4235 dupOutputDesc->mOutput1 = mPrimaryOutput;
4236 dupOutputDesc->mOutput2 = desc;
Eric Laurentd4692962014-05-05 18:13:44 -07004237 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
4238 dupOutputDesc->mFormat = desc->mFormat;
4239 dupOutputDesc->mChannelMask = desc->mChannelMask;
4240 dupOutputDesc->mLatency = desc->mLatency;
4241 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07004242 applyStreamVolumes(dupOutputDesc, device, 0, true);
Eric Laurentd4692962014-05-05 18:13:44 -07004243 } else {
4244 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004245 mPrimaryOutput->mIoHandle, output);
Eric Laurentd4692962014-05-05 18:13:44 -07004246 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01004247 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004248 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004249 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004250 }
Eric Laurente552edb2014-03-10 17:42:56 -07004251 }
4252 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004253 } else {
4254 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004255 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004256 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004257 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004258 profiles.removeAt(profile_index);
4259 profile_index--;
4260 } else {
4261 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004262 // Load digital format info only for digital devices
4263 if (audio_device_is_digital(device)) {
4264 devDesc->importAudioPort(profile);
4265 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004266
François Gaffie53615e22015-03-19 09:24:12 +01004267 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004268 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4269 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004270 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004271 NULL/*patch handle*/, address.string());
4272 }
Eric Laurente552edb2014-03-10 17:42:56 -07004273 ALOGV("checkOutputsForDevice(): adding output %d", output);
4274 }
4275 }
4276
4277 if (profiles.isEmpty()) {
4278 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4279 return BAD_VALUE;
4280 }
Eric Laurentd4692962014-05-05 18:13:44 -07004281 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004282 // check if one opened output is not needed any more after disconnecting one device
4283 for (size_t i = 0; i < mOutputs.size(); i++) {
4284 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004285 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004286 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004287 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004288 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004289 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004290 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004291 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4292 mOutputs.keyAt(i));
4293 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004294 }
Eric Laurente552edb2014-03-10 17:42:56 -07004295 }
4296 }
Eric Laurentd4692962014-05-05 18:13:44 -07004297 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07004298 for (size_t i = 0; i < mHwModules.size(); i++)
4299 {
4300 if (mHwModules[i]->mHandle == 0) {
4301 continue;
4302 }
4303 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
4304 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004305 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004306 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004307 ALOGV("checkOutputsForDevice(): "
4308 "clearing direct output profile %zu on module %zu", j, i);
François Gaffie112b0af2015-11-19 16:13:25 +01004309 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004310 }
4311 }
4312 }
4313 }
4314 return NO_ERROR;
4315}
4316
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004317status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004318 audio_policy_dev_state_t state,
4319 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004320 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004321{
Paul McLean9080a4c2015-06-18 08:24:02 -07004322 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004323 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004324
4325 if (audio_device_is_digital(device)) {
4326 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004327 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004328 }
4329
Eric Laurentd4692962014-05-05 18:13:44 -07004330 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4331 // first list already open inputs that can be routed to this device
4332 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4333 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004334 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004335 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4336 inputs.add(mInputs.keyAt(input_index));
4337 }
4338 }
4339
4340 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004341 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07004342 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
4343 {
4344 if (mHwModules[module_idx]->mHandle == 0) {
4345 continue;
4346 }
4347 for (size_t profile_index = 0;
4348 profile_index < mHwModules[module_idx]->mInputProfiles.size();
4349 profile_index++)
4350 {
Eric Laurent275e8e92014-11-30 15:14:47 -08004351 sp<IOProfile> profile = mHwModules[module_idx]->mInputProfiles[profile_index];
4352
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004353 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004354 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004355 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004356 profiles.add(profile);
4357 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
4358 profile_index, module_idx);
4359 }
Eric Laurentd4692962014-05-05 18:13:44 -07004360 }
4361 }
4362 }
4363
4364 if (profiles.isEmpty() && inputs.isEmpty()) {
4365 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4366 return BAD_VALUE;
4367 }
4368
4369 // open inputs for matching profiles if needed. Direct inputs are also opened to
4370 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4371 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4372
Eric Laurent1c333e22014-05-20 10:48:17 -07004373 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07004374 // nothing to do if one input is already opened for this profile
4375 size_t input_index;
4376 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4377 desc = mInputs.valueAt(input_index);
4378 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004379 if (audio_device_is_digital(device)) {
4380 devDesc->importAudioPort(profile);
4381 }
Eric Laurentd4692962014-05-05 18:13:44 -07004382 break;
4383 }
4384 }
4385 if (input_index != mInputs.size()) {
4386 continue;
4387 }
4388
4389 ALOGV("opening input for device 0x%X with params %s", device, address.string());
4390 desc = new AudioInputDescriptor(profile);
4391 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07004392 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4393 config.sample_rate = desc->mSamplingRate;
4394 config.channel_mask = desc->mChannelMask;
4395 config.format = desc->mFormat;
4396 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent83efe1c2017-07-09 16:51:08 -07004397
4398 ALOGV("opening inputput for device %08x with params %s profile %p name %s",
4399 desc->mDevice, address.string(), profile.get(), profile->getName().string());
4400
Eric Laurent322b4d22015-04-03 15:57:54 -07004401 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07004402 &input,
4403 &config,
4404 &desc->mDevice,
4405 address,
4406 AUDIO_SOURCE_MIC,
4407 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07004408
Eric Laurentcf2c0212014-07-25 16:20:43 -07004409 if (status == NO_ERROR) {
4410 desc->mSamplingRate = config.sample_rate;
4411 desc->mChannelMask = config.channel_mask;
4412 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07004413
Eric Laurentd4692962014-05-05 18:13:44 -07004414 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004415 char *param = audio_device_address_to_parameter(device, address);
4416 mpClientInterface->setParameters(input, String8(param));
4417 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004418 }
Phil Burk00eeb322016-03-31 12:41:00 -07004419 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004420 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004421 ALOGW("checkInputsForDevice() direct input missing param");
4422 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004423 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004424 }
4425
4426 if (input != 0) {
4427 addInput(input, desc);
4428 }
4429 } // endif input != 0
4430
Eric Laurentcf2c0212014-07-25 16:20:43 -07004431 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004432 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004433 profiles.removeAt(profile_index);
4434 profile_index--;
4435 } else {
4436 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004437 if (audio_device_is_digital(device)) {
4438 devDesc->importAudioPort(profile);
4439 }
Eric Laurentd4692962014-05-05 18:13:44 -07004440 ALOGV("checkInputsForDevice(): adding input %d", input);
4441 }
4442 } // end scan profiles
4443
4444 if (profiles.isEmpty()) {
4445 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4446 return BAD_VALUE;
4447 }
4448 } else {
4449 // Disconnect
4450 // check if one opened input is not needed any more after disconnecting one device
4451 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4452 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004453 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004454 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4455 mInputs.keyAt(input_index));
4456 inputs.add(mInputs.keyAt(input_index));
4457 }
4458 }
4459 // Clear any profiles associated with the disconnected device.
4460 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
4461 if (mHwModules[module_index]->mHandle == 0) {
4462 continue;
4463 }
4464 for (size_t profile_index = 0;
4465 profile_index < mHwModules[module_index]->mInputProfiles.size();
4466 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004467 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004468 if (profile->supportDevice(device)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004469 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07004470 profile_index, module_index);
François Gaffie112b0af2015-11-19 16:13:25 +01004471 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004472 }
4473 }
4474 }
4475 } // end disconnect
4476
4477 return NO_ERROR;
4478}
4479
4480
Eric Laurente0720872014-03-11 09:30:41 -07004481void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004482{
4483 ALOGV("closeOutput(%d)", output);
4484
Eric Laurentc75307b2015-03-17 15:29:32 -07004485 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004486 if (outputDesc == NULL) {
4487 ALOGW("closeOutput() unknown output %d", output);
4488 return;
4489 }
François Gaffie036e1e92015-03-19 10:16:24 +01004490 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004491
Eric Laurente552edb2014-03-10 17:42:56 -07004492 // look for duplicated outputs connected to the output being removed.
4493 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004494 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004495 if (dupOutputDesc->isDuplicated() &&
4496 (dupOutputDesc->mOutput1 == outputDesc ||
4497 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004498 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004499 if (dupOutputDesc->mOutput1 == outputDesc) {
4500 outputDesc2 = dupOutputDesc->mOutput2;
4501 } else {
4502 outputDesc2 = dupOutputDesc->mOutput1;
4503 }
4504 // As all active tracks on duplicated output will be deleted,
4505 // and as they were also referenced on the other output, the reference
4506 // count for their stream type must be adjusted accordingly on
4507 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07004508 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004509 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07004510 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004511 }
4512 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4513 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4514
4515 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004516 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004517 }
4518 }
4519
Eric Laurent05b90f82014-08-27 15:32:29 -07004520 nextAudioPortGeneration();
4521
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004522 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004523 if (index >= 0) {
4524 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004525 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004526 mAudioPatches.removeItemsAt(index);
4527 mpClientInterface->onAudioPatchListUpdate();
4528 }
4529
Eric Laurente552edb2014-03-10 17:42:56 -07004530 AudioParameter param;
4531 param.add(String8("closing"), String8("true"));
4532 mpClientInterface->setParameters(output, param.toString());
4533
4534 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01004535 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004536 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004537}
4538
4539void AudioPolicyManager::closeInput(audio_io_handle_t input)
4540{
4541 ALOGV("closeInput(%d)", input);
4542
4543 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4544 if (inputDesc == NULL) {
4545 ALOGW("closeInput() unknown input %d", input);
4546 return;
4547 }
4548
Eric Laurent6a94d692014-05-20 11:18:06 -07004549 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004550
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004551 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004552 if (index >= 0) {
4553 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004554 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004555 mAudioPatches.removeItemsAt(index);
4556 mpClientInterface->onAudioPatchListUpdate();
4557 }
4558
4559 mpClientInterface->closeInput(input);
4560 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004561}
4562
Eric Laurentc75307b2015-03-17 15:29:32 -07004563SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4564 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004565 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004566{
4567 SortedVector<audio_io_handle_t> outputs;
4568
4569 ALOGVV("getOutputsForDevice() device %04x", device);
4570 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004571 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004572 i, openOutputs.valueAt(i)->isDuplicated(),
4573 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004574 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4575 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4576 outputs.add(openOutputs.keyAt(i));
4577 }
4578 }
4579 return outputs;
4580}
4581
Eric Laurente0720872014-03-11 09:30:41 -07004582bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
François Gaffie53615e22015-03-19 09:24:12 +01004583 SortedVector<audio_io_handle_t>& outputs2)
Eric Laurente552edb2014-03-10 17:42:56 -07004584{
4585 if (outputs1.size() != outputs2.size()) {
4586 return false;
4587 }
4588 for (size_t i = 0; i < outputs1.size(); i++) {
4589 if (outputs1[i] != outputs2[i]) {
4590 return false;
4591 }
4592 }
4593 return true;
4594}
4595
Eric Laurente0720872014-03-11 09:30:41 -07004596void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004597{
4598 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4599 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4600 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4601 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4602
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004603 // also take into account external policy-related changes: add all outputs which are
4604 // associated with policies in the "before" and "after" output vectors
4605 ALOGVV("checkOutputForStrategy(): policy related outputs");
4606 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004607 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004608 if (desc != 0 && desc->mPolicyMix != NULL) {
4609 srcOutputs.add(desc->mIoHandle);
4610 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4611 }
4612 }
4613 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004614 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004615 if (desc != 0 && desc->mPolicyMix != NULL) {
4616 dstOutputs.add(desc->mIoHandle);
4617 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4618 }
4619 }
4620
Eric Laurente552edb2014-03-10 17:42:56 -07004621 if (!vectorsEqual(srcOutputs,dstOutputs)) {
4622 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4623 strategy, srcOutputs[0], dstOutputs[0]);
4624 // mute strategy while moving tracks from one output to another
4625 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004626 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
François Gaffiead3183e2015-03-18 16:55:35 +01004627 if (isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004628 setStrategyMute(strategy, true, desc);
4629 setStrategyMute(strategy, false, desc, MUTE_TIME_MS, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004630 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004631 sp<AudioSourceDescriptor> source =
4632 getSourceForStrategyOnOutput(srcOutputs[i], strategy);
4633 if (source != 0){
4634 connectAudioSource(source);
4635 }
Eric Laurente552edb2014-03-10 17:42:56 -07004636 }
4637
4638 // Move effects associated to this strategy from previous output to new output
4639 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004640 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004641 }
4642 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004643 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004644 if (getStrategy((audio_stream_type_t)i) == strategy) {
4645 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004646 }
4647 }
4648 }
4649}
4650
Eric Laurente0720872014-03-11 09:30:41 -07004651void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004652{
François Gaffie2110e042015-03-24 08:41:51 +01004653 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004654 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004655 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004656 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004657 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004658 checkOutputForStrategy(STRATEGY_SONIFICATION);
4659 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004660 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004661 checkOutputForStrategy(STRATEGY_MEDIA);
4662 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004663 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004664}
4665
Eric Laurente0720872014-03-11 09:30:41 -07004666void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004667{
François Gaffie53615e22015-03-19 09:24:12 +01004668 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Eric Laurente552edb2014-03-10 17:42:56 -07004669 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004670 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004671 return;
4672 }
4673
Eric Laurent3a4311c2014-03-17 12:00:47 -07004674 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004675 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4676 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4677 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004678
4679 // if suspended, restore A2DP output if:
4680 // ((SCO device is NOT connected) ||
4681 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4682 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004683 //
Eric Laurentf732e072016-08-03 19:30:28 -07004684 // if not suspended, suspend A2DP output if:
4685 // (SCO device is connected) &&
4686 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4687 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004688 //
4689 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004690 if (!isScoConnected ||
4691 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4692 AUDIO_POLICY_FORCE_BT_SCO) &&
4693 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4694 AUDIO_POLICY_FORCE_BT_SCO) &&
4695 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004696 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004697
4698 mpClientInterface->restoreOutput(a2dpOutput);
4699 mA2dpSuspended = false;
4700 }
4701 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004702 if (isScoConnected &&
4703 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4704 AUDIO_POLICY_FORCE_BT_SCO) ||
4705 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4706 AUDIO_POLICY_FORCE_BT_SCO) ||
4707 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004708 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004709
4710 mpClientInterface->suspendOutput(a2dpOutput);
4711 mA2dpSuspended = true;
4712 }
4713 }
4714}
4715
Eric Laurentc75307b2015-03-17 15:29:32 -07004716audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4717 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004718{
4719 audio_devices_t device = AUDIO_DEVICE_NONE;
4720
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004721 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004722 if (index >= 0) {
4723 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4724 if (patchDesc->mUid != mUidCached) {
4725 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004726 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004727 return outputDesc->device();
4728 }
4729 }
4730
Eric Laurente552edb2014-03-10 17:42:56 -07004731 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004732 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004733 // use device for strategy enforced audible
4734 // 2: we are in call or the strategy phone is active on the output:
4735 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004736 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004737 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004738 // 4: the strategy for enforced audible is active but not enforced on the output:
4739 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004740 // 5: the strategy accessibility is active on the output:
4741 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004742 // 6: the strategy "respectful" sonification is active on the output:
4743 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004744 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004745 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004746 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004747 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004748 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004749 // use device for strategy t-t-s
François Gaffiead3183e2015-03-18 16:55:35 +01004750 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004751 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004752 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4753 } else if (isInCall() ||
François Gaffiead3183e2015-03-18 16:55:35 +01004754 isStrategyActive(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004755 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004756 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004757 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004758 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
4759 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004760 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4761 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004762 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004763 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004764 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004765 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004766 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004767 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004768 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004769 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004770 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004771 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004772 }
4773
Eric Laurent1c333e22014-05-20 10:48:17 -07004774 ALOGV("getNewOutputDevice() selected device %x", device);
4775 return device;
4776}
4777
Eric Laurentfb66dd92016-01-28 18:32:03 -08004778audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004779{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004780 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004781
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004782 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004783 if (index >= 0) {
4784 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4785 if (patchDesc->mUid != mUidCached) {
4786 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004787 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004788 return inputDesc->mDevice;
4789 }
4790 }
4791
Eric Laurentfb66dd92016-01-28 18:32:03 -08004792 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
4793 if (isInCall()) {
4794 device = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
4795 } else if (source != AUDIO_SOURCE_DEFAULT) {
4796 device = getDeviceAndMixForInputSource(source);
4797 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004798
Eric Laurente552edb2014-03-10 17:42:56 -07004799 return device;
4800}
4801
Eric Laurent794fde22016-03-11 09:50:45 -08004802bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4803 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004804 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004805}
4806
Eric Laurente0720872014-03-11 09:30:41 -07004807uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004808 return (uint32_t)getStrategy(stream);
4809}
4810
Eric Laurente0720872014-03-11 09:30:41 -07004811audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004812 // By checking the range of stream before calling getStrategy, we avoid
4813 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4814 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004815 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004816 return AUDIO_DEVICE_NONE;
4817 }
Eric Laurent28d09f02016-03-08 10:43:05 -08004818 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004819 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4820 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004821 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004822 }
Eric Laurent794fde22016-03-11 09:50:45 -08004823 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004824 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004825 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Eric Laurent28d09f02016-03-08 10:43:05 -08004826 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(curDevices, mOutputs);
4827 for (size_t i = 0; i < outputs.size(); i++) {
4828 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent794fde22016-03-11 09:50:45 -08004829 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004830 curDevices |= outputDesc->device();
4831 }
4832 }
4833 devices |= curDevices;
Eric Laurente552edb2014-03-10 17:42:56 -07004834 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004835
4836 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4837 and doesn't really need to.*/
4838 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4839 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4840 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4841 }
Eric Laurente552edb2014-03-10 17:42:56 -07004842 return devices;
4843}
4844
François Gaffie2110e042015-03-24 08:41:51 +01004845routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4846{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004847 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004848 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004849}
4850
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004851uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4852 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004853 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4854 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4855 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004856 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4857 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4858 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004859 // usage to strategy mapping
François Gaffie2110e042015-03-24 08:41:51 +01004860 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004861}
4862
Eric Laurente0720872014-03-11 09:30:41 -07004863void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004864 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004865 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004866 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4867 updateDevicesAndOutputs();
4868 break;
4869 default:
4870 break;
4871 }
4872}
4873
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004874uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004875
4876 // skip beacon mute management if a dedicated TTS output is available
4877 if (mTtsOutputAvailable) {
4878 return 0;
4879 }
4880
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004881 switch(event) {
4882 case STARTING_OUTPUT:
4883 mBeaconMuteRefCount++;
4884 break;
4885 case STOPPING_OUTPUT:
4886 if (mBeaconMuteRefCount > 0) {
4887 mBeaconMuteRefCount--;
4888 }
4889 break;
4890 case STARTING_BEACON:
4891 mBeaconPlayingRefCount++;
4892 break;
4893 case STOPPING_BEACON:
4894 if (mBeaconPlayingRefCount > 0) {
4895 mBeaconPlayingRefCount--;
4896 }
4897 break;
4898 }
4899
4900 if (mBeaconMuteRefCount > 0) {
4901 // any playback causes beacon to be muted
4902 return setBeaconMute(true);
4903 } else {
4904 // no other playback: unmute when beacon starts playing, mute when it stops
4905 return setBeaconMute(mBeaconPlayingRefCount == 0);
4906 }
4907}
4908
4909uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4910 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4911 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4912 // keep track of muted state to avoid repeating mute/unmute operations
4913 if (mBeaconMuted != mute) {
4914 // mute/unmute AUDIO_STREAM_TTS on all outputs
4915 ALOGV("\t muting %d", mute);
4916 uint32_t maxLatency = 0;
4917 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004918 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004919 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07004920 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004921 0 /*delay*/, AUDIO_DEVICE_NONE);
4922 const uint32_t latency = desc->latency() * 2;
4923 if (latency > maxLatency) {
4924 maxLatency = latency;
4925 }
4926 }
4927 mBeaconMuted = mute;
4928 return maxLatency;
4929 }
4930 return 0;
4931}
4932
Eric Laurente0720872014-03-11 09:30:41 -07004933audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01004934 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004935{
Paul McLeanaa981192015-03-21 09:55:15 -07004936 // Routing
4937 // see if we have an explicit route
4938 // scan the whole RouteMap, for each entry, convert the stream type to a strategy
4939 // (getStrategy(stream)).
4940 // if the strategy from the stream type in the RouteMap is the same as the argument above,
Eric Laurentad2e7b92017-09-14 20:06:42 -07004941 // and activity count is non-zero and the device in the route descriptor is available
4942 // then select this device.
Paul McLeanaa981192015-03-21 09:55:15 -07004943 for (size_t routeIndex = 0; routeIndex < mOutputRoutes.size(); routeIndex++) {
4944 sp<SessionRoute> route = mOutputRoutes.valueAt(routeIndex);
Eric Laurent28d09f02016-03-08 10:43:05 -08004945 routing_strategy routeStrategy = getStrategy(route->mStreamType);
Eric Laurentad2e7b92017-09-14 20:06:42 -07004946 if ((routeStrategy == strategy) && route->isActive() &&
4947 (mAvailableOutputDevices.indexOf(route->mDeviceDescriptor) >= 0)) {
Paul McLeanaa981192015-03-21 09:55:15 -07004948 return route->mDeviceDescriptor->type();
4949 }
4950 }
4951
Eric Laurente552edb2014-03-10 17:42:56 -07004952 if (fromCache) {
4953 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4954 strategy, mDeviceForStrategy[strategy]);
4955 return mDeviceForStrategy[strategy];
4956 }
François Gaffie2110e042015-03-24 08:41:51 +01004957 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07004958}
4959
Eric Laurente0720872014-03-11 09:30:41 -07004960void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004961{
4962 for (int i = 0; i < NUM_STRATEGIES; i++) {
4963 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4964 }
4965 mPreviousOutputs = mOutputs;
4966}
4967
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004968uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004969 audio_devices_t prevDevice,
4970 uint32_t delayMs)
4971{
4972 // mute/unmute strategies using an incompatible device combination
4973 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4974 // if unmuting, unmute only after the specified delay
4975 if (outputDesc->isDuplicated()) {
4976 return 0;
4977 }
4978
4979 uint32_t muteWaitMs = 0;
4980 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004981 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004982
4983 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4984 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07004985 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07004986 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4987 bool doMute = false;
4988
4989 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4990 doMute = true;
4991 outputDesc->mStrategyMutedByDevice[i] = true;
4992 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4993 doMute = true;
4994 outputDesc->mStrategyMutedByDevice[i] = false;
4995 }
Eric Laurent99401132014-05-07 19:48:15 -07004996 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004997 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004998 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004999 // skip output if it does not share any device with current output
5000 if ((desc->supportedDevices() & outputDesc->supportedDevices())
5001 == AUDIO_DEVICE_NONE) {
5002 continue;
5003 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005004 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07005005 mute ? "muting" : "unmuting", i, curDevice);
5006 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005007 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005008 if (mute) {
5009 // FIXME: should not need to double latency if volume could be applied
5010 // immediately by the audioflinger mixer. We must account for the delay
5011 // between now and the next time the audioflinger thread for this output
5012 // will process a buffer (which corresponds to one buffer size,
5013 // usually 1/2 or 1/4 of the latency).
5014 if (muteWaitMs < desc->latency() * 2) {
5015 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005016 }
5017 }
5018 }
5019 }
5020 }
5021 }
5022
Eric Laurent99401132014-05-07 19:48:15 -07005023 // temporary mute output if device selection changes to avoid volume bursts due to
5024 // different per device volumes
5025 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005026 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5027 // temporary mute duration is conservatively set to 4 times the reported latency
5028 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5029 if (muteWaitMs < tempMuteWaitMs) {
5030 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005031 }
Eric Laurentdc462862016-07-19 12:29:53 -07005032
Eric Laurent99401132014-05-07 19:48:15 -07005033 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005034 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005035 // make sure that we do not start the temporary mute period too early in case of
5036 // delayed device change
5037 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005038 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07005039 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07005040 }
5041 }
5042 }
5043
Eric Laurente552edb2014-03-10 17:42:56 -07005044 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5045 if (muteWaitMs > delayMs) {
5046 muteWaitMs -= delayMs;
5047 usleep(muteWaitMs * 1000);
5048 return muteWaitMs;
5049 }
5050 return 0;
5051}
5052
Eric Laurentc75307b2015-03-17 15:29:32 -07005053uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005054 audio_devices_t device,
5055 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07005056 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005057 audio_patch_handle_t *patchHandle,
5058 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07005059{
Eric Laurentc75307b2015-03-17 15:29:32 -07005060 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005061 AudioParameter param;
5062 uint32_t muteWaitMs;
5063
5064 if (outputDesc->isDuplicated()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005065 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs);
5066 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005067 return muteWaitMs;
5068 }
5069 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5070 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07005071 if ((device != AUDIO_DEVICE_NONE) &&
5072 ((device & outputDesc->supportedDevices()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005073 return 0;
5074 }
5075
5076 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07005077 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07005078
5079 audio_devices_t prevDevice = outputDesc->mDevice;
5080
Paul McLeanaa981192015-03-21 09:55:15 -07005081 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005082
5083 if (device != AUDIO_DEVICE_NONE) {
5084 outputDesc->mDevice = device;
5085 }
5086 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
5087
5088 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005089 // the requested device is AUDIO_DEVICE_NONE
5090 // OR the requested device is the same as current device
5091 // AND force is not specified
5092 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07005093 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07005094 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
5095 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005096 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005097 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005098 return muteWaitMs;
5099 }
5100
5101 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07005102
Eric Laurente552edb2014-03-10 17:42:56 -07005103 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07005104 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005105 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005106 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07005107 DeviceVector deviceList;
5108 if ((address == NULL) || (strlen(address) == 0)) {
5109 deviceList = mAvailableOutputDevices.getDevicesFromType(device);
5110 } else {
5111 deviceList = mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
5112 }
5113
Eric Laurent1c333e22014-05-20 10:48:17 -07005114 if (!deviceList.isEmpty()) {
5115 struct audio_patch patch;
5116 outputDesc->toAudioPortConfig(&patch.sources[0]);
5117 patch.num_sources = 1;
5118 patch.num_sinks = 0;
5119 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
5120 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07005121 patch.num_sinks++;
5122 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005123 ssize_t index;
5124 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
5125 index = mAudioPatches.indexOfKey(*patchHandle);
5126 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005127 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005128 }
5129 sp< AudioPatch> patchDesc;
5130 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
5131 if (index >= 0) {
5132 patchDesc = mAudioPatches.valueAt(index);
5133 afPatchHandle = patchDesc->mAfPatchHandle;
5134 }
5135
Eric Laurent1c333e22014-05-20 10:48:17 -07005136 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07005137 &afPatchHandle,
5138 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005139 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
5140 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07005141 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07005142 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005143 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01005144 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005145 addAudioPatch(patchDesc->mHandle, patchDesc);
5146 } else {
5147 patchDesc->mPatch = patch;
5148 }
5149 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07005150 if (patchHandle) {
5151 *patchHandle = patchDesc->mHandle;
5152 }
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005153 outputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005154 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005155 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005156 }
5157 }
bryant_liuf5e7e792014-08-19 20:07:05 +08005158
5159 // inform all input as well
5160 for (size_t i = 0; i < mInputs.size(); i++) {
5161 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01005162 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08005163 AudioParameter inputCmd = AudioParameter();
5164 ALOGV("%s: inform input %d of device:%d", __func__,
5165 inputDescriptor->mIoHandle, device);
5166 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
5167 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
5168 inputCmd.toString(),
5169 delayMs);
5170 }
5171 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005172 }
Eric Laurente552edb2014-03-10 17:42:56 -07005173
5174 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07005175 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005176
5177 return muteWaitMs;
5178}
5179
Eric Laurentc75307b2015-03-17 15:29:32 -07005180status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005181 int delayMs,
5182 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005183{
Eric Laurent6a94d692014-05-20 11:18:06 -07005184 ssize_t index;
5185 if (patchHandle) {
5186 index = mAudioPatches.indexOfKey(*patchHandle);
5187 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005188 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005189 }
5190 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005191 return INVALID_OPERATION;
5192 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005193 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5194 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005195 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005196 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005197 removeAudioPatch(patchDesc->mHandle);
5198 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005199 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005200 return status;
5201}
5202
5203status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5204 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005205 bool force,
5206 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005207{
5208 status_t status = NO_ERROR;
5209
Eric Laurent1f2f2232014-06-02 12:01:23 -07005210 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005211 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5212 inputDesc->mDevice = device;
5213
5214 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
5215 if (!deviceList.isEmpty()) {
5216 struct audio_patch patch;
5217 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005218 // AUDIO_SOURCE_HOTWORD is for internal use only:
5219 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005220 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
Eric Laurent599c7582015-12-07 18:05:55 -08005221 !inputDesc->isSoundTrigger()) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005222 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5223 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005224 patch.num_sinks = 1;
5225 //only one input device for now
5226 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07005227 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07005228 ssize_t index;
5229 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
5230 index = mAudioPatches.indexOfKey(*patchHandle);
5231 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005232 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005233 }
5234 sp< AudioPatch> patchDesc;
5235 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
5236 if (index >= 0) {
5237 patchDesc = mAudioPatches.valueAt(index);
5238 afPatchHandle = patchDesc->mAfPatchHandle;
5239 }
5240
Eric Laurent1c333e22014-05-20 10:48:17 -07005241 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07005242 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07005243 0);
5244 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07005245 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005246 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005247 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01005248 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005249 addAudioPatch(patchDesc->mHandle, patchDesc);
5250 } else {
5251 patchDesc->mPatch = patch;
5252 }
5253 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07005254 if (patchHandle) {
5255 *patchHandle = patchDesc->mHandle;
5256 }
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005257 inputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005258 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005259 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005260 }
5261 }
5262 }
5263 return status;
5264}
5265
Eric Laurent6a94d692014-05-20 11:18:06 -07005266status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5267 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005268{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005269 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005270 ssize_t index;
5271 if (patchHandle) {
5272 index = mAudioPatches.indexOfKey(*patchHandle);
5273 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005274 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005275 }
5276 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005277 return INVALID_OPERATION;
5278 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005279 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5280 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005281 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005282 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005283 removeAudioPatch(patchDesc->mHandle);
5284 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005285 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005286 return status;
5287}
5288
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005289sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005290 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005291 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005292 audio_format_t& format,
5293 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005294 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005295{
5296 // Choose an input profile based on the requested capture parameters: select the first available
5297 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005298 //
5299 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5300 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005301
5302 for (size_t i = 0; i < mHwModules.size(); i++)
5303 {
5304 if (mHwModules[i]->mHandle == 0) {
5305 continue;
5306 }
5307 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
5308 {
Eric Laurent1c333e22014-05-20 10:48:17 -07005309 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07005310 // profile->log();
Eric Laurent275e8e92014-11-30 15:14:47 -08005311 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07005312 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005313 format,
5314 &format /*updatedFormat*/,
5315 channelMask,
5316 &channelMask /*updatedChannelMask*/,
5317 (audio_output_flags_t) flags)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005318
Eric Laurente552edb2014-03-10 17:42:56 -07005319 return profile;
5320 }
5321 }
5322 }
5323 return NULL;
5324}
5325
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005326
5327audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005328 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005329{
François Gaffie036e1e92015-03-19 10:16:24 +01005330 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5331 audio_devices_t selectedDeviceFromMix =
5332 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005333
François Gaffie036e1e92015-03-19 10:16:24 +01005334 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5335 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005336 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005337 return getDeviceForInputSource(inputSource);
5338}
5339
5340audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5341{
Eric Laurentad2e7b92017-09-14 20:06:42 -07005342 // Routing
5343 // Scan the whole RouteMap to see if we have an explicit route:
5344 // if the input source in the RouteMap is the same as the argument above,
5345 // and activity count is non-zero and the device in the route descriptor is available
5346 // then select this device.
Paul McLean466dc8e2015-04-17 13:15:36 -06005347 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
5348 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
Eric Laurentad2e7b92017-09-14 20:06:42 -07005349 if ((inputSource == route->mSource) && route->isActive() &&
5350 (mAvailableInputDevices.indexOf(route->mDeviceDescriptor) >= 0)) {
Paul McLean466dc8e2015-04-17 13:15:36 -06005351 return route->mDeviceDescriptor->type();
5352 }
5353 }
5354
5355 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005356}
5357
Eric Laurente0720872014-03-11 09:30:41 -07005358float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005359 int index,
5360 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005361{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005362 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005363
5364 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5365 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5366 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5367 // the ringtone volume
5368 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5369 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5370 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5371 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5372 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5373 }
5374
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005375 // in-call: always cap earpiece volume by voice volume + some low headroom
5376 if ((stream != AUDIO_STREAM_VOICE_CALL) && (device & AUDIO_DEVICE_OUT_EARPIECE) && isInCall()) {
5377 switch (stream) {
5378 case AUDIO_STREAM_SYSTEM:
5379 case AUDIO_STREAM_RING:
5380 case AUDIO_STREAM_MUSIC:
5381 case AUDIO_STREAM_ALARM:
5382 case AUDIO_STREAM_NOTIFICATION:
5383 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5384 case AUDIO_STREAM_DTMF:
5385 case AUDIO_STREAM_ACCESSIBILITY: {
5386 const float maxVoiceVolDb = computeVolume(AUDIO_STREAM_VOICE_CALL, index, device)
5387 + IN_CALL_EARPIECE_HEADROOM_DB;
5388 if (volumeDB > maxVoiceVolDb) {
5389 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5390 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5391 volumeDB = maxVoiceVolDb;
5392 }
5393 } break;
5394 default:
5395 break;
5396 }
5397 }
5398
Eric Laurente552edb2014-03-10 17:42:56 -07005399 // if a headset is connected, apply the following rules to ring tones and notifications
5400 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005401 // - always attenuate notifications volume by 6dB
5402 // - attenuate ring tones volume by 6dB unless music is not playing and
5403 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005404 // - if music is playing, always limit the volume to current music volume,
5405 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005406 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005407 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5408 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5409 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005410 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
5411 AUDIO_DEVICE_OUT_USB_HEADSET)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005412 ((stream_strategy == STRATEGY_SONIFICATION)
5413 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005414 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005415 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005416 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005417 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005418 // when the phone is ringing we must consider that music could have been paused just before
5419 // by the music application and behave as if music was active if the last music track was
5420 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005421 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005422 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005423 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005424 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005425 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005426 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5427 musicDevice),
5428 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005429 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5430 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005431 if (volumeDB > minVolDB) {
5432 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005433 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005434 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005435 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5436 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5437 // on A2DP, also ensure notification volume is not too low compared to media when
5438 // intended to be played
5439 if ((volumeDB > -96.0f) &&
5440 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5441 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5442 stream, device,
5443 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5444 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5445 }
5446 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005447 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5448 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005449 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005450 }
5451 }
5452
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005453 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005454}
5455
Eric Laurente0720872014-03-11 09:30:41 -07005456status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005457 int index,
5458 const sp<AudioOutputDescriptor>& outputDesc,
5459 audio_devices_t device,
5460 int delayMs,
5461 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005462{
Eric Laurente552edb2014-03-10 17:42:56 -07005463 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005464 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005465 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005466 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005467 return NO_ERROR;
5468 }
François Gaffie2110e042015-03-24 08:41:51 +01005469 audio_policy_forced_cfg_t forceUseForComm =
5470 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005471 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005472 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5473 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005474 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005475 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005476 return INVALID_OPERATION;
5477 }
5478
Eric Laurentc75307b2015-03-17 15:29:32 -07005479 if (device == AUDIO_DEVICE_NONE) {
5480 device = outputDesc->device();
5481 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005482
Eric Laurentffbc80f2015-03-18 18:30:19 -07005483 float volumeDb = computeVolume(stream, index, device);
Eric Laurentc75307b2015-03-17 15:29:32 -07005484 if (outputDesc->isFixedVolume(device)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005485 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005486 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005487
Eric Laurentffbc80f2015-03-18 18:30:19 -07005488 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005489
Eric Laurent3b73df72014-03-11 09:06:29 -07005490 if (stream == AUDIO_STREAM_VOICE_CALL ||
5491 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005492 float voiceVolume;
5493 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005494 if (stream == AUDIO_STREAM_VOICE_CALL) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005495 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005496 } else {
5497 voiceVolume = 1.0;
5498 }
5499
Eric Laurent18fba842016-03-31 14:41:26 -07005500 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005501 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5502 mLastVoiceVolume = voiceVolume;
5503 }
5504 }
5505
5506 return NO_ERROR;
5507}
5508
Eric Laurentc75307b2015-03-17 15:29:32 -07005509void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5510 audio_devices_t device,
5511 int delayMs,
5512 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005513{
Eric Laurentc75307b2015-03-17 15:29:32 -07005514 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005515
Eric Laurent794fde22016-03-11 09:50:45 -08005516 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005517 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005518 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005519 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005520 device,
5521 delayMs,
5522 force);
5523 }
5524}
5525
Eric Laurente0720872014-03-11 09:30:41 -07005526void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005527 bool on,
5528 const sp<AudioOutputDescriptor>& outputDesc,
5529 int delayMs,
5530 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005531{
Eric Laurent72249d52015-06-08 11:12:15 -07005532 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5533 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005534 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005535 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005536 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005537 }
5538 }
5539}
5540
Eric Laurente0720872014-03-11 09:30:41 -07005541void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005542 bool on,
5543 const sp<AudioOutputDescriptor>& outputDesc,
5544 int delayMs,
5545 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005546{
Eric Laurente552edb2014-03-10 17:42:56 -07005547 if (device == AUDIO_DEVICE_NONE) {
5548 device = outputDesc->device();
5549 }
5550
Eric Laurentc75307b2015-03-17 15:29:32 -07005551 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5552 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005553
5554 if (on) {
5555 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005556 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005557 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005558 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005559 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005560 }
5561 }
5562 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5563 outputDesc->mMuteCount[stream]++;
5564 } else {
5565 if (outputDesc->mMuteCount[stream] == 0) {
5566 ALOGV("setStreamMute() unmuting non muted stream!");
5567 return;
5568 }
5569 if (--outputDesc->mMuteCount[stream] == 0) {
5570 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005571 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005572 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005573 device,
5574 delayMs);
5575 }
5576 }
5577}
5578
Eric Laurente0720872014-03-11 09:30:41 -07005579void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005580 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005581{
Eric Laurent87ffa392015-05-22 10:32:38 -07005582 if(!hasPrimaryOutput()) {
5583 return;
5584 }
5585
Eric Laurente552edb2014-03-10 17:42:56 -07005586 // if the stream pertains to sonification strategy and we are in call we must
5587 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5588 // in the device used for phone strategy and play the tone if the selected device does not
5589 // interfere with the device used for phone strategy
5590 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5591 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005592 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005593 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5594 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005595 sp<SwAudioOutputDescriptor> outputDesc = mPrimaryOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07005596 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5597 stream, starting, outputDesc->mDevice, stateChange);
5598 if (outputDesc->mRefCount[stream]) {
5599 int muteCount = 1;
5600 if (stateChange) {
5601 muteCount = outputDesc->mRefCount[stream];
5602 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005603 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005604 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5605 for (int i = 0; i < muteCount; i++) {
5606 setStreamMute(stream, starting, mPrimaryOutput);
5607 }
5608 } else {
5609 ALOGV("handleIncallSonification() high visibility");
5610 if (outputDesc->device() &
5611 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5612 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5613 for (int i = 0; i < muteCount; i++) {
5614 setStreamMute(stream, starting, mPrimaryOutput);
5615 }
5616 }
5617 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005618 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5619 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005620 } else {
5621 mpClientInterface->stopTone();
5622 }
5623 }
5624 }
5625 }
5626}
5627
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005628audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5629{
5630 // flags to stream type mapping
5631 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5632 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5633 }
5634 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5635 return AUDIO_STREAM_BLUETOOTH_SCO;
5636 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005637 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5638 return AUDIO_STREAM_TTS;
5639 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005640
5641 // usage to stream type mapping
5642 switch (attr->usage) {
5643 case AUDIO_USAGE_MEDIA:
5644 case AUDIO_USAGE_GAME:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005645 case AUDIO_USAGE_ASSISTANT:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005646 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5647 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005648 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5649 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005650 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5651 return AUDIO_STREAM_SYSTEM;
5652 case AUDIO_USAGE_VOICE_COMMUNICATION:
5653 return AUDIO_STREAM_VOICE_CALL;
5654
5655 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5656 return AUDIO_STREAM_DTMF;
5657
5658 case AUDIO_USAGE_ALARM:
5659 return AUDIO_STREAM_ALARM;
5660 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5661 return AUDIO_STREAM_RING;
5662
5663 case AUDIO_USAGE_NOTIFICATION:
5664 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5665 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5666 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5667 case AUDIO_USAGE_NOTIFICATION_EVENT:
5668 return AUDIO_STREAM_NOTIFICATION;
5669
5670 case AUDIO_USAGE_UNKNOWN:
5671 default:
5672 return AUDIO_STREAM_MUSIC;
5673 }
5674}
Eric Laurente83b55d2014-11-14 10:06:21 -08005675
François Gaffie53615e22015-03-19 09:24:12 +01005676bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5677{
Eric Laurente83b55d2014-11-14 10:06:21 -08005678 // has flags that map to a strategy?
5679 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5680 return true;
5681 }
5682
5683 // has known usage?
5684 switch (paa->usage) {
5685 case AUDIO_USAGE_UNKNOWN:
5686 case AUDIO_USAGE_MEDIA:
5687 case AUDIO_USAGE_VOICE_COMMUNICATION:
5688 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5689 case AUDIO_USAGE_ALARM:
5690 case AUDIO_USAGE_NOTIFICATION:
5691 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5692 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5693 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5694 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5695 case AUDIO_USAGE_NOTIFICATION_EVENT:
5696 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5697 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5698 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5699 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005700 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005701 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005702 break;
5703 default:
5704 return false;
5705 }
5706 return true;
5707}
5708
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005709bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005710 routing_strategy strategy, uint32_t inPastMs,
5711 nsecs_t sysTime) const
5712{
5713 if ((sysTime == 0) && (inPastMs != 0)) {
5714 sysTime = systemTime();
5715 }
Eric Laurent794fde22016-03-11 09:50:45 -08005716 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005717 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5718 (NUM_STRATEGIES == strategy)) &&
5719 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5720 return true;
5721 }
5722 }
5723 return false;
5724}
5725
François Gaffie2110e042015-03-24 08:41:51 +01005726audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5727{
5728 return mEngine->getForceUse(usage);
5729}
5730
5731bool AudioPolicyManager::isInCall()
5732{
5733 return isStateInCall(mEngine->getPhoneState());
5734}
5735
5736bool AudioPolicyManager::isStateInCall(int state)
5737{
5738 return is_state_in_call(state);
5739}
5740
Eric Laurentd60560a2015-04-10 11:31:20 -07005741void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5742{
5743 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5744 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
5745 if (sourceDesc->mDevice->equals(deviceDesc)) {
5746 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle());
5747 stopAudioSource(sourceDesc->getHandle());
5748 }
5749 }
5750
5751 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5752 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5753 bool release = false;
5754 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5755 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5756 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5757 source->ext.device.type == deviceDesc->type()) {
5758 release = true;
5759 }
5760 }
5761 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5762 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5763 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5764 sink->ext.device.type == deviceDesc->type()) {
5765 release = true;
5766 }
5767 }
5768 if (release) {
5769 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5770 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5771 }
5772 }
5773}
5774
Phil Burk09bc4612016-02-24 15:58:15 -08005775// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005776void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5777 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005778 // TODO Set this based on Config properties.
5779 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005780
5781 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5782 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005783 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005784
5785 // Analyze original support for various formats.
Phil Burk07ac1142016-03-25 13:39:29 -07005786 bool supportsAC3 = false;
5787 bool supportsOtherSurround = false;
Phil Burk09bc4612016-02-24 15:58:15 -08005788 bool supportsIEC61937 = false;
5789 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
5790 audio_format_t format = formats[formatIndex];
Phil Burk09bc4612016-02-24 15:58:15 -08005791 switch (format) {
5792 case AUDIO_FORMAT_AC3:
Phil Burk07ac1142016-03-25 13:39:29 -07005793 supportsAC3 = true;
5794 break;
Phil Burk09bc4612016-02-24 15:58:15 -08005795 case AUDIO_FORMAT_E_AC3:
5796 case AUDIO_FORMAT_DTS:
5797 case AUDIO_FORMAT_DTS_HD:
Phil Burk07ac1142016-03-25 13:39:29 -07005798 supportsOtherSurround = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005799 break;
5800 case AUDIO_FORMAT_IEC61937:
5801 supportsIEC61937 = true;
5802 break;
5803 default:
5804 break;
5805 }
5806 }
Phil Burk09bc4612016-02-24 15:58:15 -08005807
5808 // Modify formats based on surround preferences.
5809 // If NEVER, remove support for surround formats.
Phil Burk07ac1142016-03-25 13:39:29 -07005810 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5811 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5812 // Remove surround sound related formats.
5813 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5814 audio_format_t format = formats[formatIndex];
5815 switch(format) {
5816 case AUDIO_FORMAT_AC3:
5817 case AUDIO_FORMAT_E_AC3:
5818 case AUDIO_FORMAT_DTS:
5819 case AUDIO_FORMAT_DTS_HD:
5820 case AUDIO_FORMAT_IEC61937:
Phil Burk07ac1142016-03-25 13:39:29 -07005821 formats.removeAt(formatIndex);
5822 break;
5823 default:
5824 formatIndex++; // keep it
5825 break;
5826 }
Phil Burk09bc4612016-02-24 15:58:15 -08005827 }
Phil Burk07ac1142016-03-25 13:39:29 -07005828 supportsAC3 = false;
5829 supportsOtherSurround = false;
5830 supportsIEC61937 = false;
Phil Burk09bc4612016-02-24 15:58:15 -08005831 }
Phil Burk07ac1142016-03-25 13:39:29 -07005832 } else { // AUTO or ALWAYS
5833 // Most TVs support AC3 even if they do not report it in the EDID.
5834 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
5835 && !supportsAC3) {
5836 formats.add(AUDIO_FORMAT_AC3);
5837 supportsAC3 = true;
5838 }
5839
5840 // If ALWAYS, add support for raw surround formats if all are missing.
5841 // This assumes that if any of these formats are reported by the HAL
5842 // then the report is valid and should not be modified.
5843 if ((forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS)
5844 && !supportsOtherSurround) {
5845 formats.add(AUDIO_FORMAT_E_AC3);
5846 formats.add(AUDIO_FORMAT_DTS);
5847 formats.add(AUDIO_FORMAT_DTS_HD);
5848 supportsOtherSurround = true;
5849 }
5850
5851 // Add support for IEC61937 if any raw surround supported.
5852 // The HAL could do this but add it here, just in case.
5853 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
5854 formats.add(AUDIO_FORMAT_IEC61937);
5855 supportsIEC61937 = true;
5856 }
Phil Burk09bc4612016-02-24 15:58:15 -08005857 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005858}
5859
5860// Modify the list of channel masks supported.
5861void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
5862 ChannelsVector &channelMasks = *channelMasksPtr;
5863 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5864 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5865
5866 // If NEVER, then remove support for channelMasks > stereo.
5867 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5868 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5869 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5870 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5871 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5872 channelMasks.removeAt(maskIndex);
5873 } else {
5874 maskIndex++;
5875 }
5876 }
5877 // If ALWAYS, then make sure we at least support 5.1
5878 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5879 bool supports5dot1 = false;
5880 // Are there any channel masks that can be considered "surround"?
5881 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); maskIndex++) {
5882 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5883 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5884 supports5dot1 = true;
5885 break;
5886 }
5887 }
5888 // If not then add 5.1 support.
5889 if (!supports5dot1) {
5890 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
5891 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
5892 }
Phil Burk09bc4612016-02-24 15:58:15 -08005893 }
5894}
5895
Phil Burk00eeb322016-03-31 12:41:00 -07005896void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
5897 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005898 AudioProfileVector &profiles)
5899{
5900 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07005901
François Gaffie112b0af2015-11-19 16:13:25 +01005902 // Format MUST be checked first to update the list of AudioProfile
5903 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005904 reply = mpClientInterface->getParameters(
5905 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
Phil Burk0709b0a2016-03-31 12:54:57 -07005906 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005907 AudioParameter repliedParameters(reply);
5908 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005909 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005910 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5911 return;
5912 }
Phil Burk09bc4612016-02-24 15:58:15 -08005913 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07005914 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005915 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005916 }
Phil Burk09bc4612016-02-24 15:58:15 -08005917 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005918 }
5919 const FormatVector &supportedFormats = profiles.getSupportedFormats();
5920
Eric Laurent20eb3a42016-01-26 18:39:17 -08005921 for (size_t formatIndex = 0; formatIndex < supportedFormats.size(); formatIndex++) {
François Gaffie112b0af2015-11-19 16:13:25 +01005922 audio_format_t format = supportedFormats[formatIndex];
Eric Laurent20eb3a42016-01-26 18:39:17 -08005923 ChannelsVector channelMasks;
5924 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005925 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07005926 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01005927
5928 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005929 reply = mpClientInterface->getParameters(
5930 ioHandle,
5931 requestedParameters.toString() + ";" +
5932 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01005933 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005934 AudioParameter repliedParameters(reply);
5935 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005936 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005937 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005938 }
5939 }
5940 if (profiles.hasDynamicChannelsFor(format)) {
5941 reply = mpClientInterface->getParameters(ioHandle,
5942 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07005943 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01005944 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005945 AudioParameter repliedParameters(reply);
5946 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005947 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005948 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07005949 if (device == AUDIO_DEVICE_OUT_HDMI) {
5950 filterSurroundChannelMasks(&channelMasks);
5951 }
François Gaffie112b0af2015-11-19 16:13:25 +01005952 }
5953 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08005954 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01005955 }
5956}
Eric Laurentd60560a2015-04-10 11:31:20 -07005957
Eric Laurente552edb2014-03-10 17:42:56 -07005958}; // namespace android