blob: 6e66d3ef32db5a609a84d74d43788fd04c381ce4 [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"
Petri Gyntherf497f292018-04-17 18:46:10 -070029#define AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME \
30 "audio_policy_configuration_a2dp_offload_disabled.xml"
François Gaffief4ad6e52015-11-19 16:59:57 +010031
Eric Laurentd4692962014-05-05 18:13:44 -070032#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070033#include <math.h>
Eric Laurentd4692962014-05-05 18:13:44 -070034
François Gaffie2110e042015-03-24 08:41:51 +010035#include <AudioPolicyManagerInterface.h>
36#include <AudioPolicyEngineInstance.h>
Eric Laurente552edb2014-03-10 17:42:56 -070037#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070038#include <utils/Log.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070039#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080040#include <media/AudioPolicyHelper.h>
Mikhail Naganovdc769682018-05-04 15:34:08 -070041#include <media/PatchBuilder.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070042#include <private/android_filesystem_config.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070043#include <soundtrigger/SoundTrigger.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070044#include <system/audio.h>
Mikhail Naganov9ee05402016-10-13 15:58:17 -070045#include <audio_policy_conf.h>
Eric Laurentd4692962014-05-05 18:13:44 -070046#include "AudioPolicyManager.h"
François Gaffied1ab2bd2015-12-02 18:20:06 +010047#ifndef USE_XML_AUDIO_POLICY_CONF
François Gaffie53615e22015-03-19 09:24:12 +010048#include <ConfigParsingUtils.h>
François Gaffied1ab2bd2015-12-02 18:20:06 +010049#include <StreamDescriptor.h>
François Gaffief4ad6e52015-11-19 16:59:57 +010050#endif
François Gaffied1ab2bd2015-12-02 18:20:06 +010051#include <Serializer.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010052#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010053#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070054
Eric Laurent3b73df72014-03-11 09:06:29 -070055namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070056
Eric Laurentdc462862016-07-19 12:29:53 -070057//FIXME: workaround for truncated touch sounds
58// to be removed when the problem is handled by system UI
59#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070060
61// Largest difference in dB on earpiece in call between the voice volume and another
62// media / notification / system volume.
63constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
64
jiabin81772902018-04-02 17:52:27 -070065#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
66// Array of all surround formats.
67static const audio_format_t SURROUND_FORMATS[] = {
68 AUDIO_FORMAT_AC3,
69 AUDIO_FORMAT_E_AC3,
70 AUDIO_FORMAT_DTS,
71 AUDIO_FORMAT_DTS_HD,
72 AUDIO_FORMAT_AAC_LC,
73 AUDIO_FORMAT_DOLBY_TRUEHD,
74 AUDIO_FORMAT_E_AC3_JOC,
75};
76// Array of all AAC formats. When AAC is enabled by users, all AAC formats should be enabled.
77static const audio_format_t AAC_FORMATS[] = {
78 AUDIO_FORMAT_AAC_LC,
79 AUDIO_FORMAT_AAC_HE_V1,
80 AUDIO_FORMAT_AAC_HE_V2,
81 AUDIO_FORMAT_AAC_ELD,
82 AUDIO_FORMAT_AAC_XHE,
83};
84
Eric Laurente552edb2014-03-10 17:42:56 -070085// ----------------------------------------------------------------------------
86// AudioPolicyInterface implementation
87// ----------------------------------------------------------------------------
88
Eric Laurente0720872014-03-11 09:30:41 -070089status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -080090 audio_policy_dev_state_t state,
91 const char *device_address,
92 const char *device_name)
Eric Laurente552edb2014-03-10 17:42:56 -070093{
jiabina7b43792018-02-15 16:04:46 -080094 status_t status = setDeviceConnectionStateInt(device, state, device_address, device_name);
95 nextAudioPortGeneration();
96 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -080097}
98
François Gaffie44481e72016-04-20 07:49:57 +020099void AudioPolicyManager::broadcastDeviceConnectionState(audio_devices_t device,
100 audio_policy_dev_state_t state,
101 const String8 &device_address)
102{
103 AudioParameter param(device_address);
104 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganov388360c2016-10-17 17:09:41 -0700105 AudioParameter::keyStreamConnect : AudioParameter::keyStreamDisconnect);
François Gaffie44481e72016-04-20 07:49:57 +0200106 param.addInt(key, device);
107 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
108}
109
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800110status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800111 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -0800112 const char *device_address,
113 const char *device_name)
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800114{
Paul McLeane743a472015-01-28 11:07:31 -0800115 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s",
Mikhail Naganov7e22e942017-12-07 10:04:29 -0800116 device, state, device_address, device_name);
Eric Laurente552edb2014-03-10 17:42:56 -0700117
118 // connect/disconnect only 1 device at a time
119 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
120
François Gaffie53615e22015-03-19 09:24:12 +0100121 sp<DeviceDescriptor> devDesc =
122 mHwModules.getDeviceDescriptor(device, device_address, device_name);
Paul McLeane743a472015-01-28 11:07:31 -0800123
Eric Laurente552edb2014-03-10 17:42:56 -0700124 // handle output devices
125 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700126 SortedVector <audio_io_handle_t> outputs;
127
Eric Laurent3a4311c2014-03-17 12:00:47 -0700128 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
129
Eric Laurente552edb2014-03-10 17:42:56 -0700130 // save a copy of the opened output descriptors before any output is opened or closed
131 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
132 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700133 switch (state)
134 {
135 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800136 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700137 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700138 ALOGW("setDeviceConnectionState() device already connected: %x", device);
139 return INVALID_OPERATION;
140 }
141 ALOGV("setDeviceConnectionState() connecting device %x", device);
142
Eric Laurente552edb2014-03-10 17:42:56 -0700143 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700144 index = mAvailableOutputDevices.add(devDesc);
145 if (index >= 0) {
François Gaffie53615e22015-03-19 09:24:12 +0100146 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700147 if (module == 0) {
148 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
149 device);
150 mAvailableOutputDevices.remove(devDesc);
151 return INVALID_OPERATION;
152 }
Paul McLeane743a472015-01-28 11:07:31 -0800153 mAvailableOutputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700154 } else {
155 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700156 }
157
François Gaffie44481e72016-04-20 07:49:57 +0200158 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
159 // parameters on newly connected devices (instead of opening the outputs...)
160 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
161
Eric Laurenta1d525f2015-01-29 13:36:45 -0800162 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700163 mAvailableOutputDevices.remove(devDesc);
François Gaffie44481e72016-04-20 07:49:57 +0200164
165 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
166 devDesc->mAddress);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700167 return INVALID_OPERATION;
168 }
François Gaffie2110e042015-03-24 08:41:51 +0100169 // Propagate device availability to Engine
170 mEngine->setDeviceConnectionState(devDesc, state);
171
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700172 // outputs should never be empty here
173 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
174 "checkOutputsForDevice() returned no outputs but status OK");
175 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
176 outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800177
Eric Laurent3ae5f312015-02-03 17:12:08 -0800178 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700179 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700180 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700181 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700182 ALOGW("setDeviceConnectionState() device not connected: %x", device);
183 return INVALID_OPERATION;
184 }
185
Paul McLean5c477aa2014-08-20 16:47:57 -0700186 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
187
Paul McLeane743a472015-01-28 11:07:31 -0800188 // Send Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200189 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700190
Eric Laurente552edb2014-03-10 17:42:56 -0700191 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700192 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700193
Eric Laurenta1d525f2015-01-29 13:36:45 -0800194 checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress);
François Gaffie2110e042015-03-24 08:41:51 +0100195
196 // Propagate device availability to Engine
197 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700198 } break;
199
200 default:
201 ALOGE("setDeviceConnectionState() invalid state: %x", state);
202 return BAD_VALUE;
203 }
204
Eric Laurent3a4311c2014-03-17 12:00:47 -0700205 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
206 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700207 checkA2dpSuspend();
208 checkOutputForAllStrategies();
209 // outputs must be closed after checkOutputForAllStrategies() is executed
210 if (!outputs.isEmpty()) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800211 for (audio_io_handle_t output : outputs) {
212 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -0700213 // close unused outputs after device disconnection or direct outputs that have been
214 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700215 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700216 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
217 (desc->mDirectOpenCount == 0))) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800218 closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -0700219 }
220 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700221 // check again after closing A2DP output to reset mA2dpSuspended if needed
222 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700223 }
224
225 updateDevicesAndOutputs();
Eric Laurent87ffa392015-05-22 10:32:38 -0700226 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700227 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
228 updateCallRouting(newDevice);
229 }
Eric Laurente552edb2014-03-10 17:42:56 -0700230 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700231 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
232 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
233 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700234 // do not force device change on duplicated output because if device is 0, it will
235 // also force a device 0 for the two outputs it is duplicated to which may override
236 // a valid device selection on those outputs.
Eric Laurentc75307b2015-03-17 15:29:32 -0700237 bool force = !desc->isDuplicated()
François Gaffie53615e22015-03-19 09:24:12 +0100238 && (!device_distinguishes_on_address(device)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700239 // always force when disconnecting (a non-duplicated device)
240 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
Eric Laurentc75307b2015-03-17 15:29:32 -0700241 setOutputDevice(desc, newDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700242 }
Eric Laurente552edb2014-03-10 17:42:56 -0700243 }
244
Eric Laurentd60560a2015-04-10 11:31:20 -0700245 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
246 cleanUpForDevice(devDesc);
247 }
248
Eric Laurent72aa32f2014-05-30 18:51:48 -0700249 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700250 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700251 } // end if is output device
252
Eric Laurente552edb2014-03-10 17:42:56 -0700253 // handle input devices
254 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700255 SortedVector <audio_io_handle_t> inputs;
256
Eric Laurent3a4311c2014-03-17 12:00:47 -0700257 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700258 switch (state)
259 {
260 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700261 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700262 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700263 ALOGW("setDeviceConnectionState() device already connected: %d", device);
264 return INVALID_OPERATION;
265 }
François Gaffie53615e22015-03-19 09:24:12 +0100266 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700267 if (module == NULL) {
268 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
269 device);
270 return INVALID_OPERATION;
271 }
François Gaffie44481e72016-04-20 07:49:57 +0200272
273 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
274 // parameters on newly connected devices (instead of opening the inputs...)
275 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
276
Paul McLean9080a4c2015-06-18 08:24:02 -0700277 if (checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress) != NO_ERROR) {
François Gaffie44481e72016-04-20 07:49:57 +0200278 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
279 devDesc->mAddress);
Eric Laurentd4692962014-05-05 18:13:44 -0700280 return INVALID_OPERATION;
281 }
282
Eric Laurent3a4311c2014-03-17 12:00:47 -0700283 index = mAvailableInputDevices.add(devDesc);
284 if (index >= 0) {
Paul McLeane743a472015-01-28 11:07:31 -0800285 mAvailableInputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700286 } else {
287 return NO_MEMORY;
288 }
Eric Laurent3ae5f312015-02-03 17:12:08 -0800289
François Gaffie2110e042015-03-24 08:41:51 +0100290 // Propagate device availability to Engine
291 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700292 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700293
294 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700295 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700296 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700297 ALOGW("setDeviceConnectionState() device not connected: %d", device);
298 return INVALID_OPERATION;
299 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700300
301 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
302
303 // Set Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200304 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700305
Paul McLean9080a4c2015-06-18 08:24:02 -0700306 checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700307 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700308
François Gaffie2110e042015-03-24 08:41:51 +0100309 // Propagate device availability to Engine
310 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700311 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700312
313 default:
314 ALOGE("setDeviceConnectionState() invalid state: %x", state);
315 return BAD_VALUE;
316 }
317
Eric Laurentd4692962014-05-05 18:13:44 -0700318 closeAllInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700319 // As the input device list can impact the output device selection, update
320 // getDeviceForStrategy() cache
321 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700322
Eric Laurent87ffa392015-05-22 10:32:38 -0700323 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700324 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
325 updateCallRouting(newDevice);
326 }
327
Eric Laurentd60560a2015-04-10 11:31:20 -0700328 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
329 cleanUpForDevice(devDesc);
330 }
331
Eric Laurentb52c1522014-05-20 11:27:36 -0700332 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700333 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700334 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700335
336 ALOGW("setDeviceConnectionState() invalid device: %x", device);
337 return BAD_VALUE;
338}
339
Eric Laurente0720872014-03-11 09:30:41 -0700340audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100341 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700342{
Eric Laurent634b7142016-04-20 13:48:02 -0700343 sp<DeviceDescriptor> devDesc =
344 mHwModules.getDeviceDescriptor(device, device_address, "",
345 (strlen(device_address) != 0)/*matchAddress*/);
346
347 if (devDesc == 0) {
348 ALOGW("getDeviceConnectionState() undeclared device, type %08x, address: %s",
349 device, device_address);
350 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
351 }
François Gaffie53615e22015-03-19 09:24:12 +0100352
Eric Laurent3a4311c2014-03-17 12:00:47 -0700353 DeviceVector *deviceVector;
354
Eric Laurente552edb2014-03-10 17:42:56 -0700355 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700356 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700357 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700358 deviceVector = &mAvailableInputDevices;
359 } else {
360 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
361 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700362 }
Eric Laurent634b7142016-04-20 13:48:02 -0700363
364 return (deviceVector->getDevice(device, String8(device_address)) != 0) ?
365 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800366}
367
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800368status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
369 const char *device_address,
370 const char *device_name)
371{
372 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700373 String8 reply;
374 AudioParameter param;
375 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800376
377 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s",
378 device, device_address, device_name);
379
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800380 // connect/disconnect only 1 device at a time
381 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
382
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800383 // Check if the device is currently connected
384 sp<DeviceDescriptor> devDesc =
385 mHwModules.getDeviceDescriptor(device, device_address, device_name);
386 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
387 if (index < 0) {
388 // Nothing to do: device is not connected
389 return NO_ERROR;
390 }
391
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700392 // For offloaded A2DP, Hw modules may have the capability to
393 // configure codecs. Check if any of the loaded hw modules
394 // supports this.
395 // If supported, send a set parameter to configure A2DP codecs
396 // and return. No need to toggle device state.
397 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
398 reply = mpClientInterface->getParameters(
399 AUDIO_IO_HANDLE_NONE,
400 String8(AudioParameter::keyReconfigA2dpSupported));
401 AudioParameter repliedParameters(reply);
402 repliedParameters.getInt(
403 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
404 if (isReconfigA2dpSupported) {
405 const String8 key(AudioParameter::keyReconfigA2dp);
406 param.add(key, String8("true"));
407 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
408 return NO_ERROR;
409 }
410 }
411
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800412 // Toggle the device state: UNAVAILABLE -> AVAILABLE
413 // This will force reading again the device configuration
414 status = setDeviceConnectionState(device,
415 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
416 device_address, device_name);
417 if (status != NO_ERROR) {
418 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
419 status);
420 return status;
421 }
422
423 status = setDeviceConnectionState(device,
424 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
425 device_address, device_name);
426 if (status != NO_ERROR) {
427 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
428 status);
429 return status;
430 }
431
432 return NO_ERROR;
433}
434
Eric Laurentdc462862016-07-19 12:29:53 -0700435uint32_t AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700436{
437 bool createTxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700438 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700439
Andy Hunga76c7de2016-12-13 19:14:31 -0800440 if(!hasPrimaryOutput() || mPrimaryOutput->device() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurentdc462862016-07-19 12:29:53 -0700441 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700442 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800443 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700444 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
445
446 // release existing RX patch if any
447 if (mCallRxPatch != 0) {
448 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
449 mCallRxPatch.clear();
450 }
451 // release TX patch if any
452 if (mCallTxPatch != 0) {
453 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
454 mCallTxPatch.clear();
455 }
456
457 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
458 // via setOutputDevice() on primary output.
459 // Otherwise, create two audio patches for TX and RX path.
460 if (availablePrimaryOutputDevices() & rxDevice) {
Eric Laurentdc462862016-07-19 12:29:53 -0700461 muteWaitMs = setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700462 // If the TX device is also on the primary HW module, setOutputDevice() will take care
463 // of it due to legacy implementation. If not, create a patch.
464 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
465 == AUDIO_DEVICE_NONE) {
466 createTxPatch = true;
467 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700468 } else { // create RX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800469 mCallRxPatch = createTelephonyPatch(true /*isRx*/, rxDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700470 createTxPatch = true;
471 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700472 if (createTxPatch) { // create TX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800473 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txDevice, delayMs);
474 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700475
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800476 return muteWaitMs;
477}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700478
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800479sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
480 bool isRx, audio_devices_t device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700481 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700482
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800483 sp<DeviceDescriptor> txSourceDeviceDesc;
484 if (isRx) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700485 patchBuilder.addSink(findDevice(mAvailableOutputDevices, device)).
486 addSource(findDevice(mAvailableInputDevices, AUDIO_DEVICE_IN_TELEPHONY_RX));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800487 } else {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700488 patchBuilder.addSource(txSourceDeviceDesc = findDevice(mAvailableInputDevices, device)).
489 addSink(findDevice(mAvailableOutputDevices, AUDIO_DEVICE_OUT_TELEPHONY_TX));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800490 }
491
492 audio_devices_t outputDevice = isRx ? device : AUDIO_DEVICE_OUT_TELEPHONY_TX;
493 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(outputDevice, mOutputs);
494 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
495 // request to reuse existing output stream if one is already opened to reach the target device
496 if (output != AUDIO_IO_HANDLE_NONE) {
497 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
498 ALOG_ASSERT(!outputDesc->isDuplicated(),
499 "%s() %#x device output %d is duplicated", __func__, outputDevice, output);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700500 patchBuilder.addSource(outputDesc, { .stream = AUDIO_STREAM_PATCH });
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800501 }
502
503 if (!isRx) {
Eric Laurentc0a889f2015-10-14 14:36:34 -0700504 // terminate active capture if on the same HW module as the call TX source device
505 // FIXME: would be better to refine to only inputs whose profile connects to the
506 // call TX device but this information is not in the audio patch and logic here must be
507 // symmetric to the one in startInput()
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800508 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800509 if (activeDesc->hasSameHwModuleAs(txSourceDeviceDesc)) {
510 AudioSessionCollection activeSessions =
511 activeDesc->getAudioSessions(true /*activeOnly*/);
512 for (size_t j = 0; j < activeSessions.size(); j++) {
513 audio_session_t activeSession = activeSessions.keyAt(j);
514 stopInput(activeDesc->mIoHandle, activeSession);
515 releaseInput(activeDesc->mIoHandle, activeSession);
516 }
Eric Laurentc0a889f2015-10-14 14:36:34 -0700517 }
518 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700519 }
Eric Laurentdc462862016-07-19 12:29:53 -0700520
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800521 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Mikhail Naganovdc769682018-05-04 15:34:08 -0700522 status_t status = mpClientInterface->createAudioPatch(
523 patchBuilder.patch(), &afPatchHandle, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800524 ALOGW_IF(status != NO_ERROR,
525 "%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
526 sp<AudioPatch> audioPatch;
527 if (status == NO_ERROR) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700528 audioPatch = new AudioPatch(patchBuilder.patch(), mUidCached);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800529 audioPatch->mAfPatchHandle = afPatchHandle;
530 audioPatch->mUid = mUidCached;
531 }
532 return audioPatch;
533}
534
Mikhail Naganovdc769682018-05-04 15:34:08 -0700535sp<DeviceDescriptor> AudioPolicyManager::findDevice(
536 const DeviceVector& devices, audio_devices_t device) {
Mikhail Naganov708e0382018-05-30 09:53:04 -0700537 DeviceVector deviceList = devices.getDevicesFromTypeMask(device);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800538 ALOG_ASSERT(!deviceList.isEmpty(),
539 "%s() selected device type %#x is not in devices list", __func__, device);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700540 return deviceList.itemAt(0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700541}
542
Eric Laurente0720872014-03-11 09:30:41 -0700543void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700544{
545 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100546 // store previous phone state for management of sonification strategy below
547 int oldState = mEngine->getPhoneState();
548
549 if (mEngine->setPhoneState(state) != NO_ERROR) {
550 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700551 return;
552 }
François Gaffie2110e042015-03-24 08:41:51 +0100553 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700554 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700555 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700556 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800557 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700558 }
559
François Gaffie2110e042015-03-24 08:41:51 +0100560 /**
561 * Switching to or from incall state or switching between telephony and VoIP lead to force
562 * routing command.
563 */
564 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
565 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700566
567 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700568 checkA2dpSuspend();
569 checkOutputForAllStrategies();
570 updateDevicesAndOutputs();
571
Eric Laurente552edb2014-03-10 17:42:56 -0700572 int delayMs = 0;
573 if (isStateInCall(state)) {
574 nsecs_t sysTime = systemTime();
575 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700576 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700577 // mute media and sonification strategies and delay device switch by the largest
578 // latency of any output where either strategy is active.
579 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100580 if ((isStrategyActive(desc, STRATEGY_MEDIA,
581 SONIFICATION_HEADSET_MUSIC_DELAY,
582 sysTime) ||
583 isStrategyActive(desc, STRATEGY_SONIFICATION,
584 SONIFICATION_HEADSET_MUSIC_DELAY,
585 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700586 (delayMs < (int)desc->latency()*2)) {
587 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700588 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700589 setStrategyMute(STRATEGY_MEDIA, true, desc);
590 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700591 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700592 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
593 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700594 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
595 }
596 }
597
Eric Laurent87ffa392015-05-22 10:32:38 -0700598 if (hasPrimaryOutput()) {
599 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
600 // the device returned is not necessarily reachable via this output
601 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
602 // force routing command to audio hardware when ending call
603 // even if no device change is needed
604 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
605 rxDevice = mPrimaryOutput->device();
606 }
Eric Laurente552edb2014-03-10 17:42:56 -0700607
Eric Laurent87ffa392015-05-22 10:32:38 -0700608 if (state == AUDIO_MODE_IN_CALL) {
609 updateCallRouting(rxDevice, delayMs);
610 } else if (oldState == AUDIO_MODE_IN_CALL) {
611 if (mCallRxPatch != 0) {
612 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
613 mCallRxPatch.clear();
614 }
615 if (mCallTxPatch != 0) {
616 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
617 mCallTxPatch.clear();
618 }
619 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
620 } else {
621 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700622 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700623 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700624
625 // reevaluate routing on all outputs in case tracks have been started during the call
626 for (size_t i = 0; i < mOutputs.size(); i++) {
627 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
628 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
629 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
Yung Ti Suf60c8242018-05-10 18:07:26 +0800630 setOutputDevice(desc, newDevice, (newDevice != AUDIO_DEVICE_NONE), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700631 }
632 }
633
Eric Laurente552edb2014-03-10 17:42:56 -0700634 if (isStateInCall(state)) {
635 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700636 // force reevaluating accessibility routing when call starts
637 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700638 }
639
640 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700641 if (state == AUDIO_MODE_RINGTONE &&
642 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700643 mLimitRingtoneVolume = true;
644 } else {
645 mLimitRingtoneVolume = false;
646 }
647}
648
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700649audio_mode_t AudioPolicyManager::getPhoneState() {
650 return mEngine->getPhoneState();
651}
652
Eric Laurente0720872014-03-11 09:30:41 -0700653void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700654 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700655{
François Gaffie2110e042015-03-24 08:41:51 +0100656 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700657 if (config == mEngine->getForceUse(usage)) {
658 return;
659 }
Eric Laurente552edb2014-03-10 17:42:56 -0700660
François Gaffie2110e042015-03-24 08:41:51 +0100661 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
662 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
663 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700664 }
François Gaffie2110e042015-03-24 08:41:51 +0100665 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
666 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
667 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700668
669 // check for device and output changes triggered by new force usage
670 checkA2dpSuspend();
671 checkOutputForAllStrategies();
672 updateDevicesAndOutputs();
Phil Burk09bc4612016-02-24 15:58:15 -0800673
Eric Laurentdc462862016-07-19 12:29:53 -0700674 //FIXME: workaround for truncated touch sounds
675 // to be removed when the problem is handled by system UI
676 uint32_t delayMs = 0;
677 uint32_t waitMs = 0;
678 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
679 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
680 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700681 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700682 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
Eric Laurentdc462862016-07-19 12:29:53 -0700683 waitMs = updateCallRouting(newDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700684 }
Eric Laurente552edb2014-03-10 17:42:56 -0700685 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700686 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
687 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
688 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700689 waitMs = setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE),
690 delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700691 }
Eric Laurente552edb2014-03-10 17:42:56 -0700692 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700693 applyStreamVolumes(outputDesc, newDevice, waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700694 }
695 }
696
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800697 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800698 audio_devices_t newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700699 // Force new input selection if the new device can not be reached via current input
Eric Laurentfb66dd92016-01-28 18:32:03 -0800700 if (activeDesc->mProfile->getSupportedDevices().types() &
701 (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
702 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700703 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800704 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700705 }
Eric Laurente552edb2014-03-10 17:42:56 -0700706 }
Eric Laurente552edb2014-03-10 17:42:56 -0700707}
708
Eric Laurente0720872014-03-11 09:30:41 -0700709void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700710{
711 ALOGV("setSystemProperty() property %s, value %s", property, value);
712}
713
714// Find a direct output profile compatible with the parameters passed, even if the input flags do
715// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800716sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700717 audio_devices_t device,
718 uint32_t samplingRate,
719 audio_format_t format,
720 audio_channel_mask_t channelMask,
721 audio_output_flags_t flags)
722{
Eric Laurent861a6282015-05-18 15:40:16 -0700723 // only retain flags that will drive the direct output profile selection
724 // if explicitly requested
725 static const uint32_t kRelevantFlags =
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700726 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
727 AUDIO_OUTPUT_FLAG_VOIP_RX);
Eric Laurent861a6282015-05-18 15:40:16 -0700728 flags =
729 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
730
731 sp<IOProfile> profile;
732
Mikhail Naganovd4120142017-12-06 15:49:22 -0800733 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800734 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent861a6282015-05-18 15:40:16 -0700735 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700736 samplingRate, NULL /*updatedSamplingRate*/,
737 format, NULL /*updatedFormat*/,
738 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700739 flags)) {
740 continue;
741 }
742 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100743 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700744 continue;
745 }
746 // if several profiles are compatible, give priority to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100747 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700748 continue;
749 }
750 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100751 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700752 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700753 }
Eric Laurente552edb2014-03-10 17:42:56 -0700754 }
755 }
Eric Laurent861a6282015-05-18 15:40:16 -0700756 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700757}
758
Eric Laurentf4e63452017-11-06 19:31:46 +0000759audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
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*/);
Andy Hungc9901522017-11-10 20:07:54 -0800763
764 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
765 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
766 // format, flags, etc. This may result in some discrepancy for functions that utilize
767 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
768 // and AudioSystem::getOutputSamplingRate().
769
Eric Laurentf4e63452017-11-06 19:31:46 +0000770 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
771 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
Eric Laurente552edb2014-03-10 17:42:56 -0700772
Eric Laurentf4e63452017-11-06 19:31:46 +0000773 ALOGV("getOutput() stream %d selected device %08x, output %d", stream, device, output);
774 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700775}
776
Eric Laurente83b55d2014-11-14 10:06:21 -0800777status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
778 audio_io_handle_t *output,
779 audio_session_t session,
780 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700781 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800782 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200783 audio_output_flags_t *flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700784 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800785 audio_port_handle_t *portId)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700786{
Eric Laurente83b55d2014-11-14 10:06:21 -0800787 audio_attributes_t attributes;
788 if (attr != NULL) {
789 if (!isValidAttributes(attr)) {
790 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
791 attr->usage, attr->content_type, attr->flags,
792 attr->tags);
793 return BAD_VALUE;
794 }
795 attributes = *attr;
796 } else {
797 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
798 ALOGE("getOutputForAttr(): invalid stream type");
799 return BAD_VALUE;
800 }
801 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700802 }
Eric Laurent20b9ef02016-12-05 11:03:16 -0800803
804 // TODO: check for existing client for this port ID
805 if (*portId == AUDIO_PORT_HANDLE_NONE) {
806 *portId = AudioPort::getNextUniqueId();
807 }
808
Eric Laurentc75307b2015-03-17 15:29:32 -0700809 sp<SwAudioOutputDescriptor> desc;
Jean-Michel Trivie8deced2016-02-11 12:50:39 -0800810 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
François Gaffie036e1e92015-03-19 10:16:24 +0100811 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
Eric Laurent20b9ef02016-12-05 11:03:16 -0800812 if (!audio_has_proportional_frames(config->format)) {
François Gaffie036e1e92015-03-19 10:16:24 +0100813 return BAD_VALUE;
Eric Laurent275e8e92014-11-30 15:14:47 -0800814 }
François Gaffie036e1e92015-03-19 10:16:24 +0100815 *stream = streamTypefromAttributesInt(&attributes);
816 *output = desc->mIoHandle;
817 ALOGV("getOutputForAttr() returns output %d", *output);
818 return NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -0800819 }
820 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
821 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
822 return BAD_VALUE;
823 }
824
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700825 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
826 " session %d selectedDeviceId %d",
827 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700828 session, *selectedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700829
830 *stream = streamTypefromAttributesInt(&attributes);
831
832 // Explicit routing?
833 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -0700834 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800835 deviceDesc = mAvailableOutputDevices.getDeviceFromId(*selectedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700836 }
837 mOutputRoutes.addRoute(session, *stream, SessionRoute::SOURCE_TYPE_NA, deviceDesc, uid);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700838
Eric Laurente83b55d2014-11-14 10:06:21 -0800839 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700840 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700841
Eric Laurente83b55d2014-11-14 10:06:21 -0800842 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200843 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -0700844 }
845
Glenn Kasten49f36ba2017-12-06 13:02:02 -0800846 ALOGV("getOutputForAttr() device 0x%x, sampling rate %d, format %#x, channel mask %#x, "
847 "flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +0200848 device, config->sample_rate, config->format, config->channel_mask, *flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700849
Andy Hungc88b0642018-04-27 15:42:35 -0700850 *output = getOutputForDevice(device, session, *stream, config, flags);
Eric Laurente83b55d2014-11-14 10:06:21 -0800851 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700852 mOutputRoutes.removeRoute(session);
Eric Laurente83b55d2014-11-14 10:06:21 -0800853 return INVALID_OPERATION;
854 }
Paul McLeanaa981192015-03-21 09:55:15 -0700855
Mikhail Naganov708e0382018-05-30 09:53:04 -0700856 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -0700857 *selectedDeviceId = outputDevices.size() > 0 ? outputDevices.itemAt(0)->getId()
858 : AUDIO_PORT_HANDLE_NONE;
859
860 ALOGV(" getOutputForAttr() returns output %d selectedDeviceId %d", *output, *selectedDeviceId);
861
Eric Laurente83b55d2014-11-14 10:06:21 -0800862 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700863}
864
865audio_io_handle_t AudioPolicyManager::getOutputForDevice(
866 audio_devices_t device,
Kevin Rocard169753c2017-03-06 14:18:23 -0800867 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700868 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -0800869 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200870 audio_output_flags_t *flags)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700871{
Andy Hungc88b0642018-04-27 15:42:35 -0700872 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700873 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700874
Eric Laurente552edb2014-03-10 17:42:56 -0700875 // open a direct output if required by specified parameters
876 //force direct flag if offload flag is set: offloading implies a direct output stream
877 // and all common behaviors are driven by checking only the direct flag
878 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +0200879 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
880 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700881 }
Nadav Bar766fb022018-01-07 12:18:03 +0200882 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
883 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -0700884 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800885 // only allow deep buffering for music stream type
886 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +0200887 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700888 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +0200889 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700890 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
891 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +0200892 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800893 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700894 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +0200895 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700896 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Eric Laurentfe231122017-11-17 17:48:06 -0800897 audio_is_linear_pcm(config->format)) {
Nadav Bar766fb022018-01-07 12:18:03 +0200898 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700899 AUDIO_OUTPUT_FLAG_DIRECT);
900 ALOGV("Set VoIP and Direct output flags for PCM format");
Nadav Bar766fb022018-01-07 12:18:03 +0200901 } else if (device == AUDIO_DEVICE_OUT_TELEPHONY_TX &&
902 stream == AUDIO_STREAM_MUSIC &&
903 audio_is_linear_pcm(config->format) &&
904 isInCall()) {
905 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700906 }
Eric Laurente552edb2014-03-10 17:42:56 -0700907
Nadav Bar766fb022018-01-07 12:18:03 +0200908
Eric Laurentb732cf52014-09-24 19:08:21 -0700909 sp<IOProfile> profile;
910
911 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700912 // and not explicitly requested
Nadav Bar766fb022018-01-07 12:18:03 +0200913 if (((*flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Eric Laurentfe231122017-11-17 17:48:06 -0800914 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
915 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
Eric Laurentb732cf52014-09-24 19:08:21 -0700916 goto non_direct_output;
917 }
918
Andy Hung2ddee192015-12-18 17:34:44 -0800919 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
920 // This prevents creating an offloaded track and tearing it down immediately after start
921 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700922 // FIXME: We should check the audio session here but we do not have it in this context.
923 // This may prevent offloading in rare situations where effects are left active by apps
924 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700925
Nadav Bar766fb022018-01-07 12:18:03 +0200926 if (((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800927 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700928 profile = getProfileForDirectOutput(device,
Eric Laurentfe231122017-11-17 17:48:06 -0800929 config->sample_rate,
930 config->format,
931 config->channel_mask,
Nadav Bar766fb022018-01-07 12:18:03 +0200932 (audio_output_flags_t)*flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700933 }
934
Eric Laurent1c333e22014-05-20 10:48:17 -0700935 if (profile != 0) {
Andy Hungc88b0642018-04-27 15:42:35 -0700936 // exclusive outputs for MMAP and Offload are enforced by different session ids.
937 for (size_t i = 0; i < mOutputs.size(); i++) {
938 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
939 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
940 // reuse direct output if currently open by the same client
941 // and configured with same parameters
942 if ((config->sample_rate == desc->mSamplingRate) &&
Andy Hung5659ed52018-04-30 10:31:26 -0700943 (config->format == desc->mFormat) &&
Andy Hungc88b0642018-04-27 15:42:35 -0700944 (config->channel_mask == desc->mChannelMask) &&
945 (session == desc->mDirectClientSession)) {
946 desc->mDirectOpenCount++;
947 ALOGI("getOutputForDevice() reusing direct output %d for session %d",
948 mOutputs.keyAt(i), session);
949 return mOutputs.keyAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700950 }
951 }
952 }
Eric Laurent3974e3b2017-12-07 17:58:43 -0800953
954 if (!profile->canOpenNewIo()) {
955 goto non_direct_output;
Eric Laurente552edb2014-03-10 17:42:56 -0700956 }
Eric Laurent861a6282015-05-18 15:40:16 -0700957
Eric Laurent3974e3b2017-12-07 17:58:43 -0800958 sp<SwAudioOutputDescriptor> outputDesc =
959 new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurent53b810e2017-12-10 17:25:10 -0800960
Mikhail Naganov708e0382018-05-30 09:53:04 -0700961 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -0800962 String8 address = outputDevices.size() > 0 ? outputDevices.itemAt(0)->mAddress
963 : String8("");
964
Nadav Bar766fb022018-01-07 12:18:03 +0200965 status = outputDesc->open(config, device, address, stream, *flags, &output);
Eric Laurente552edb2014-03-10 17:42:56 -0700966
967 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -0700968 if (status != NO_ERROR ||
Eric Laurentfe231122017-11-17 17:48:06 -0800969 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
Andy Hung5659ed52018-04-30 10:31:26 -0700970 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->mFormat) ||
Eric Laurentfe231122017-11-17 17:48:06 -0800971 (config->channel_mask != 0 && config->channel_mask != outputDesc->mChannelMask)) {
972 ALOGV("getOutputForDevice() failed opening direct output: output %d sample rate %d %d,"
973 "format %d %d, channel mask %04x %04x", output, config->sample_rate,
974 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
975 config->channel_mask, outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700976 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -0800977 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -0700978 }
Eric Laurenta82797f2015-01-30 11:49:43 -0800979 // fall back to mixer output if possible when the direct output could not be open
Eric Laurentfe231122017-11-17 17:48:06 -0800980 if (audio_is_linear_pcm(config->format) &&
981 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -0800982 goto non_direct_output;
983 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700984 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -0700985 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700986 outputDesc->mRefCount[stream] = 0;
987 outputDesc->mStopTime[stream] = 0;
988 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -0800989 outputDesc->mDirectClientSession = session;
990
Eric Laurente552edb2014-03-10 17:42:56 -0700991 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700992 mPreviousOutputs = mOutputs;
Eric Laurentf4e63452017-11-06 19:31:46 +0000993 ALOGV("getOutputForDevice() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -0700994 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700995 return output;
996 }
997
Eric Laurentb732cf52014-09-24 19:08:21 -0700998non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -0700999
1000 // A request for HW A/V sync cannot fallback to a mixed output because time
1001 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001002 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001003 return AUDIO_IO_HANDLE_NONE;
1004 }
1005
Eric Laurente552edb2014-03-10 17:42:56 -07001006 // ignoring channel mask due to downmix capability in mixer
1007
1008 // open a non direct output
1009
1010 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001011 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001012 // get which output is suitable for the specified stream. The actual
1013 // routing change will happen when startOutput() will be called
1014 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1015
Eric Laurent8838a382014-09-08 16:44:28 -07001016 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001017 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1018 output = selectOutput(outputs, *flags, config->format);
Eric Laurente552edb2014-03-10 17:42:56 -07001019 }
Eric Laurentf4e63452017-11-06 19:31:46 +00001020 ALOGW_IF((output == 0), "getOutputForDevice() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001021 "sampling rate %d, format %#x, channels %#x, flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +02001022 stream, config->sample_rate, config->format, config->channel_mask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001023
Eric Laurente552edb2014-03-10 17:42:56 -07001024 return output;
1025}
1026
Eric Laurente0720872014-03-11 09:30:41 -07001027audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001028 audio_output_flags_t flags,
1029 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001030{
1031 // select one output among several that provide a path to a particular device or set of
1032 // devices (the list was previously build by getOutputsForDevice()).
1033 // The priority is as follows:
1034 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001035 // 2: the output with the bit depth the closest to the requested one
1036 // 3: the primary output
1037 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001038
1039 if (outputs.size() == 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001040 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001041 }
1042 if (outputs.size() == 1) {
1043 return outputs[0];
1044 }
1045
1046 int maxCommonFlags = 0;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001047 audio_io_handle_t outputForFlags = AUDIO_IO_HANDLE_NONE;
1048 audio_io_handle_t outputForPrimary = AUDIO_IO_HANDLE_NONE;
1049 audio_io_handle_t outputForFormat = AUDIO_IO_HANDLE_NONE;
Eric Laurente6930022016-02-11 10:20:40 -08001050 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1051 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001052
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001053 for (audio_io_handle_t output : outputs) {
1054 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001055 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001056 // if a valid format is specified, skip output if not compatible
1057 if (format != AUDIO_FORMAT_INVALID) {
1058 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Andy Hung5659ed52018-04-30 10:31:26 -07001059 if (format != outputDesc->mFormat) {
Eric Laurent8838a382014-09-08 16:44:28 -07001060 continue;
1061 }
1062 } else if (!audio_is_linear_pcm(format)) {
1063 continue;
1064 }
Eric Laurente6930022016-02-11 10:20:40 -08001065 if (AudioPort::isBetterFormatMatch(
1066 outputDesc->mFormat, bestFormat, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001067 outputForFormat = output;
Eric Laurente6930022016-02-11 10:20:40 -08001068 bestFormat = outputDesc->mFormat;
1069 }
Eric Laurent8838a382014-09-08 16:44:28 -07001070 }
1071
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001072 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001073 if (commonFlags >= maxCommonFlags) {
1074 if (commonFlags == maxCommonFlags) {
Andy Hungc9901522017-11-10 20:07:54 -08001075 if (format != AUDIO_FORMAT_INVALID
1076 && AudioPort::isBetterFormatMatch(
1077 outputDesc->mFormat, bestFormatForFlags, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001078 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001079 bestFormatForFlags = outputDesc->mFormat;
1080 }
1081 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001082 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001083 maxCommonFlags = commonFlags;
1084 bestFormatForFlags = outputDesc->mFormat;
1085 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001086 ALOGV("selectOutput() commonFlags for output %d, %04x", output, commonFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001087 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001088 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001089 outputForPrimary = output;
Eric Laurente552edb2014-03-10 17:42:56 -07001090 }
1091 }
1092 }
1093
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001094 if (outputForFlags != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001095 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001096 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001097 if (outputForFormat != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001098 return outputForFormat;
1099 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001100 if (outputForPrimary != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001101 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001102 }
1103
1104 return outputs[0];
1105}
1106
Eric Laurente0720872014-03-11 09:30:41 -07001107status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001108 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001109 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001110{
Paul McLeanaa981192015-03-21 09:55:15 -07001111 ALOGV("startOutput() output %d, stream %d, session %d",
1112 output, stream, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001113 ssize_t index = mOutputs.indexOfKey(output);
1114 if (index < 0) {
1115 ALOGW("startOutput() unknown output %d", output);
1116 return BAD_VALUE;
1117 }
1118
Eric Laurentc75307b2015-03-17 15:29:32 -07001119 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1120
Eric Laurent733ce942017-12-07 12:18:25 -08001121 status_t status = outputDesc->start();
1122 if (status != NO_ERROR) {
1123 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001124 }
1125
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001126 // Routing?
1127 mOutputRoutes.incRouteActivity(session);
1128
Eric Laurentc75307b2015-03-17 15:29:32 -07001129 audio_devices_t newDevice;
Eric Laurentc40d9692016-04-13 19:14:13 -07001130 AudioMix *policyMix = NULL;
1131 const char *address = NULL;
Eric Laurentc75307b2015-03-17 15:29:32 -07001132 if (outputDesc->mPolicyMix != NULL) {
Eric Laurentc40d9692016-04-13 19:14:13 -07001133 policyMix = outputDesc->mPolicyMix;
1134 address = policyMix->mDeviceAddress.string();
1135 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1136 newDevice = policyMix->mDeviceType;
1137 } else {
1138 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1139 }
Eric Laurent2157f5b2018-04-25 18:33:02 -07001140 } else if (mOutputRoutes.getAndClearRouteChanged(session)) {
Eric Laurent493404d2015-04-21 15:07:36 -07001141 newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurentf3a5a602018-05-22 18:42:55 -07001142 if (newDevice != outputDesc->device()) {
1143 checkStrategyRoute(getStrategy(stream), output);
1144 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001145 } else {
1146 newDevice = AUDIO_DEVICE_NONE;
1147 }
1148
1149 uint32_t delayMs = 0;
1150
Eric Laurent733ce942017-12-07 12:18:25 -08001151 status = startSource(outputDesc, stream, newDevice, address, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001152
1153 if (status != NO_ERROR) {
1154 mOutputRoutes.decRouteActivity(session);
Eric Laurent733ce942017-12-07 12:18:25 -08001155 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001156 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001157 }
1158 // Automatically enable the remote submix input when output is started on a re routing mix
1159 // of type MIX_TYPE_RECORDERS
Eric Laurentc40d9692016-04-13 19:14:13 -07001160 if (audio_is_remote_submix_device(newDevice) && policyMix != NULL &&
1161 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001162 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1163 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Eric Laurentc40d9692016-04-13 19:14:13 -07001164 address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001165 "remote-submix");
1166 }
1167
1168 if (delayMs != 0) {
1169 usleep(delayMs * 1000);
1170 }
1171
1172 return status;
1173}
1174
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001175status_t AudioPolicyManager::startSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurentc75307b2015-03-17 15:29:32 -07001176 audio_stream_type_t stream,
1177 audio_devices_t device,
Eric Laurentc40d9692016-04-13 19:14:13 -07001178 const char *address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001179 uint32_t *delayMs)
1180{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001181 // cannot start playback of STREAM_TTS if any other output is being used
1182 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001183
1184 *delayMs = 0;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001185 if (stream == AUDIO_STREAM_TTS) {
1186 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001187 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001188 return INVALID_OPERATION;
1189 } else {
1190 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1191 }
1192 } else {
1193 // some playback other than beacon starts
1194 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1195 }
1196
Eric Laurent77305a62016-07-25 16:39:22 -07001197 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001198 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001199 bool force = !outputDesc->isActive() &&
1200 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001201
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001202 // requiresMuteCheck is false when we can bypass mute strategy.
1203 // It covers a common case when there is no materially active audio
1204 // and muting would result in unnecessary delay and dropped audio.
1205 const uint32_t outputLatencyMs = outputDesc->latency();
1206 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1207
Eric Laurente552edb2014-03-10 17:42:56 -07001208 // increment usage count for this stream on the requested output:
1209 // NOTE that the usage count is the same for duplicated output and hardware output which is
1210 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1211 outputDesc->changeRefCount(stream, 1);
1212
Eric Laurent36829f92017-04-07 19:04:42 -07001213 if (stream == AUDIO_STREAM_MUSIC) {
1214 selectOutputForMusicEffects();
1215 }
1216
Eric Laurent493404d2015-04-21 15:07:36 -07001217 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001218 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001219 if (device == AUDIO_DEVICE_NONE) {
1220 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001221 }
Eric Laurent36829f92017-04-07 19:04:42 -07001222
Eric Laurente552edb2014-03-10 17:42:56 -07001223 routing_strategy strategy = getStrategy(stream);
1224 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001225 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1226 (beaconMuteLatency > 0);
1227 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001228 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001229 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001230 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001231 // An output has a shared device if
1232 // - managed by the same hw module
1233 // - supports the currently selected device
1234 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
1235 && (desc->supportedDevices() & device) != AUDIO_DEVICE_NONE;
1236
Eric Laurent77305a62016-07-25 16:39:22 -07001237 // force a device change if any other output is:
1238 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001239 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001240 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001241 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001242 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001243 // change the device currently selected by the other output.
1244 if (sharedDevice &&
Eric Laurent77305a62016-07-25 16:39:22 -07001245 desc->device() != device &&
Eric Laurent77305a62016-07-25 16:39:22 -07001246 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001247 force = true;
1248 }
1249 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001250 // a notification so that audio focus effect can propagate, or that a mute/unmute
1251 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001252 const uint32_t latencyMs = desc->latency();
1253 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1254
1255 if (shouldWait && isActive && (waitMs < latencyMs)) {
1256 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001257 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001258
1259 // Require mute check if another output is on a shared device
1260 // and currently active to have proper drain and avoid pops.
1261 // Note restoring AudioTracks onto this output needs to invoke
1262 // a volume ramp if there is no mute.
1263 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001264 }
1265 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001266
1267 const uint32_t muteWaitMs =
1268 setOutputDevice(outputDesc, device, force, 0, NULL, address, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001269
Eric Laurente552edb2014-03-10 17:42:56 -07001270 // apply volume rules for current stream and device if necessary
1271 checkAndSetVolume(stream,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001272 mVolumeCurves->getVolumeIndex(stream, outputDesc->device()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001273 outputDesc,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001274 outputDesc->device());
Eric Laurente552edb2014-03-10 17:42:56 -07001275
1276 // update the outputs if starting an output with a stream that can affect notification
1277 // routing
1278 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001279
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001280 // force reevaluating accessibility routing when ringtone or alarm starts
1281 if (strategy == STRATEGY_SONIFICATION) {
1282 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1283 }
Eric Laurentdc462862016-07-19 12:29:53 -07001284
1285 if (waitMs > muteWaitMs) {
1286 *delayMs = waitMs - muteWaitMs;
1287 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001288
1289 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1290 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1291 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1292 // change occurs after the MixerThread starts and causes a stream volume
1293 // glitch.
1294 //
1295 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001296 }
Eric Laurentdc462862016-07-19 12:29:53 -07001297
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001298 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1299 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1300 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1301 }
1302
Tomoharu Kasaharaa81f0982018-01-18 20:55:02 +09001303 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1304 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1305 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1306 }
1307
Eric Laurente552edb2014-03-10 17:42:56 -07001308 return NO_ERROR;
1309}
1310
1311
Eric Laurente0720872014-03-11 09:30:41 -07001312status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001313 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001314 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001315{
1316 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1317 ssize_t index = mOutputs.indexOfKey(output);
1318 if (index < 0) {
1319 ALOGW("stopOutput() unknown output %d", output);
1320 return BAD_VALUE;
1321 }
1322
Eric Laurentc75307b2015-03-17 15:29:32 -07001323 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001324
Eric Laurentc75307b2015-03-17 15:29:32 -07001325 if (outputDesc->mRefCount[stream] == 1) {
1326 // Automatically disable the remote submix input when output is stopped on a
1327 // re routing mix of type MIX_TYPE_RECORDERS
1328 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1329 outputDesc->mPolicyMix != NULL &&
1330 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1331 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1332 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001333 outputDesc->mPolicyMix->mDeviceAddress,
Eric Laurentc75307b2015-03-17 15:29:32 -07001334 "remote-submix");
1335 }
1336 }
1337
1338 // Routing?
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001339 bool forceDeviceUpdate = false;
Eric Laurentc75307b2015-03-17 15:29:32 -07001340 if (outputDesc->mRefCount[stream] > 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001341 int activityCount = mOutputRoutes.decRouteActivity(session);
1342 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1343
1344 if (forceDeviceUpdate) {
1345 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1346 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001347 }
1348
Eric Laurent3974e3b2017-12-07 17:58:43 -08001349 status_t status = stopSource(outputDesc, stream, forceDeviceUpdate);
1350
Eric Laurent733ce942017-12-07 12:18:25 -08001351 if (status == NO_ERROR ) {
1352 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001353 }
1354 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001355}
1356
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001357status_t AudioPolicyManager::stopSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001358 audio_stream_type_t stream,
1359 bool forceDeviceUpdate)
Eric Laurentc75307b2015-03-17 15:29:32 -07001360{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001361 // always handle stream stop, check which stream type is stopping
1362 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1363
Eric Laurente552edb2014-03-10 17:42:56 -07001364 if (outputDesc->mRefCount[stream] > 0) {
1365 // decrement usage count of this stream on the output
1366 outputDesc->changeRefCount(stream, -1);
Paul McLeanaa981192015-03-21 09:55:15 -07001367
Eric Laurente552edb2014-03-10 17:42:56 -07001368 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001369 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001370 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001371 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001372 // delay the device switch by twice the latency because stopOutput() is executed when
1373 // the track stop() command is received and at that time the audio track buffer can
1374 // still contain data that needs to be drained. The latency only covers the audio HAL
1375 // and kernel buffers. Also the latency does not always include additional delay in the
1376 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001377 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001378
1379 // force restoring the device selection on other active outputs if it differs from the
1380 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001381 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001382 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001383 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001384 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001385 desc->isActive() &&
1386 outputDesc->sharesHwModuleWith(desc) &&
1387 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001388 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1389 bool force = desc->device() != newDevice2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001390
Eric Laurentc75307b2015-03-17 15:29:32 -07001391 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001392 newDevice2,
1393 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001394 delayMs);
1395 // re-apply device specific volume if not done by setOutputDevice()
1396 if (!force) {
1397 applyStreamVolumes(desc, newDevice2, delayMs);
1398 }
Eric Laurente552edb2014-03-10 17:42:56 -07001399 }
1400 }
1401 // update the outputs if stopping one with a stream that can affect notification routing
1402 handleNotificationRoutingForStream(stream);
1403 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001404
1405 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1406 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1407 setStrategyMute(STRATEGY_SONIFICATION, false, outputDesc);
1408 }
1409
Eric Laurent36829f92017-04-07 19:04:42 -07001410 if (stream == AUDIO_STREAM_MUSIC) {
1411 selectOutputForMusicEffects();
1412 }
Eric Laurente552edb2014-03-10 17:42:56 -07001413 return NO_ERROR;
1414 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001415 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001416 return INVALID_OPERATION;
1417 }
1418}
1419
Eric Laurente83b55d2014-11-14 10:06:21 -08001420void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001421 audio_stream_type_t stream __unused,
1422 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001423{
1424 ALOGV("releaseOutput() %d", output);
1425 ssize_t index = mOutputs.indexOfKey(output);
1426 if (index < 0) {
1427 ALOGW("releaseOutput() releasing unknown output %d", output);
1428 return;
1429 }
1430
Paul McLeanaa981192015-03-21 09:55:15 -07001431 // Routing
1432 mOutputRoutes.removeRoute(session);
1433
Eric Laurentc75307b2015-03-17 15:29:32 -07001434 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001435 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001436 if (desc->mDirectOpenCount <= 0) {
1437 ALOGW("releaseOutput() invalid open count %d for output %d",
1438 desc->mDirectOpenCount, output);
1439 return;
1440 }
1441 if (--desc->mDirectOpenCount == 0) {
1442 closeOutput(output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001443 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001444 }
1445 }
1446}
1447
1448
Eric Laurentcaf7f482014-11-25 17:50:47 -08001449status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1450 audio_io_handle_t *input,
1451 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001452 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001453 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001454 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001455 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001456 input_type_t *inputType,
1457 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001458{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001459 ALOGV("getInputForAttr() source %d, sampling rate %d, format %#x, channel mask %#x,"
Eric Laurentcaf7f482014-11-25 17:50:47 -08001460 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001461 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001462
Eric Laurentad2e7b92017-09-14 20:06:42 -07001463 status_t status = NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -08001464 // handle legacy remote submix case where the address was not always specified
1465 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001466 audio_source_t halInputSource;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001467 audio_source_t inputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001468 AudioMix *policyMix = NULL;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001469 DeviceVector inputDevices;
Eric Laurent20b9ef02016-12-05 11:03:16 -08001470
Eric Laurentfe231122017-11-17 17:48:06 -08001471 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1472 inputSource = AUDIO_SOURCE_MIC;
1473 }
1474
Paul McLean466dc8e2015-04-17 13:15:36 -06001475 // Explicit routing?
1476 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -07001477 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
jiabinc0c831a2018-01-29 17:55:15 -08001478 deviceDesc = mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001479 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001480 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
Paul McLean466dc8e2015-04-17 13:15:36 -06001481
Eric Laurentad2e7b92017-09-14 20:06:42 -07001482 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1483 // possible
1484 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1485 *input != AUDIO_IO_HANDLE_NONE) {
1486 ssize_t index = mInputs.indexOfKey(*input);
1487 if (index < 0) {
1488 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1489 status = BAD_VALUE;
1490 goto error;
1491 }
1492 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1493 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1494 if (audioSession == 0) {
1495 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1496 status = BAD_VALUE;
1497 goto error;
1498 }
1499 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1500 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001501 // corresponds to a new client and is only permitted from the same UID.
1502 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurentad2e7b92017-09-14 20:06:42 -07001503 if (audioSession->openCount() == 1) {
1504 audioSession->setUid(uid);
1505 } else if (audioSession->uid() != uid) {
Eric Laurent331679c2018-04-16 17:03:16 -07001506 if (!audioSession->isSilenced()) {
1507 ALOGW("getInputForAttr() bad uid %d for session %d uid %d",
1508 uid, session, audioSession->uid());
1509 status = INVALID_OPERATION;
1510 goto error;
1511 }
1512 audioSession->setUid(uid);
1513 audioSession->setSilenced(false);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001514 }
1515 audioSession->changeOpenCount(1);
1516 *inputType = API_INPUT_LEGACY;
1517 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1518 *portId = AudioPort::getNextUniqueId();
1519 }
Mikhail Naganov708e0382018-05-30 09:53:04 -07001520 inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(inputDesc->mDevice);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001521 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1522 : AUDIO_PORT_HANDLE_NONE;
1523 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
1524
1525 return NO_ERROR;
1526 }
1527
1528 *input = AUDIO_IO_HANDLE_NONE;
1529 *inputType = API_INPUT_INVALID;
1530
Eric Laurentad2e7b92017-09-14 20:06:42 -07001531 halInputSource = inputSource;
1532
1533 // TODO: check for existing client for this port ID
1534 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1535 *portId = AudioPort::getNextUniqueId();
1536 }
1537
1538 audio_devices_t device;
1539
Eric Laurentc447ded2015-01-06 08:47:05 -08001540 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001541 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001542 status = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
1543 if (status != NO_ERROR) {
1544 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001545 }
1546 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001547 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1548 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001549 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001550 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001551 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001552 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001553 status = BAD_VALUE;
1554 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001555 }
Eric Laurentc722f302014-12-10 11:21:49 -08001556 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001557 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001558 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1559 // there is an external policy, but this input is attached to a mix of recorders,
1560 // meaning it receives audio injected into the framework, so the recorder doesn't
1561 // know about it and is therefore considered "legacy"
1562 *inputType = API_INPUT_LEGACY;
1563 } else {
1564 // recording a mix of players defined by an external policy, we're rerouting for
1565 // an external policy
1566 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1567 }
Eric Laurentc722f302014-12-10 11:21:49 -08001568 } else if (audio_is_remote_submix_device(device)) {
1569 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001570 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001571 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1572 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001573 } else {
1574 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001575 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001576
Eric Laurent599c7582015-12-07 18:05:55 -08001577 }
1578
1579 *input = getInputForDevice(device, address, session, uid, inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001580 config, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001581 policyMix);
1582 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001583 status = INVALID_OPERATION;
1584 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001585 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001586
Mikhail Naganov708e0382018-05-30 09:53:04 -07001587 inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -07001588 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1589 : AUDIO_PORT_HANDLE_NONE;
1590
1591 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d",
1592 *input, *inputType, *selectedDeviceId);
1593
Eric Laurent599c7582015-12-07 18:05:55 -08001594 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001595
1596error:
1597 mInputRoutes.removeRoute(session);
1598 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001599}
1600
1601
1602audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1603 String8 address,
1604 audio_session_t session,
1605 uid_t uid,
1606 audio_source_t inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001607 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08001608 audio_input_flags_t flags,
1609 AudioMix *policyMix)
1610{
1611 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1612 audio_source_t halInputSource = inputSource;
1613 bool isSoundTrigger = false;
1614
1615 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1616 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1617 if (index >= 0) {
1618 input = mSoundTriggerSessions.valueFor(session);
1619 isSoundTrigger = true;
1620 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1621 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1622 } else {
1623 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001624 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001625 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08001626 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001627 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001628 }
1629
Andy Hungf129b032015-04-07 13:45:50 -07001630 // find a compatible input profile (not necessarily identical in parameters)
1631 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08001632 // sampling rate and flags may be updated by getInputProfile
1633 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
1634 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07001635 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08001636 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07001637 audio_input_flags_t profileFlags = flags;
1638 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07001639 profileFormat = config->format; // reset each time through loop, in case it is updated
Eric Laurent275e8e92014-11-30 15:14:47 -08001640 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001641 profileSamplingRate, profileFormat, profileChannelMask,
1642 profileFlags);
1643 if (profile != 0) {
1644 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001645 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1646 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001647 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1648 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1649 } else { // fail
Glenn Kastenfaa10a62017-05-25 15:52:05 -07001650 ALOGW("getInputForDevice() could not find profile for device 0x%X, "
Eric Laurentfe231122017-11-17 17:48:06 -08001651 "sampling rate %u, format %#x, channel mask 0x%X, flags %#x",
1652 device, config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001653 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001654 }
Eric Laurente552edb2014-03-10 17:42:56 -07001655 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001656 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08001657 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08001658 if (samplingRate == 0) {
1659 samplingRate = profileSamplingRate;
1660 }
Eric Laurente552edb2014-03-10 17:42:56 -07001661
Eric Laurent322b4d22015-04-03 15:57:54 -07001662 if (profile->getModuleHandle() == 0) {
1663 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001664 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001665 }
1666
Eric Laurent599c7582015-12-07 18:05:55 -08001667 sp<AudioSession> audioSession = new AudioSession(session,
Eric Laurentfe231122017-11-17 17:48:06 -08001668 inputSource,
1669 config->format,
1670 samplingRate,
1671 config->channel_mask,
1672 flags,
1673 uid,
1674 isSoundTrigger,
1675 policyMix, mpClientInterface);
Eric Laurent599c7582015-12-07 18:05:55 -08001676
Eric Laurent74708e72017-04-07 17:13:42 -07001677// FIXME: disable concurrent capture until UI is ready
1678#if 0
Eric Laurent599c7582015-12-07 18:05:55 -08001679 // reuse an open input if possible
Eric Laurent555530a2017-02-07 18:17:24 -08001680 sp<AudioInputDescriptor> reusedInputDesc;
Eric Laurent599c7582015-12-07 18:05:55 -08001681 for (size_t i = 0; i < mInputs.size(); i++) {
1682 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001683 // reuse input if:
1684 // - it shares the same profile
1685 // AND
1686 // - it is not a reroute submix input
1687 // AND
1688 // - it is: not used for sound trigger
1689 // OR
1690 // used for sound trigger and all clients use the same session ID
1691 //
1692 if ((profile == desc->mProfile) &&
1693 (isSoundTrigger == desc->isSoundTrigger()) &&
1694 !is_virtual_input_device(device)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001695
1696 sp<AudioSession> as = desc->getAudioSession(session);
1697 if (as != 0) {
1698 // do not allow unmatching properties on same session
1699 if (as->matches(audioSession)) {
1700 as->changeOpenCount(1);
1701 } else {
1702 ALOGW("getInputForDevice() record with different attributes"
1703 " exists for session %d", session);
Eric Laurent555530a2017-02-07 18:17:24 -08001704 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001705 }
Eric Laurentfb66dd92016-01-28 18:32:03 -08001706 } else if (isSoundTrigger) {
Eric Laurent555530a2017-02-07 18:17:24 -08001707 continue;
Eric Laurentfb66dd92016-01-28 18:32:03 -08001708 }
Eric Laurentbb948092017-01-23 18:33:30 -08001709
Eric Laurent555530a2017-02-07 18:17:24 -08001710 // Reuse the already opened input stream on this profile if:
1711 // - the new capture source is background OR
1712 // - the path requested configurations match OR
1713 // - the new source priority is less than the highest source priority on this input
1714 // If the input stream cannot be reused, close it before opening a new stream
1715 // on the same profile for the new client so that the requested path configuration
1716 // can be selected.
1717 if (!isConcurrentSource(inputSource) &&
Eric Laurentbb948092017-01-23 18:33:30 -08001718 ((desc->mSamplingRate != samplingRate ||
Eric Laurentfe231122017-11-17 17:48:06 -08001719 desc->mChannelMask != config->channel_mask ||
1720 !audio_formats_match(desc->mFormat, config->format)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001721 (source_priority(desc->getHighestPrioritySource(false /*activeOnly*/)) <
Eric Laurentbb948092017-01-23 18:33:30 -08001722 source_priority(inputSource)))) {
Eric Laurent555530a2017-02-07 18:17:24 -08001723 reusedInputDesc = desc;
1724 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001725 } else {
1726 desc->addAudioSession(session, audioSession);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001727 ALOGV("%s: reusing input %d", __FUNCTION__, mInputs.keyAt(i));
1728 return mInputs.keyAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08001729 }
Eric Laurent599c7582015-12-07 18:05:55 -08001730 }
1731 }
Eric Laurent599c7582015-12-07 18:05:55 -08001732
Eric Laurent555530a2017-02-07 18:17:24 -08001733 if (reusedInputDesc != 0) {
1734 AudioSessionCollection sessions = reusedInputDesc->getAudioSessions(false /*activeOnly*/);
1735 for (size_t j = 0; j < sessions.size(); j++) {
1736 audio_session_t currentSession = sessions.keyAt(j);
1737 stopInput(reusedInputDesc->mIoHandle, currentSession);
1738 releaseInput(reusedInputDesc->mIoHandle, currentSession);
1739 }
1740 }
Eric Laurent74708e72017-04-07 17:13:42 -07001741#endif
Eric Laurent555530a2017-02-07 18:17:24 -08001742
Eric Laurent3974e3b2017-12-07 17:58:43 -08001743 if (!profile->canOpenNewIo()) {
1744 return AUDIO_IO_HANDLE_NONE;
1745 }
1746
Eric Laurentfe231122017-11-17 17:48:06 -08001747 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001748
Eric Laurentfe231122017-11-17 17:48:06 -08001749 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
1750 lConfig.sample_rate = profileSamplingRate;
1751 lConfig.channel_mask = profileChannelMask;
1752 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07001753
Eric Laurent53b810e2017-12-10 17:25:10 -08001754 if (address == "") {
Mikhail Naganov708e0382018-05-30 09:53:04 -07001755 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -08001756 // the inputs vector must be of size >= 1, but we don't want to crash here
1757 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress : String8("");
1758 }
1759
Eric Laurentfe231122017-11-17 17:48:06 -08001760 status_t status = inputDesc->open(&lConfig, device, address,
1761 halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001762
1763 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001764 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08001765 (profileSamplingRate != lConfig.sample_rate) ||
1766 !audio_formats_match(profileFormat, lConfig.format) ||
1767 (profileChannelMask != lConfig.channel_mask)) {
1768 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001769 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08001770 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001771 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001772 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07001773 }
Eric Laurent599c7582015-12-07 18:05:55 -08001774 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001775 }
1776
Eric Laurentc722f302014-12-10 11:21:49 -08001777 inputDesc->mPolicyMix = policyMix;
Eric Laurent599c7582015-12-07 18:05:55 -08001778 inputDesc->addAudioSession(session, audioSession);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001779
Eric Laurent599c7582015-12-07 18:05:55 -08001780 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001781 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001782
Eric Laurent599c7582015-12-07 18:05:55 -08001783 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001784}
1785
Eric Laurentbb948092017-01-23 18:33:30 -08001786//static
1787bool AudioPolicyManager::isConcurrentSource(audio_source_t source)
1788{
1789 return (source == AUDIO_SOURCE_HOTWORD) ||
1790 (source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
1791 (source == AUDIO_SOURCE_FM_TUNER);
1792}
1793
Eric Laurentfb66dd92016-01-28 18:32:03 -08001794bool AudioPolicyManager::isConcurentCaptureAllowed(const sp<AudioInputDescriptor>& inputDesc,
1795 const sp<AudioSession>& audioSession)
1796{
1797 // Do not allow capture if an active voice call is using a software patch and
1798 // the call TX source device is on the same HW module.
1799 // FIXME: would be better to refine to only inputs whose profile connects to the
1800 // call TX device but this information is not in the audio patch
1801 if (mCallTxPatch != 0 &&
1802 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1803 return false;
1804 }
1805
1806 // starting concurrent capture is enabled if:
1807 // 1) capturing for re-routing
1808 // 2) capturing for HOTWORD source
1809 // 3) capturing for FM TUNER source
1810 // 3) All other active captures are either for re-routing or HOTWORD
1811
1812 if (is_virtual_input_device(inputDesc->mDevice) ||
Eric Laurentbb948092017-01-23 18:33:30 -08001813 isConcurrentSource(audioSession->inputSource())) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001814 return true;
1815 }
1816
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001817 for (const auto& activeInput : mInputs.getActiveInputs()) {
Eric Laurentbb948092017-01-23 18:33:30 -08001818 if (!isConcurrentSource(activeInput->inputSource(true)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001819 !is_virtual_input_device(activeInput->mDevice)) {
1820 return false;
1821 }
1822 }
1823
1824 return true;
1825}
1826
Chris Thornton2b864642017-06-27 21:26:07 -07001827// FIXME: remove when concurrent capture is ready. This is a hack to work around bug b/63083537.
1828bool AudioPolicyManager::soundTriggerSupportsConcurrentCapture() {
1829 if (!mHasComputedSoundTriggerSupportsConcurrentCapture) {
1830 bool soundTriggerSupportsConcurrentCapture = false;
1831 unsigned int numModules = 0;
1832 struct sound_trigger_module_descriptor* nModules = NULL;
1833
1834 status_t status = SoundTrigger::listModules(nModules, &numModules);
1835 if (status == NO_ERROR && numModules != 0) {
1836 nModules = (struct sound_trigger_module_descriptor*) calloc(
1837 numModules, sizeof(struct sound_trigger_module_descriptor));
1838 if (nModules == NULL) {
1839 // We failed to malloc the buffer, so just say no for now, and hope that we have more
1840 // ram the next time this function is called.
1841 ALOGE("Failed to allocate buffer for module descriptors");
1842 return false;
1843 }
1844
1845 status = SoundTrigger::listModules(nModules, &numModules);
1846 if (status == NO_ERROR) {
1847 soundTriggerSupportsConcurrentCapture = true;
1848 for (size_t i = 0; i < numModules; ++i) {
1849 soundTriggerSupportsConcurrentCapture &=
1850 nModules[i].properties.concurrent_capture;
1851 }
1852 }
1853 free(nModules);
1854 }
1855 mSoundTriggerSupportsConcurrentCapture = soundTriggerSupportsConcurrentCapture;
1856 mHasComputedSoundTriggerSupportsConcurrentCapture = true;
1857 }
1858 return mSoundTriggerSupportsConcurrentCapture;
1859}
1860
Eric Laurentfb66dd92016-01-28 18:32:03 -08001861
Eric Laurent4dc68062014-07-28 17:26:49 -07001862status_t AudioPolicyManager::startInput(audio_io_handle_t input,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001863 audio_session_t session,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001864 bool silenced,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001865 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07001866{
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001867
1868 ALOGV("AudioPolicyManager::startInput(input:%d, session:%d, silenced:%d, concurrency:%d)",
1869 input, session, silenced, *concurrency);
1870
Eric Laurentfb66dd92016-01-28 18:32:03 -08001871 *concurrency = API_INPUT_CONCURRENCY_NONE;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001872
Eric Laurente552edb2014-03-10 17:42:56 -07001873 ssize_t index = mInputs.indexOfKey(input);
1874 if (index < 0) {
1875 ALOGW("startInput() unknown input %d", input);
1876 return BAD_VALUE;
1877 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001878 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001879
Eric Laurent599c7582015-12-07 18:05:55 -08001880 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1881 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07001882 ALOGW("startInput() unknown session %d on input %d", session, input);
1883 return BAD_VALUE;
1884 }
1885
Eric Laurent74708e72017-04-07 17:13:42 -07001886// FIXME: disable concurrent capture until UI is ready
1887#if 0
Eric Laurentfb66dd92016-01-28 18:32:03 -08001888 if (!isConcurentCaptureAllowed(inputDesc, audioSession)) {
1889 ALOGW("startInput(%d) failed: other input already started", input);
1890 return INVALID_OPERATION;
1891 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001892
Eric Laurentfb66dd92016-01-28 18:32:03 -08001893 if (isInCall()) {
1894 *concurrency |= API_INPUT_CONCURRENCY_CALL;
1895 }
Eric Laurentf7c50102016-09-30 15:19:43 -07001896 if (mInputs.activeInputsCountOnDevices() != 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001897 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurente552edb2014-03-10 17:42:56 -07001898 }
Eric Laurent74708e72017-04-07 17:13:42 -07001899#else
1900 if (!is_virtual_input_device(inputDesc->mDevice)) {
1901 if (mCallTxPatch != 0 &&
1902 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1903 ALOGW("startInput(%d) failed: call in progress", input);
Ray Essick84e84a52018-05-03 18:45:07 -07001904 *concurrency |= API_INPUT_CONCURRENCY_CALL;
Eric Laurent74708e72017-04-07 17:13:42 -07001905 return INVALID_OPERATION;
1906 }
1907
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001908 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07001909
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001910 // If a UID is idle and records silence and another not silenced recording starts
1911 // from another UID (idle or active) we stop the current idle UID recording in
1912 // favor of the new one - "There can be only one" TM
1913 if (!silenced) {
1914 for (const auto& activeDesc : activeInputs) {
1915 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
1916 activeDesc->getId() == inputDesc->getId()) {
1917 continue;
1918 }
1919
1920 AudioSessionCollection activeSessions = activeDesc->getAudioSessions(
1921 true /*activeOnly*/);
1922 sp<AudioSession> activeSession = activeSessions.valueAt(0);
1923 if (activeSession->isSilenced()) {
1924 audio_io_handle_t activeInput = activeDesc->mIoHandle;
1925 audio_session_t activeSessionId = activeSession->session();
1926 stopInput(activeInput, activeSessionId);
1927 releaseInput(activeInput, activeSessionId);
1928 ALOGV("startInput(%d) stopping silenced input %d", input, activeInput);
1929 activeInputs = mInputs.getActiveInputs();
1930 }
1931 }
1932 }
1933
1934 for (const auto& activeDesc : activeInputs) {
Eric Laurentcb4dae22017-07-01 19:39:32 -07001935 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
1936 activeDesc->getId() == inputDesc->getId()) {
1937 continue;
1938 }
1939
Eric Laurent74708e72017-04-07 17:13:42 -07001940 audio_source_t activeSource = activeDesc->inputSource(true);
1941 if (audioSession->inputSource() == AUDIO_SOURCE_HOTWORD) {
1942 if (activeSource == AUDIO_SOURCE_HOTWORD) {
1943 if (activeDesc->hasPreemptedSession(session)) {
1944 ALOGW("startInput(%d) failed for HOTWORD: "
1945 "other input %d already started for HOTWORD",
1946 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07001947 *concurrency |= API_INPUT_CONCURRENCY_HOTWORD;
Eric Laurent74708e72017-04-07 17:13:42 -07001948 return INVALID_OPERATION;
1949 }
1950 } else {
1951 ALOGV("startInput(%d) failed for HOTWORD: other input %d already started",
1952 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07001953 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07001954 return INVALID_OPERATION;
1955 }
1956 } else {
1957 if (activeSource != AUDIO_SOURCE_HOTWORD) {
1958 ALOGW("startInput(%d) failed: other input %d already started",
1959 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07001960 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07001961 return INVALID_OPERATION;
1962 }
1963 }
1964 }
1965
Chris Thornton2b864642017-06-27 21:26:07 -07001966 // We only need to check if the sound trigger session supports concurrent capture if the
1967 // input is also a sound trigger input. Otherwise, we should preempt any hotword stream
1968 // that's running.
1969 const bool allowConcurrentWithSoundTrigger =
1970 inputDesc->isSoundTrigger() ? soundTriggerSupportsConcurrentCapture() : false;
1971
Eric Laurent74708e72017-04-07 17:13:42 -07001972 // if capture is allowed, preempt currently active HOTWORD captures
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001973 for (const auto& activeDesc : activeInputs) {
Chris Thornton2b864642017-06-27 21:26:07 -07001974 if (allowConcurrentWithSoundTrigger && activeDesc->isSoundTrigger()) {
1975 continue;
1976 }
1977
Eric Laurent74708e72017-04-07 17:13:42 -07001978 audio_source_t activeSource = activeDesc->inputSource(true);
1979 if (activeSource == AUDIO_SOURCE_HOTWORD) {
1980 AudioSessionCollection activeSessions =
1981 activeDesc->getAudioSessions(true /*activeOnly*/);
1982 audio_session_t activeSession = activeSessions.keyAt(0);
1983 audio_io_handle_t activeHandle = activeDesc->mIoHandle;
1984 SortedVector<audio_session_t> sessions = activeDesc->getPreemptedSessions();
Ray Essick84e84a52018-05-03 18:45:07 -07001985 *concurrency |= API_INPUT_CONCURRENCY_PREEMPT;
Eric Laurent74708e72017-04-07 17:13:42 -07001986 sessions.add(activeSession);
1987 inputDesc->setPreemptedSessions(sessions);
1988 stopInput(activeHandle, activeSession);
1989 releaseInput(activeHandle, activeSession);
1990 ALOGV("startInput(%d) for HOTWORD preempting HOTWORD input %d",
1991 input, activeDesc->mIoHandle);
1992 }
1993 }
1994 }
1995#endif
Eric Laurente552edb2014-03-10 17:42:56 -07001996
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001997 // Make sure we start with the correct silence state
1998 audioSession->setSilenced(silenced);
1999
Eric Laurent313d1e72016-01-29 09:56:57 -08002000 // increment activity count before calling getNewInputDevice() below as only active sessions
2001 // are considered for device selection
2002 audioSession->changeActiveCount(1);
2003
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002004 // Routing?
2005 mInputRoutes.incRouteActivity(session);
2006
Eric Laurent2157f5b2018-04-25 18:33:02 -07002007 if (audioSession->activeCount() == 1 || mInputRoutes.getAndClearRouteChanged(session)) {
Eric Laurent271a93e2016-09-29 14:47:06 -07002008 // indicate active capture to sound trigger service if starting capture from a mic on
2009 // primary HW module
Eric Laurentf7c50102016-09-30 15:19:43 -07002010 audio_devices_t device = getNewInputDevice(inputDesc);
Eric Laurent271a93e2016-09-29 14:47:06 -07002011 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002012
Eric Laurent733ce942017-12-07 12:18:25 -08002013 status_t status = inputDesc->start();
2014 if (status != NO_ERROR) {
2015 mInputRoutes.decRouteActivity(session);
2016 audioSession->changeActiveCount(-1);
2017 return status;
2018 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002019
Eric Laurent733ce942017-12-07 12:18:25 -08002020 if (inputDesc->getAudioSessionCount(true/*activeOnly*/) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002021 // if input maps to a dynamic policy with an activity listener, notify of state change
2022 if ((inputDesc->mPolicyMix != NULL)
2023 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2024 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2025 MIX_STATE_MIXING);
Eric Laurentc722f302014-12-10 11:21:49 -08002026 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002027
Eric Laurentf7c50102016-09-30 15:19:43 -07002028 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2029 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Eric Laurent05b345e2016-11-18 12:36:27 -08002030 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002031 SoundTrigger::setCaptureState(true);
2032 }
2033
2034 // automatically enable the remote submix output when input is started if not
2035 // used by a policy mix of type MIX_TYPE_RECORDERS
2036 // For remote submix (a virtual device), we open only one input per capture request.
2037 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2038 String8 address = String8("");
2039 if (inputDesc->mPolicyMix == NULL) {
2040 address = String8("0");
2041 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2042 address = inputDesc->mPolicyMix->mDeviceAddress;
2043 }
2044 if (address != "") {
2045 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2046 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2047 address, "remote-submix");
2048 }
Eric Laurentc722f302014-12-10 11:21:49 -08002049 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002050 }
Eric Laurente552edb2014-03-10 17:42:56 -07002051 }
2052
Eric Laurent599c7582015-12-07 18:05:55 -08002053 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
Eric Laurente552edb2014-03-10 17:42:56 -07002054
Eric Laurente552edb2014-03-10 17:42:56 -07002055 return NO_ERROR;
2056}
2057
Eric Laurent4dc68062014-07-28 17:26:49 -07002058status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
2059 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07002060{
2061 ALOGV("stopInput() input %d", input);
2062 ssize_t index = mInputs.indexOfKey(input);
2063 if (index < 0) {
2064 ALOGW("stopInput() unknown input %d", input);
2065 return BAD_VALUE;
2066 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002067 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07002068
Eric Laurent599c7582015-12-07 18:05:55 -08002069 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07002070 if (index < 0) {
2071 ALOGW("stopInput() unknown session %d on input %d", session, input);
2072 return BAD_VALUE;
2073 }
2074
Eric Laurent599c7582015-12-07 18:05:55 -08002075 if (audioSession->activeCount() == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002076 ALOGW("stopInput() input %d already stopped", input);
2077 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002078 }
2079
Eric Laurent599c7582015-12-07 18:05:55 -08002080 audioSession->changeActiveCount(-1);
Paul McLean466dc8e2015-04-17 13:15:36 -06002081
2082 // Routing?
2083 mInputRoutes.decRouteActivity(session);
2084
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002085 if (audioSession->activeCount() == 0) {
Eric Laurent733ce942017-12-07 12:18:25 -08002086 inputDesc->stop();
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002087 if (inputDesc->isActive()) {
2088 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2089 } else {
2090 // if input maps to a dynamic policy with an activity listener, notify of state change
2091 if ((inputDesc->mPolicyMix != NULL)
2092 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2093 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2094 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002095 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002096
2097 // automatically disable the remote submix output when input is stopped if not
2098 // used by a policy mix of type MIX_TYPE_RECORDERS
2099 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2100 String8 address = String8("");
2101 if (inputDesc->mPolicyMix == NULL) {
2102 address = String8("0");
2103 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2104 address = inputDesc->mPolicyMix->mDeviceAddress;
2105 }
2106 if (address != "") {
2107 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2108 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2109 address, "remote-submix");
2110 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002111 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002112
Eric Laurentf7c50102016-09-30 15:19:43 -07002113 audio_devices_t device = inputDesc->mDevice;
Eric Laurentfb66dd92016-01-28 18:32:03 -08002114 resetInputDevice(input);
Eric Laurent84332aa2016-01-28 22:19:18 +00002115
Eric Laurentf7c50102016-09-30 15:19:43 -07002116 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2117 // primary HW module
2118 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2119 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2120 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08002121 SoundTrigger::setCaptureState(false);
2122 }
2123 inputDesc->clearPreemptedSessions();
Eric Laurent84332aa2016-01-28 22:19:18 +00002124 }
Eric Laurente552edb2014-03-10 17:42:56 -07002125 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002126 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002127}
2128
Eric Laurent4dc68062014-07-28 17:26:49 -07002129void AudioPolicyManager::releaseInput(audio_io_handle_t input,
2130 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07002131{
2132 ALOGV("releaseInput() %d", input);
2133 ssize_t index = mInputs.indexOfKey(input);
2134 if (index < 0) {
2135 ALOGW("releaseInput() releasing unknown input %d", input);
2136 return;
2137 }
Paul McLean466dc8e2015-04-17 13:15:36 -06002138
2139 // Routing
2140 mInputRoutes.removeRoute(session);
2141
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002142 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
2143 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07002144
Eric Laurent599c7582015-12-07 18:05:55 -08002145 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
vivek mehta587b8df2017-01-31 14:58:44 -08002146 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07002147 ALOGW("releaseInput() unknown session %d on input %d", session, input);
2148 return;
2149 }
Eric Laurent599c7582015-12-07 18:05:55 -08002150
2151 if (audioSession->openCount() == 0) {
2152 ALOGW("releaseInput() invalid open count %d on session %d",
2153 audioSession->openCount(), session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002154 return;
2155 }
Eric Laurent599c7582015-12-07 18:05:55 -08002156
2157 if (audioSession->changeOpenCount(-1) == 0) {
2158 inputDesc->removeAudioSession(session);
2159 }
2160
Jean-Michel Trivi65bfe912015-12-04 15:56:47 -08002161 if (inputDesc->getOpenRefCount() > 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002162 ALOGV("releaseInput() exit > 0");
2163 return;
2164 }
2165
Eric Laurent05b90f82014-08-27 15:32:29 -07002166 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002167 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002168 ALOGV("releaseInput() exit");
2169}
2170
Eric Laurentd4692962014-05-05 18:13:44 -07002171void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002172 bool patchRemoved = false;
2173
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002174 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002175 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002176 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002177 if (patch_index >= 0) {
2178 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002179 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002180 mAudioPatches.removeItemsAt(patch_index);
2181 patchRemoved = true;
2182 }
Eric Laurentfe231122017-11-17 17:48:06 -08002183 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002184 }
jiabin829a00b2018-04-04 16:28:32 -07002185 mInputRoutes.clear();
Eric Laurentd4692962014-05-05 18:13:44 -07002186 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002187 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002188 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002189
2190 if (patchRemoved) {
2191 mpClientInterface->onAudioPatchListUpdate();
2192 }
Eric Laurentd4692962014-05-05 18:13:44 -07002193}
2194
Eric Laurente0720872014-03-11 09:30:41 -07002195void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002196 int indexMin,
2197 int indexMax)
2198{
2199 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002200 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002201
2202 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002203 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2204 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002205 continue;
2206 }
2207 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002208 }
Eric Laurente552edb2014-03-10 17:42:56 -07002209}
2210
Eric Laurente0720872014-03-11 09:30:41 -07002211status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002212 int index,
2213 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002214{
2215
Nadav Bar7c605f62017-12-25 00:01:52 +02002216 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2217 // app that has MODIFY_PHONE_STATE permission.
2218 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
2219 !(stream == AUDIO_STREAM_VOICE_CALL && index == 0)) ||
François Gaffied1ab2bd2015-12-02 18:20:06 +01002220 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002221 return BAD_VALUE;
2222 }
2223 if (!audio_is_output_device(device)) {
2224 return BAD_VALUE;
2225 }
2226
2227 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002228 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002229
Eric Laurent1fd372e2016-04-06 14:23:53 -07002230 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002231 stream, device, index);
2232
Eric Laurent28d09f02016-03-08 10:43:05 -08002233 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002234 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2235 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002236 continue;
2237 }
2238 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2239 }
Eric Laurente552edb2014-03-10 17:42:56 -07002240
Eric Laurent1fd372e2016-04-06 14:23:53 -07002241 // update volume on all outputs and streams matching the following:
2242 // - The requested stream (or a stream matching for volume control) is active on the output
2243 // - The device (or devices) selected by the strategy corresponding to this stream includes
2244 // the requested device
2245 // - For non default requested device, currently selected device on the output is either the
2246 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002247 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2248 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002249 status_t status = NO_ERROR;
2250 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002251 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2252 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08002253 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
Eric Laurentdcd4ab12018-06-29 17:45:13 -07002254 if (!(streamsMatchForvolume(stream, (audio_stream_type_t)curStream) || isInCall())) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002255 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002256 }
Eric Laurentdcd4ab12018-06-29 17:45:13 -07002257 if (!(desc->isStreamActive((audio_stream_type_t)curStream) || isInCall())) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002258 continue;
2259 }
Eric Laurent794fde22016-03-11 09:50:45 -08002260 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002261 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2262 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002263 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2264 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002265 continue;
2266 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002267 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002268 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002269 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07002270 applyVolume = (curDevice & curStreamDevice) != 0;
2271 } else {
2272 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002273 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002274 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002275
Eric Laurente76f29c2016-09-14 17:17:53 -07002276 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002277 //FIXME: workaround for truncated touch sounds
2278 // delayed volume change for system stream to be removed when the problem is
2279 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002280 status_t volStatus =
Eric Laurentdc462862016-07-19 12:29:53 -07002281 checkAndSetVolume((audio_stream_type_t)curStream, index, desc, curDevice,
2282 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002283 if (volStatus != NO_ERROR) {
2284 status = volStatus;
2285 }
2286 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002287 }
Eric Laurente552edb2014-03-10 17:42:56 -07002288 }
2289 return status;
2290}
2291
Eric Laurente0720872014-03-11 09:30:41 -07002292status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002293 int *index,
2294 audio_devices_t device)
2295{
2296 if (index == NULL) {
2297 return BAD_VALUE;
2298 }
2299 if (!audio_is_output_device(device)) {
2300 return BAD_VALUE;
2301 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002302 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002303 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002304 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002305 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2306 }
François Gaffiedfd74092015-03-19 12:10:59 +01002307 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002308
François Gaffied1ab2bd2015-12-02 18:20:06 +01002309 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002310 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2311 return NO_ERROR;
2312}
2313
Eric Laurent36829f92017-04-07 19:04:42 -07002314audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002315{
2316 // select one output among several suitable for global effects.
2317 // The priority is as follows:
2318 // 1: An offloaded output. If the effect ends up not being offloadable,
2319 // AudioFlinger will invalidate the track and the offloaded output
2320 // will be closed causing the effect to be moved to a PCM output.
2321 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002322 // 3: The primary output
2323 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002324
Eric Laurent3b73df72014-03-11 09:06:29 -07002325 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002326 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent36829f92017-04-07 19:04:42 -07002327 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002328
Eric Laurent36829f92017-04-07 19:04:42 -07002329 if (outputs.size() == 0) {
2330 return AUDIO_IO_HANDLE_NONE;
2331 }
Eric Laurente552edb2014-03-10 17:42:56 -07002332
Eric Laurent36829f92017-04-07 19:04:42 -07002333 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2334 bool activeOnly = true;
2335
2336 while (output == AUDIO_IO_HANDLE_NONE) {
2337 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2338 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2339 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2340
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002341 for (audio_io_handle_t output : outputs) {
2342 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002343 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2344 continue;
2345 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002346 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2347 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002348 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002349 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002350 }
2351 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002352 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002353 }
2354 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002355 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002356 }
2357 }
2358 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2359 output = outputOffloaded;
2360 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2361 output = outputDeepBuffer;
2362 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2363 output = outputPrimary;
2364 } else {
2365 output = outputs[0];
2366 }
2367 activeOnly = false;
2368 }
2369
2370 if (output != mMusicEffectOutput) {
2371 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2372 mMusicEffectOutput = output;
2373 }
2374
2375 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002376 return output;
2377}
2378
Eric Laurent36829f92017-04-07 19:04:42 -07002379audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2380{
2381 return selectOutputForMusicEffects();
2382}
2383
Eric Laurente0720872014-03-11 09:30:41 -07002384status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002385 audio_io_handle_t io,
2386 uint32_t strategy,
2387 int session,
2388 int id)
2389{
2390 ssize_t index = mOutputs.indexOfKey(io);
2391 if (index < 0) {
2392 index = mInputs.indexOfKey(io);
2393 if (index < 0) {
2394 ALOGW("registerEffect() unknown io %d", io);
2395 return INVALID_OPERATION;
2396 }
2397 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002398 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002399}
2400
Eric Laurentc75307b2015-03-17 15:29:32 -07002401bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2402{
Eric Laurent28d09f02016-03-08 10:43:05 -08002403 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002404 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2405 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002406 continue;
2407 }
2408 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2409 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002410 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002411}
2412
2413bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2414{
2415 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2416}
2417
Eric Laurente0720872014-03-11 09:30:41 -07002418bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002419{
2420 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002421 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002422 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002423 return true;
2424 }
2425 }
2426 return false;
2427}
2428
Eric Laurent275e8e92014-11-30 15:14:47 -08002429// Register a list of custom mixes with their attributes and format.
2430// When a mix is registered, corresponding input and output profiles are
2431// added to the remote submix hw module. The profile contains only the
2432// parameters (sampling rate, format...) specified by the mix.
2433// The corresponding input remote submix device is also connected.
2434//
2435// When a remote submix device is connected, the address is checked to select the
2436// appropriate profile and the corresponding input or output stream is opened.
2437//
2438// When capture starts, getInputForAttr() will:
2439// - 1 look for a mix matching the address passed in attribtutes tags if any
2440// - 2 if none found, getDeviceForInputSource() will:
2441// - 2.1 look for a mix matching the attributes source
2442// - 2.2 if none found, default to device selection by policy rules
2443// At this time, the corresponding output remote submix device is also connected
2444// and active playback use cases can be transferred to this mix if needed when reconnecting
2445// after AudioTracks are invalidated
2446//
2447// When playback starts, getOutputForAttr() will:
2448// - 1 look for a mix matching the address passed in attribtutes tags if any
2449// - 2 if none found, look for a mix matching the attributes usage
2450// - 3 if none found, default to device and output selection by policy rules.
2451
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002452status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002453{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002454 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2455 status_t res = NO_ERROR;
2456
2457 sp<HwModule> rSubmixModule;
2458 // examine each mix's route type
2459 for (size_t i = 0; i < mixes.size(); i++) {
2460 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
2461 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
2462 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002463 break;
2464 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002465 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002466 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002467 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002468 rSubmixModule = mHwModules.getModuleFromName(
2469 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2470 if (rSubmixModule == 0) {
2471 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2472 i);
2473 res = INVALID_OPERATION;
2474 break;
2475 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002476 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002477
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002478 String8 address = mixes[i].mDeviceAddress;
François Gaffie036e1e92015-03-19 10:16:24 +01002479
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002480 if (mPolicyMixes.registerMix(address, mixes[i], 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002481 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002482 res = INVALID_OPERATION;
2483 break;
2484 }
2485 audio_config_t outputConfig = mixes[i].mFormat;
2486 audio_config_t inputConfig = mixes[i].mFormat;
2487 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2488 // stereo and let audio flinger do the channel conversion if needed.
2489 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2490 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2491 rSubmixModule->addOutputProfile(address, &outputConfig,
2492 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2493 rSubmixModule->addInputProfile(address, &inputConfig,
2494 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002495
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002496 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
2497 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2498 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2499 address.string(), "remote-submix");
2500 } else {
2501 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2502 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2503 address.string(), "remote-submix");
2504 }
2505 } else if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002506 String8 address = mixes[i].mDeviceAddress;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002507 audio_devices_t device = mixes[i].mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002508 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2509 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002510
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002511 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002512 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2513 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2514 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2515 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2516 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2517 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002518 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2519 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002520 if (mPolicyMixes.registerMix(address, mixes[i], desc) != NO_ERROR) {
2521 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002522 } else {
2523 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002524 }
2525 break;
2526 }
2527 }
2528
2529 if (res != NO_ERROR) {
2530 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002531 i, device, address.string());
2532 res = INVALID_OPERATION;
2533 break;
2534 } else if (!foundOutput) {
2535 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2536 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002537 res = INVALID_OPERATION;
2538 break;
2539 }
Eric Laurentc722f302014-12-10 11:21:49 -08002540 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002541 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002542 if (res != NO_ERROR) {
2543 unregisterPolicyMixes(mixes);
2544 }
2545 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002546}
2547
2548status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2549{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002550 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002551 status_t res = NO_ERROR;
2552 sp<HwModule> rSubmixModule;
2553 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002554 for (const auto& mix : mixes) {
2555 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002556
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002557 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002558 rSubmixModule = mHwModules.getModuleFromName(
2559 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2560 if (rSubmixModule == 0) {
2561 res = INVALID_OPERATION;
2562 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002563 }
2564 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002565
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002566 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002567
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002568 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2569 res = INVALID_OPERATION;
2570 continue;
2571 }
2572
2573 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2574 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2575 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2576 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2577 address.string(), "remote-submix");
2578 }
2579 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2580 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2581 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2582 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2583 address.string(), "remote-submix");
2584 }
2585 rSubmixModule->removeOutputProfile(address);
2586 rSubmixModule->removeInputProfile(address);
2587
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002588 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2589 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002590 res = INVALID_OPERATION;
2591 continue;
2592 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002593 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002594 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002595 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002596}
2597
Eric Laurente552edb2014-03-10 17:42:56 -07002598
Eric Laurente0720872014-03-11 09:30:41 -07002599status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002600{
Eric Laurente552edb2014-03-10 17:42:56 -07002601 String8 result;
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002602 result.appendFormat("\nAudioPolicyManager Dump: %p\n", this);
2603 result.appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07002604 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002605 std::string stateLiteral;
2606 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002607 result.appendFormat(" Phone state: %s\n", stateLiteral.c_str());
2608 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
2609 "communications", "media", "record", "dock", "system",
2610 "HDMI system audio", "encoded surround output", "vibrate ringing" };
2611 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
2612 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
2613 result.appendFormat(" Force use for %s: %d\n",
2614 forceUses[i], mEngine->getForceUse(i));
2615 }
2616 result.appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
2617 result.appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
2618 result.appendFormat(" Config source: %s\n", getConfig().getSource().c_str());
François Gaffie2110e042015-03-24 08:41:51 +01002619 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002620
François Gaffie112b0af2015-11-19 16:13:25 +01002621 mAvailableOutputDevices.dump(fd, String8("Available output"));
2622 mAvailableInputDevices.dump(fd, String8("Available input"));
Mikhail Naganovd4120142017-12-06 15:49:22 -08002623 mHwModulesAll.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002624 mOutputs.dump(fd);
2625 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002626 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002627 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002628 mAudioPatches.dump(fd);
Mikhail Naganov44344b02016-12-13 11:21:02 -08002629 mPolicyMixes.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002630
2631 return NO_ERROR;
2632}
2633
2634// This function checks for the parameters which can be offloaded.
2635// This can be enhanced depending on the capability of the DSP and policy
2636// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002637bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002638{
2639 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002640 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002641 offloadInfo.sample_rate, offloadInfo.channel_mask,
2642 offloadInfo.format,
2643 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2644 offloadInfo.has_video);
2645
Andy Hung2ddee192015-12-18 17:34:44 -08002646 if (mMasterMono) {
2647 return false; // no offloading if mono is set.
2648 }
2649
Eric Laurente552edb2014-03-10 17:42:56 -07002650 // Check if offload has been disabled
2651 char propValue[PROPERTY_VALUE_MAX];
2652 if (property_get("audio.offload.disable", propValue, "0")) {
2653 if (atoi(propValue) != 0) {
2654 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2655 return false;
2656 }
2657 }
2658
2659 // Check if stream type is music, then only allow offload as of now.
2660 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2661 {
2662 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2663 return false;
2664 }
2665
2666 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002667 const bool allowOffloadWithVideo =
2668 property_get_bool("audio.offload.video", false /* default_value */);
2669 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002670 ALOGV("isOffloadSupported: has_video == true, returning false");
2671 return false;
2672 }
2673
2674 //If duration is less than minimum value defined in property, return false
2675 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2676 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2677 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2678 return false;
2679 }
2680 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2681 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2682 return false;
2683 }
2684
2685 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2686 // creating an offloaded track and tearing it down immediately after start when audioflinger
2687 // detects there is an active non offloadable effect.
2688 // FIXME: We should check the audio session here but we do not have it in this context.
2689 // This may prevent offloading in rare situations where effects are left active by apps
2690 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002691 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002692 return false;
2693 }
2694
2695 // See if there is a profile to support this.
2696 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002697 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002698 offloadInfo.sample_rate,
2699 offloadInfo.format,
2700 offloadInfo.channel_mask,
2701 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002702 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2703 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002704}
2705
Eric Laurent6a94d692014-05-20 11:18:06 -07002706status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2707 audio_port_type_t type,
2708 unsigned int *num_ports,
2709 struct audio_port *ports,
2710 unsigned int *generation)
2711{
2712 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2713 generation == NULL) {
2714 return BAD_VALUE;
2715 }
2716 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2717 if (ports == NULL) {
2718 *num_ports = 0;
2719 }
2720
2721 size_t portsWritten = 0;
2722 size_t portsMax = *num_ports;
2723 *num_ports = 0;
2724 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002725 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2726 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002727 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002728 for (const auto& dev : mAvailableOutputDevices) {
2729 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002730 continue;
2731 }
2732 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002733 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002734 }
2735 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002736 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002737 }
2738 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002739 for (const auto& dev : mAvailableInputDevices) {
2740 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002741 continue;
2742 }
2743 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002744 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002745 }
2746 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002747 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002748 }
2749 }
2750 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2751 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2752 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2753 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2754 }
2755 *num_ports += mInputs.size();
2756 }
2757 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002758 size_t numOutputs = 0;
2759 for (size_t i = 0; i < mOutputs.size(); i++) {
2760 if (!mOutputs[i]->isDuplicated()) {
2761 numOutputs++;
2762 if (portsWritten < portsMax) {
2763 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2764 }
2765 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002766 }
Eric Laurent84c70242014-06-23 08:46:27 -07002767 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002768 }
2769 }
2770 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002771 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002772 return NO_ERROR;
2773}
2774
Eric Laurent99fcae42018-05-17 16:59:18 -07002775status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07002776{
Eric Laurent99fcae42018-05-17 16:59:18 -07002777 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
2778 return BAD_VALUE;
2779 }
2780 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
2781 if (dev != 0) {
2782 dev->toAudioPort(port);
2783 return NO_ERROR;
2784 }
2785 dev = mAvailableInputDevices.getDeviceFromId(port->id);
2786 if (dev != 0) {
2787 dev->toAudioPort(port);
2788 return NO_ERROR;
2789 }
2790 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
2791 if (out != 0) {
2792 out->toAudioPort(port);
2793 return NO_ERROR;
2794 }
2795 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
2796 if (in != 0) {
2797 in->toAudioPort(port);
2798 return NO_ERROR;
2799 }
2800 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002801}
2802
Eric Laurent6a94d692014-05-20 11:18:06 -07002803status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2804 audio_patch_handle_t *handle,
2805 uid_t uid)
2806{
2807 ALOGV("createAudioPatch()");
2808
2809 if (handle == NULL || patch == NULL) {
2810 return BAD_VALUE;
2811 }
2812 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2813
Eric Laurent874c42872014-08-08 15:13:39 -07002814 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2815 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2816 return BAD_VALUE;
2817 }
2818 // only one source per audio patch supported for now
2819 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002820 return INVALID_OPERATION;
2821 }
Eric Laurent874c42872014-08-08 15:13:39 -07002822
2823 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002824 return INVALID_OPERATION;
2825 }
Eric Laurent874c42872014-08-08 15:13:39 -07002826 for (size_t i = 0; i < patch->num_sinks; i++) {
2827 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2828 return INVALID_OPERATION;
2829 }
2830 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002831
2832 sp<AudioPatch> patchDesc;
2833 ssize_t index = mAudioPatches.indexOfKey(*handle);
2834
Eric Laurent6a94d692014-05-20 11:18:06 -07002835 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2836 patch->sources[0].role,
2837 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002838#if LOG_NDEBUG == 0
2839 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002840 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002841 patch->sinks[i].role,
2842 patch->sinks[i].type);
2843 }
2844#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002845
2846 if (index >= 0) {
2847 patchDesc = mAudioPatches.valueAt(index);
2848 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2849 mUidCached, patchDesc->mUid, uid);
2850 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2851 return INVALID_OPERATION;
2852 }
2853 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002854 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002855 }
2856
2857 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002858 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002859 if (outputDesc == NULL) {
2860 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2861 return BAD_VALUE;
2862 }
Eric Laurent84c70242014-06-23 08:46:27 -07002863 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2864 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002865 if (patchDesc != 0) {
2866 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2867 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2868 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2869 return BAD_VALUE;
2870 }
2871 }
Eric Laurent874c42872014-08-08 15:13:39 -07002872 DeviceVector devices;
2873 for (size_t i = 0; i < patch->num_sinks; i++) {
2874 // Only support mix to devices connection
2875 // TODO add support for mix to mix connection
2876 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2877 ALOGV("createAudioPatch() source mix but sink is not a device");
2878 return INVALID_OPERATION;
2879 }
2880 sp<DeviceDescriptor> devDesc =
2881 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2882 if (devDesc == 0) {
2883 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2884 return BAD_VALUE;
2885 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002886
François Gaffie53615e22015-03-19 09:24:12 +01002887 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002888 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002889 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002890 NULL, // updatedSamplingRate
2891 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002892 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002893 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002894 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002895 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002896 ALOGV("createAudioPatch() profile not supported for device %08x",
2897 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002898 return INVALID_OPERATION;
2899 }
2900 devices.add(devDesc);
2901 }
2902 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002903 return INVALID_OPERATION;
2904 }
Eric Laurent874c42872014-08-08 15:13:39 -07002905
Eric Laurent6a94d692014-05-20 11:18:06 -07002906 // TODO: reconfigure output format and channels here
2907 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002908 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002909 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002910 index = mAudioPatches.indexOfKey(*handle);
2911 if (index >= 0) {
2912 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2913 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2914 }
2915 patchDesc = mAudioPatches.valueAt(index);
2916 patchDesc->mUid = uid;
2917 ALOGV("createAudioPatch() success");
2918 } else {
2919 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2920 return INVALID_OPERATION;
2921 }
2922 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2923 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2924 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002925 // only one sink supported when connecting an input device to a mix
2926 if (patch->num_sinks > 1) {
2927 return INVALID_OPERATION;
2928 }
François Gaffie53615e22015-03-19 09:24:12 +01002929 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002930 if (inputDesc == NULL) {
2931 return BAD_VALUE;
2932 }
2933 if (patchDesc != 0) {
2934 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2935 return BAD_VALUE;
2936 }
2937 }
2938 sp<DeviceDescriptor> devDesc =
2939 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2940 if (devDesc == 0) {
2941 return BAD_VALUE;
2942 }
2943
François Gaffie53615e22015-03-19 09:24:12 +01002944 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002945 devDesc->mAddress,
2946 patch->sinks[0].sample_rate,
2947 NULL, /*updatedSampleRate*/
2948 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002949 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002950 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002951 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002952 // FIXME for the parameter type,
2953 // and the NONE
2954 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002955 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002956 return INVALID_OPERATION;
2957 }
2958 // TODO: reconfigure output format and channels here
2959 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01002960 devDesc->type(), inputDesc->mIoHandle);
2961 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002962 index = mAudioPatches.indexOfKey(*handle);
2963 if (index >= 0) {
2964 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2965 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2966 }
2967 patchDesc = mAudioPatches.valueAt(index);
2968 patchDesc->mUid = uid;
2969 ALOGV("createAudioPatch() success");
2970 } else {
2971 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2972 return INVALID_OPERATION;
2973 }
2974 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2975 // device to device connection
2976 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002977 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002978 return BAD_VALUE;
2979 }
2980 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002981 sp<DeviceDescriptor> srcDeviceDesc =
2982 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002983 if (srcDeviceDesc == 0) {
2984 return BAD_VALUE;
2985 }
Eric Laurent874c42872014-08-08 15:13:39 -07002986
Eric Laurent6a94d692014-05-20 11:18:06 -07002987 //update source and sink with our own data as the data passed in the patch may
2988 // be incomplete.
2989 struct audio_patch newPatch = *patch;
2990 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002991
Eric Laurent874c42872014-08-08 15:13:39 -07002992 for (size_t i = 0; i < patch->num_sinks; i++) {
2993 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2994 ALOGV("createAudioPatch() source device but one sink is not a device");
2995 return INVALID_OPERATION;
2996 }
2997
2998 sp<DeviceDescriptor> sinkDeviceDesc =
2999 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3000 if (sinkDeviceDesc == 0) {
3001 return BAD_VALUE;
3002 }
3003 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
3004
Eric Laurent3bcf8592015-04-03 12:13:24 -07003005 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003006 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003007 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08003008 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003009 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003010 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003011 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003012 return INVALID_OPERATION;
3013 }
Eric Laurent874c42872014-08-08 15:13:39 -07003014 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01003015 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003016 // if the sink device is reachable via an opened output stream, request to go via
3017 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07003018 audio_io_handle_t output = selectOutput(outputs,
3019 AUDIO_OUTPUT_FLAG_NONE,
3020 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07003021 if (output != AUDIO_IO_HANDLE_NONE) {
3022 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3023 if (outputDesc->isDuplicated()) {
3024 return INVALID_OPERATION;
3025 }
3026 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003027 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003028 newPatch.num_sources = 2;
3029 }
Eric Laurent83b88082014-06-20 18:31:16 -07003030 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003031 }
3032 // TODO: check from routing capabilities in config file and other conflicting patches
3033
Mikhail Naganovdc769682018-05-04 15:34:08 -07003034 status_t status = installPatch(__func__, index, handle, &newPatch, 0, uid, &patchDesc);
3035 if (status != NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003036 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3037 status);
3038 return INVALID_OPERATION;
3039 }
3040 } else {
3041 return BAD_VALUE;
3042 }
3043 } else {
3044 return BAD_VALUE;
3045 }
3046 return NO_ERROR;
3047}
3048
3049status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3050 uid_t uid)
3051{
3052 ALOGV("releaseAudioPatch() patch %d", handle);
3053
3054 ssize_t index = mAudioPatches.indexOfKey(handle);
3055
3056 if (index < 0) {
3057 return BAD_VALUE;
3058 }
3059 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3060 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3061 mUidCached, patchDesc->mUid, uid);
3062 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3063 return INVALID_OPERATION;
3064 }
3065
3066 struct audio_patch *patch = &patchDesc->mPatch;
3067 patchDesc->mUid = mUidCached;
3068 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003069 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003070 if (outputDesc == NULL) {
3071 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3072 return BAD_VALUE;
3073 }
3074
Eric Laurentc75307b2015-03-17 15:29:32 -07003075 setOutputDevice(outputDesc,
3076 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07003077 true,
3078 0,
3079 NULL);
3080 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3081 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003082 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003083 if (inputDesc == NULL) {
3084 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3085 return BAD_VALUE;
3086 }
3087 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003088 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003089 true,
3090 NULL);
3091 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003092 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3093 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3094 status, patchDesc->mAfPatchHandle);
3095 removeAudioPatch(patchDesc->mHandle);
3096 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003097 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003098 } else {
3099 return BAD_VALUE;
3100 }
3101 } else {
3102 return BAD_VALUE;
3103 }
3104 return NO_ERROR;
3105}
3106
3107status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3108 struct audio_patch *patches,
3109 unsigned int *generation)
3110{
François Gaffie53615e22015-03-19 09:24:12 +01003111 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003112 return BAD_VALUE;
3113 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003114 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003115 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003116}
3117
Eric Laurente1715a42014-05-20 11:30:42 -07003118status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003119{
Eric Laurente1715a42014-05-20 11:30:42 -07003120 ALOGV("setAudioPortConfig()");
3121
3122 if (config == NULL) {
3123 return BAD_VALUE;
3124 }
3125 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3126 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003127 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3128 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003129 }
3130
Eric Laurenta121f902014-06-03 13:32:54 -07003131 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003132 if (config->type == AUDIO_PORT_TYPE_MIX) {
3133 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003134 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003135 if (outputDesc == NULL) {
3136 return BAD_VALUE;
3137 }
Eric Laurent84c70242014-06-23 08:46:27 -07003138 ALOG_ASSERT(!outputDesc->isDuplicated(),
3139 "setAudioPortConfig() called on duplicated output %d",
3140 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003141 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003142 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003143 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003144 if (inputDesc == NULL) {
3145 return BAD_VALUE;
3146 }
Eric Laurenta121f902014-06-03 13:32:54 -07003147 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003148 } else {
3149 return BAD_VALUE;
3150 }
3151 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3152 sp<DeviceDescriptor> deviceDesc;
3153 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3154 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3155 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3156 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3157 } else {
3158 return BAD_VALUE;
3159 }
3160 if (deviceDesc == NULL) {
3161 return BAD_VALUE;
3162 }
Eric Laurenta121f902014-06-03 13:32:54 -07003163 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003164 } else {
3165 return BAD_VALUE;
3166 }
3167
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003168 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003169 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3170 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003171 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003172 audioPortConfig->toAudioPortConfig(&newConfig, config);
3173 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003174 }
Eric Laurenta121f902014-06-03 13:32:54 -07003175 if (status != NO_ERROR) {
3176 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003177 }
Eric Laurente1715a42014-05-20 11:30:42 -07003178
3179 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003180}
3181
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003182void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3183{
Eric Laurentd60560a2015-04-10 11:31:20 -07003184 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003185 clearAudioPatches(uid);
3186 clearSessionRoutes(uid);
3187}
3188
Eric Laurent6a94d692014-05-20 11:18:06 -07003189void AudioPolicyManager::clearAudioPatches(uid_t uid)
3190{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003191 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003192 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3193 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003194 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003195 }
3196 }
3197}
3198
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003199void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3200 audio_io_handle_t ouptutToSkip)
3201{
3202 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3203 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3204 for (size_t j = 0; j < mOutputs.size(); j++) {
3205 if (mOutputs.keyAt(j) == ouptutToSkip) {
3206 continue;
3207 }
3208 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3209 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3210 continue;
3211 }
3212 // If the default device for this strategy is on another output mix,
3213 // invalidate all tracks in this strategy to force re connection.
3214 // Otherwise select new device on the output mix.
3215 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003216 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003217 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3218 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3219 }
3220 }
3221 } else {
3222 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3223 setOutputDevice(outputDesc, newDevice, false);
3224 }
3225 }
3226}
3227
3228void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3229{
3230 // remove output routes associated with this uid
3231 SortedVector<routing_strategy> affectedStrategies;
3232 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
3233 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
3234 if (route->mUid == uid) {
3235 mOutputRoutes.removeItemsAt(i);
3236 if (route->mDeviceDescriptor != 0) {
3237 affectedStrategies.add(getStrategy(route->mStreamType));
3238 }
3239 }
3240 }
3241 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003242 for (const auto& strategy : affectedStrategies) {
3243 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003244 }
3245
3246 // remove input routes associated with this uid
3247 SortedVector<audio_source_t> affectedSources;
3248 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
3249 sp<SessionRoute> route = mInputRoutes.valueAt(i);
3250 if (route->mUid == uid) {
3251 mInputRoutes.removeItemsAt(i);
3252 if (route->mDeviceDescriptor != 0) {
3253 affectedSources.add(route->mSource);
3254 }
3255 }
3256 }
3257 // reroute inputs if necessary
3258 SortedVector<audio_io_handle_t> inputsToClose;
3259 for (size_t i = 0; i < mInputs.size(); i++) {
3260 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003261 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003262 inputsToClose.add(inputDesc->mIoHandle);
3263 }
3264 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003265 for (const auto& input : inputsToClose) {
3266 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003267 }
3268}
3269
Eric Laurentd60560a2015-04-10 11:31:20 -07003270void AudioPolicyManager::clearAudioSources(uid_t uid)
3271{
3272 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
3273 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3274 if (sourceDesc->mUid == uid) {
3275 stopAudioSource(mAudioSources.keyAt(i));
3276 }
3277 }
3278}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003279
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003280status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3281 audio_io_handle_t *ioHandle,
3282 audio_devices_t *device)
3283{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003284 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3285 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003286 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003287
François Gaffiedf372692015-03-19 10:43:27 +01003288 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003289}
3290
Eric Laurentd60560a2015-04-10 11:31:20 -07003291status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
3292 const audio_attributes_t *attributes,
Glenn Kasten559d4392016-03-29 13:42:57 -07003293 audio_patch_handle_t *handle,
Eric Laurentd60560a2015-04-10 11:31:20 -07003294 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003295{
Eric Laurentd60560a2015-04-10 11:31:20 -07003296 ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle);
3297 if (source == NULL || attributes == NULL || handle == NULL) {
3298 return BAD_VALUE;
3299 }
3300
Glenn Kasten559d4392016-03-29 13:42:57 -07003301 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003302
3303 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3304 source->type != AUDIO_PORT_TYPE_DEVICE) {
3305 ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type);
3306 return INVALID_OPERATION;
3307 }
3308
3309 sp<DeviceDescriptor> srcDeviceDesc =
3310 mAvailableInputDevices.getDevice(source->ext.device.type,
3311 String8(source->ext.device.address));
3312 if (srcDeviceDesc == 0) {
3313 ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
3314 return BAD_VALUE;
3315 }
3316 sp<AudioSourceDescriptor> sourceDesc =
3317 new AudioSourceDescriptor(srcDeviceDesc, attributes, uid);
3318
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003319 struct audio_patch dummyPatch = {};
Eric Laurentd60560a2015-04-10 11:31:20 -07003320 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
3321 sourceDesc->mPatchDesc = patchDesc;
3322
3323 status_t status = connectAudioSource(sourceDesc);
3324 if (status == NO_ERROR) {
3325 mAudioSources.add(sourceDesc->getHandle(), sourceDesc);
3326 *handle = sourceDesc->getHandle();
3327 }
3328 return status;
3329}
3330
3331status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3332{
3333 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3334
3335 // make sure we only have one patch per source.
3336 disconnectAudioSource(sourceDesc);
3337
3338 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
Eric Laurent28d09f02016-03-08 10:43:05 -08003339 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003340 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice;
3341
3342 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3343 sp<DeviceDescriptor> sinkDeviceDesc =
3344 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3345
3346 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003347
3348 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3349 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003350 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003351 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3352 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3353 // create patch between src device and output device
3354 // create Hwoutput and add to mHwOutputs
3355 } else {
3356 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3357 audio_io_handle_t output =
3358 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3359 if (output == AUDIO_IO_HANDLE_NONE) {
3360 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3361 return INVALID_OPERATION;
3362 }
3363 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3364 if (outputDesc->isDuplicated()) {
3365 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3366 return INVALID_OPERATION;
3367 }
Eric Laurent733ce942017-12-07 12:18:25 -08003368 status_t status = outputDesc->start();
3369 if (status != NO_ERROR) {
3370 return status;
3371 }
3372
Eric Laurentd60560a2015-04-10 11:31:20 -07003373 // create a special patch with no sink and two sources:
3374 // - the second source indicates to PatchPanel through which output mix this patch should
3375 // be connected as well as the stream type for volume control
3376 // - the sink is defined by whatever output device is currently selected for the output
3377 // though which this patch is routed.
Mikhail Naganovdc769682018-05-04 15:34:08 -07003378 PatchBuilder patchBuilder;
3379 patchBuilder.addSource(srcDeviceDesc).addSource(outputDesc, { .stream = stream });
3380 status = mpClientInterface->createAudioPatch(patchBuilder.patch(),
Eric Laurentd60560a2015-04-10 11:31:20 -07003381 &afPatchHandle,
3382 0);
3383 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3384 status, afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07003385 sourceDesc->mPatchDesc->mPatch = *patchBuilder.patch();
Eric Laurentd60560a2015-04-10 11:31:20 -07003386 if (status != NO_ERROR) {
3387 ALOGW("%s patch panel could not connect device patch, error %d",
3388 __FUNCTION__, status);
3389 return INVALID_OPERATION;
3390 }
3391 uint32_t delayMs = 0;
Eric Laurentc40d9692016-04-13 19:14:13 -07003392 status = startSource(outputDesc, stream, sinkDevice, NULL, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003393
3394 if (status != NO_ERROR) {
3395 mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0);
3396 return status;
3397 }
3398 sourceDesc->mSwOutput = outputDesc;
3399 if (delayMs != 0) {
3400 usleep(delayMs * 1000);
3401 }
3402 }
3403
3404 sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle;
3405 addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc);
3406
3407 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003408}
3409
Glenn Kasten559d4392016-03-29 13:42:57 -07003410status_t AudioPolicyManager::stopAudioSource(audio_patch_handle_t handle __unused)
Eric Laurent554a2772015-04-10 11:29:24 -07003411{
Eric Laurentd60560a2015-04-10 11:31:20 -07003412 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle);
3413 ALOGV("%s handle %d", __FUNCTION__, handle);
3414 if (sourceDesc == 0) {
3415 ALOGW("%s unknown source for handle %d", __FUNCTION__, handle);
3416 return BAD_VALUE;
3417 }
3418 status_t status = disconnectAudioSource(sourceDesc);
3419
3420 mAudioSources.removeItem(handle);
3421 return status;
3422}
3423
Andy Hung2ddee192015-12-18 17:34:44 -08003424status_t AudioPolicyManager::setMasterMono(bool mono)
3425{
3426 if (mMasterMono == mono) {
3427 return NO_ERROR;
3428 }
3429 mMasterMono = mono;
3430 // if enabling mono we close all offloaded devices, which will invalidate the
3431 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3432 // for recreating the new AudioTrack as non-offloaded PCM.
3433 //
3434 // If disabling mono, we leave all tracks as is: we don't know which clients
3435 // and tracks are able to be recreated as offloaded. The next "song" should
3436 // play back offloaded.
3437 if (mMasterMono) {
3438 Vector<audio_io_handle_t> offloaded;
3439 for (size_t i = 0; i < mOutputs.size(); ++i) {
3440 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3441 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3442 offloaded.push(desc->mIoHandle);
3443 }
3444 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003445 for (const auto& handle : offloaded) {
3446 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003447 }
3448 }
3449 // update master mono for all remaining outputs
3450 for (size_t i = 0; i < mOutputs.size(); ++i) {
3451 updateMono(mOutputs.keyAt(i));
3452 }
3453 return NO_ERROR;
3454}
3455
3456status_t AudioPolicyManager::getMasterMono(bool *mono)
3457{
3458 *mono = mMasterMono;
3459 return NO_ERROR;
3460}
3461
Eric Laurentac9cef52017-06-09 15:46:26 -07003462float AudioPolicyManager::getStreamVolumeDB(
3463 audio_stream_type_t stream, int index, audio_devices_t device)
3464{
3465 return computeVolume(stream, index, device);
3466}
3467
jiabin81772902018-04-02 17:52:27 -07003468status_t AudioPolicyManager::getSupportedFormats(audio_io_handle_t ioHandle,
3469 FormatVector& formats) {
3470 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
3471 return BAD_VALUE;
3472 }
3473 String8 reply;
3474 reply = mpClientInterface->getParameters(
3475 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
3476 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
3477 AudioParameter repliedParameters(reply);
3478 if (repliedParameters.get(
3479 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
3480 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
3481 return BAD_VALUE;
3482 }
3483 for (auto format : formatsFromString(reply.string())) {
3484 // Only AUDIO_FORMAT_AAC_LC will be used in Settings UI for all AAC formats.
3485 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3486 if (format == AAC_FORMATS[i]) {
3487 format = AUDIO_FORMAT_AAC_LC;
3488 break;
3489 }
3490 }
3491 bool exist = false;
3492 for (size_t i = 0; i < formats.size(); i++) {
3493 if (format == formats[i]) {
3494 exist = true;
3495 break;
3496 }
3497 }
3498 bool isSurroundFormat = false;
3499 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3500 if (SURROUND_FORMATS[i] == format) {
3501 isSurroundFormat = true;
3502 break;
3503 }
3504 }
3505 if (!exist && isSurroundFormat) {
3506 formats.add(format);
3507 }
3508 }
3509 return NO_ERROR;
3510}
3511
3512status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3513 audio_format_t *surroundFormats,
3514 bool *surroundFormatsEnabled,
3515 bool reported)
3516{
3517 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3518 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3519 return BAD_VALUE;
3520 }
3521 ALOGV("getSurroundFormats() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
3522 *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
3523
3524 // Only return value if there is HDMI output.
3525 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3526 return INVALID_OPERATION;
3527 }
3528
3529 size_t formatsWritten = 0;
3530 size_t formatsMax = *numSurroundFormats;
3531 *numSurroundFormats = 0;
3532 FormatVector formats;
3533 if (reported) {
3534 // Only get surround formats which are reported by device.
3535 // First list already open outputs that can be routed to this device
3536 audio_devices_t device = AUDIO_DEVICE_OUT_HDMI;
3537 SortedVector<audio_io_handle_t> outputs;
3538 bool reportedFormatFound = false;
3539 status_t status;
3540 sp<SwAudioOutputDescriptor> desc;
3541 for (size_t i = 0; i < mOutputs.size(); i++) {
3542 desc = mOutputs.valueAt(i);
3543 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
3544 outputs.add(mOutputs.keyAt(i));
3545 }
3546 }
3547 // Open an output to query dynamic parameters.
Mikhail Naganov708e0382018-05-30 09:53:04 -07003548 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003549 AUDIO_DEVICE_OUT_HDMI);
3550 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3551 String8 address = hdmiOutputDevices[i]->mAddress;
3552 for (const auto& hwModule : mHwModules) {
3553 for (size_t i = 0; i < hwModule->getOutputProfiles().size(); i++) {
3554 sp<IOProfile> profile = hwModule->getOutputProfiles()[i];
3555 if (profile->supportDevice(AUDIO_DEVICE_OUT_HDMI) &&
3556 profile->supportDeviceAddress(address)) {
3557 size_t j;
3558 for (j = 0; j < outputs.size(); j++) {
3559 desc = mOutputs.valueFor(outputs.itemAt(j));
3560 if (!desc->isDuplicated() && desc->mProfile == profile) {
3561 break;
3562 }
3563 }
3564 if (j != outputs.size()) {
3565 status = getSupportedFormats(outputs.itemAt(j), formats);
3566 reportedFormatFound |= (status == NO_ERROR);
3567 continue;
3568 }
3569
3570 if (!profile->canOpenNewIo()) {
3571 ALOGW("Max Output number %u already opened for this profile %s",
3572 profile->maxOpenCount, profile->getTagName().c_str());
3573 continue;
3574 }
3575
3576 ALOGV("opening output for device %08x with params %s profile %p name %s",
3577 device, address.string(), profile.get(), profile->getName().string());
3578 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
3579 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3580 status_t status = desc->open(nullptr, device, address,
3581 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE,
3582 &output);
3583
3584 if (status == NO_ERROR) {
3585 status = getSupportedFormats(output, formats);
3586 reportedFormatFound |= (status == NO_ERROR);
3587 desc->close();
3588 output = AUDIO_IO_HANDLE_NONE;
3589 }
3590 }
3591 }
3592 }
3593 }
3594
3595 if (!reportedFormatFound) {
3596 return UNKNOWN_ERROR;
3597 }
3598 } else {
3599 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3600 formats.add(SURROUND_FORMATS[i]);
3601 }
3602 }
3603 for (size_t i = 0; i < formats.size(); i++) {
3604 if (formatsWritten < formatsMax) {
3605 surroundFormats[formatsWritten] = formats[i];
3606 bool formatEnabled = false;
3607 if (formats[i] == AUDIO_FORMAT_AAC_LC) {
3608 for (size_t j = 0; j < ARRAY_SIZE(AAC_FORMATS); j++) {
3609 formatEnabled =
3610 mSurroundFormats.find(AAC_FORMATS[i]) != mSurroundFormats.end();
3611 break;
3612 }
3613 } else {
3614 formatEnabled = mSurroundFormats.find(formats[i]) != mSurroundFormats.end();
3615 }
3616 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3617 }
3618 (*numSurroundFormats)++;
3619 }
3620 return NO_ERROR;
3621}
3622
3623status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3624{
3625 // Check if audio format is a surround formats.
3626 bool isSurroundFormat = false;
3627 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3628 if (audioFormat == SURROUND_FORMATS[i]) {
3629 isSurroundFormat = true;
3630 break;
3631 }
3632 }
3633 if (!isSurroundFormat) {
3634 return BAD_VALUE;
3635 }
3636
3637 // Should only be called when MANUAL.
3638 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3639 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
3640 if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3641 return INVALID_OPERATION;
3642 }
3643
3644 if ((mSurroundFormats.find(audioFormat) != mSurroundFormats.end() && enabled)
3645 || (mSurroundFormats.find(audioFormat) == mSurroundFormats.end() && !enabled)) {
3646 return NO_ERROR;
3647 }
3648
3649 // The operation is valid only when there is HDMI output available.
3650 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3651 return INVALID_OPERATION;
3652 }
3653
3654 if (enabled) {
3655 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3656 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3657 mSurroundFormats.insert(AAC_FORMATS[i]);
3658 }
3659 } else {
3660 mSurroundFormats.insert(audioFormat);
3661 }
3662 } else {
3663 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3664 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3665 mSurroundFormats.erase(AAC_FORMATS[i]);
3666 }
3667 } else {
3668 mSurroundFormats.erase(audioFormat);
3669 }
3670 }
3671
3672 sp<SwAudioOutputDescriptor> outputDesc;
3673 bool profileUpdated = false;
Mikhail Naganov708e0382018-05-30 09:53:04 -07003674 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003675 AUDIO_DEVICE_OUT_HDMI);
3676 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3677 // Simulate reconnection to update enabled surround sound formats.
3678 String8 address = hdmiOutputDevices[i]->mAddress;
3679 String8 name = hdmiOutputDevices[i]->getName();
3680 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3681 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3682 address.c_str(),
3683 name.c_str());
3684 if (status != NO_ERROR) {
3685 continue;
3686 }
3687 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3688 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3689 address.c_str(),
3690 name.c_str());
3691 profileUpdated |= (status == NO_ERROR);
3692 }
Mikhail Naganov708e0382018-05-30 09:53:04 -07003693 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003694 AUDIO_DEVICE_IN_HDMI);
3695 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3696 // Simulate reconnection to update enabled surround sound formats.
3697 String8 address = hdmiInputDevices[i]->mAddress;
3698 String8 name = hdmiInputDevices[i]->getName();
3699 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3700 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3701 address.c_str(),
3702 name.c_str());
3703 if (status != NO_ERROR) {
3704 continue;
3705 }
3706 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3707 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3708 address.c_str(),
3709 name.c_str());
3710 profileUpdated |= (status == NO_ERROR);
3711 }
3712
3713 // Undo the surround formats change due to no audio profiles updated.
3714 if (!profileUpdated) {
3715 if (enabled) {
3716 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3717 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3718 mSurroundFormats.erase(AAC_FORMATS[i]);
3719 }
3720 } else {
3721 mSurroundFormats.erase(audioFormat);
3722 }
3723 } else {
3724 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3725 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3726 mSurroundFormats.insert(AAC_FORMATS[i]);
3727 }
3728 } else {
3729 mSurroundFormats.insert(audioFormat);
3730 }
3731 }
3732 }
3733
3734 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3735}
3736
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003737void AudioPolicyManager::setRecordSilenced(uid_t uid, bool silenced)
3738{
3739 ALOGV("AudioPolicyManager:setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
3740
3741 Vector<sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
3742 for (size_t i = 0; i < activeInputs.size(); i++) {
3743 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
3744 AudioSessionCollection activeSessions = activeDesc->getAudioSessions(true);
3745 for (size_t j = 0; j < activeSessions.size(); j++) {
3746 sp<AudioSession> activeSession = activeSessions.valueAt(j);
3747 if (activeSession->uid() == uid) {
3748 activeSession->setSilenced(silenced);
3749 }
3750 }
3751 }
3752}
3753
Eric Laurentd60560a2015-04-10 11:31:20 -07003754status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3755{
3756 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3757
3758 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle);
3759 if (patchDesc == 0) {
3760 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
3761 sourceDesc->mPatchDesc->mHandle);
3762 return BAD_VALUE;
3763 }
3764 removeAudioPatch(sourceDesc->mPatchDesc->mHandle);
3765
Eric Laurent28d09f02016-03-08 10:43:05 -08003766 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003767 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote();
3768 if (swOutputDesc != 0) {
Eric Laurent733ce942017-12-07 12:18:25 -08003769 status_t status = stopSource(swOutputDesc, stream, false);
3770 if (status == NO_ERROR) {
3771 swOutputDesc->stop();
3772 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003773 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3774 } else {
3775 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote();
3776 if (hwOutputDesc != 0) {
3777 // release patch between src device and output device
3778 // close Hwoutput and remove from mHwOutputs
3779 } else {
3780 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3781 }
3782 }
3783 return NO_ERROR;
3784}
3785
3786sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
3787 audio_io_handle_t output, routing_strategy strategy)
3788{
3789 sp<AudioSourceDescriptor> source;
3790 for (size_t i = 0; i < mAudioSources.size(); i++) {
3791 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3792 routing_strategy sourceStrategy =
3793 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
3794 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote();
3795 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3796 source = sourceDesc;
3797 break;
3798 }
3799 }
3800 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003801}
3802
Eric Laurente552edb2014-03-10 17:42:56 -07003803// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003804// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003805// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003806uint32_t AudioPolicyManager::nextAudioPortGeneration()
3807{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003808 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003809}
3810
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003811#ifdef USE_XML_AUDIO_POLICY_CONF
3812// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3813static const char *kConfigLocationList[] =
3814 {"/odm/etc", "/vendor/etc", "/system/etc"};
3815static const int kConfigLocationListSize =
3816 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3817
3818static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3819 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07003820 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003821 status_t ret;
3822
Petri Gyntherf497f292018-04-17 18:46:10 -07003823 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
3824 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
3825 // A2DP offload supported but disabled: try to use special XML file
3826 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
3827 }
3828 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3829
3830 for (const char* fileName : fileNames) {
3831 for (int i = 0; i < kConfigLocationListSize; i++) {
3832 PolicySerializer serializer;
3833 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
3834 "%s/%s", kConfigLocationList[i], fileName);
3835 ret = serializer.deserialize(audioPolicyXmlConfigFile, config);
3836 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003837 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07003838 return ret;
3839 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003840 }
3841 }
3842 return ret;
3843}
3844#endif
3845
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003846AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
3847 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07003848 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07003849 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003850 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07003851 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003852 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003853#ifdef USE_XML_AUDIO_POLICY_CONF
3854 mVolumeCurves(new VolumeCurvesCollection()),
3855 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08003856 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003857#else
3858 mVolumeCurves(new StreamDescriptorCollection()),
3859 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
3860 mDefaultOutputDevice),
3861#endif
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003862 mAudioPortGeneration(1),
3863 mBeaconMuteRefCount(0),
3864 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003865 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003866 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003867 mMasterMono(false),
Chris Thornton2b864642017-06-27 21:26:07 -07003868 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE),
3869 mHasComputedSoundTriggerSupportsConcurrentCapture(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003870{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003871}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003872
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003873AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
3874 : AudioPolicyManager(clientInterface, false /*forTesting*/)
3875{
3876 loadConfig();
3877 initialize();
3878}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003879
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003880void AudioPolicyManager::loadConfig() {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003881#ifdef USE_XML_AUDIO_POLICY_CONF
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003882 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003883#else
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003884 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, getConfig()) != NO_ERROR)
3885 && (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, getConfig()) != NO_ERROR)) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003886#endif
3887 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003888 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01003889 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003890}
3891
3892status_t AudioPolicyManager::initialize() {
3893 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01003894
3895 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003896 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3897 if (!engineInstance) {
3898 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003899 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003900 }
3901 // Retrieve the Policy Manager Interface
3902 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3903 if (mEngine == NULL) {
3904 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003905 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003906 }
3907 mEngine->setObserver(this);
3908 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003909 if (status != NO_ERROR) {
3910 LOG_FATAL("Policy engine not initialized(err=%d)", status);
3911 return status;
3912 }
François Gaffie2110e042015-03-24 08:41:51 +01003913
Eric Laurent3a4311c2014-03-17 12:00:47 -07003914 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003915 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003916 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3917 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Mikhail Naganovd4120142017-12-06 15:49:22 -08003918 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003919 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08003920 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
3921 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003922 continue;
3923 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08003924 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07003925 // open all output streams needed to access attached devices
3926 // except for direct output streams that are only opened when they are actually
3927 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003928 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003929 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003930 if (!outProfile->canOpenNewIo()) {
3931 ALOGE("Invalid Output profile max open count %u for profile %s",
3932 outProfile->maxOpenCount, outProfile->getTagName().c_str());
3933 continue;
3934 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003935 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003936 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003937 continue;
3938 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003939 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003940 mTtsOutputAvailable = true;
3941 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003942
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003943 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003944 continue;
3945 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003946 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003947 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3948 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003949 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003950 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003951 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003952 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003953 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003954 if ((profileType & outputDeviceTypes) == 0) {
3955 continue;
3956 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003957 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3958 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003959 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov708e0382018-05-30 09:53:04 -07003960 const DeviceVector &devicesForType = supportedDevices.getDevicesFromTypeMask(
3961 profileType);
Eric Laurentc40d9692016-04-13 19:14:13 -07003962 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3963 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003964 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08003965 status_t status = outputDesc->open(nullptr, profileType, address,
3966 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07003967
3968 if (status != NO_ERROR) {
3969 ALOGW("Cannot open output stream for device %08x on hw module %s",
3970 outputDesc->mDevice,
Mikhail Naganovd4120142017-12-06 15:49:22 -08003971 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003972 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003973 for (const auto& dev : supportedDevices) {
3974 ssize_t index = mAvailableOutputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07003975 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003976 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003977 mAvailableOutputDevices[index]->attach(hwModule);
Eric Laurentd78f1532014-09-16 16:38:20 -07003978 }
3979 }
3980 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003981 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003982 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003983 }
3984 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003985 setOutputDevice(outputDesc,
Eric Laurentfe231122017-11-17 17:48:06 -08003986 profileType,
Eric Laurentc40d9692016-04-13 19:14:13 -07003987 true,
3988 0,
3989 NULL,
Eric Laurentfe231122017-11-17 17:48:06 -08003990 address);
Eric Laurentd78f1532014-09-16 16:38:20 -07003991 }
Eric Laurente552edb2014-03-10 17:42:56 -07003992 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003993 // open input streams needed to access attached devices to validate
3994 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003995 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003996 if (!inProfile->canOpenNewIo()) {
3997 ALOGE("Invalid Input profile max open count %u for profile %s",
3998 inProfile->maxOpenCount, inProfile->getTagName().c_str());
3999 continue;
4000 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004001 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004002 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004003 continue;
4004 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004005 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07004006 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004007 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
4008
Eric Laurentd78f1532014-09-16 16:38:20 -07004009 if ((profileType & inputDeviceTypes) == 0) {
4010 continue;
4011 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08004012 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08004013 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004014
Mikhail Naganov708e0382018-05-30 09:53:04 -07004015 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(profileType);
Eric Laurent53b810e2017-12-10 17:25:10 -08004016 // the inputs vector must be of size >= 1, but we don't want to crash here
4017 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
4018 : String8("");
4019 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
4020 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
4021
Eric Laurentd78f1532014-09-16 16:38:20 -07004022 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004023 status_t status = inputDesc->open(nullptr,
4024 profileType,
Eric Laurent53b810e2017-12-10 17:25:10 -08004025 address,
Eric Laurentfe231122017-11-17 17:48:06 -08004026 AUDIO_SOURCE_MIC,
4027 AUDIO_INPUT_FLAG_NONE,
4028 &input);
Eric Laurentd78f1532014-09-16 16:38:20 -07004029
4030 if (status == NO_ERROR) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004031 for (const auto& dev : inProfile->getSupportedDevices()) {
4032 ssize_t index = mAvailableInputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07004033 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07004034 if (index >= 0) {
4035 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
4036 if (!devDesc->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004037 devDesc->attach(hwModule);
Eric Laurent83efe1c2017-07-09 16:51:08 -07004038 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07004039 }
Eric Laurentd78f1532014-09-16 16:38:20 -07004040 }
4041 }
Eric Laurentfe231122017-11-17 17:48:06 -08004042 inputDesc->close();
Eric Laurentd78f1532014-09-16 16:38:20 -07004043 } else {
4044 ALOGW("Cannot open input stream for device %08x on hw module %s",
Eric Laurentfe231122017-11-17 17:48:06 -08004045 profileType,
Mikhail Naganovd4120142017-12-06 15:49:22 -08004046 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07004047 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004048 }
4049 }
4050 // make sure all attached devices have been allocated a unique ID
4051 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004052 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004053 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004054 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
4055 continue;
4056 }
François Gaffie2110e042015-03-24 08:41:51 +01004057 // The device is now validated and can be appended to the available devices of the engine
4058 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
4059 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004060 i++;
4061 }
4062 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004063 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01004064 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004065 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
4066 continue;
4067 }
François Gaffie2110e042015-03-24 08:41:51 +01004068 // The device is now validated and can be appended to the available devices of the engine
4069 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
4070 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004071 i++;
4072 }
4073 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004074 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01004075 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004076 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004077 }
jiabin9ff780e2018-03-19 18:19:52 -07004078 // If microphones address is empty, set it according to device type
4079 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
4080 if (mAvailableInputDevices[i]->mAddress.isEmpty()) {
4081 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
4082 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
4083 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
4084 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BACK_MICROPHONE_ADDRESS);
4085 }
4086 }
4087 }
Eric Laurente552edb2014-03-10 17:42:56 -07004088
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004089 if (mPrimaryOutput == 0) {
4090 ALOGE("Failed to open primary output");
4091 status = NO_INIT;
4092 }
Eric Laurente552edb2014-03-10 17:42:56 -07004093
4094 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004095 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004096}
4097
Eric Laurente0720872014-03-11 09:30:41 -07004098AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004099{
Eric Laurente552edb2014-03-10 17:42:56 -07004100 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004101 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004102 }
4103 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004104 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004105 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004106 mAvailableOutputDevices.clear();
4107 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004108 mOutputs.clear();
4109 mInputs.clear();
4110 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004111 mHwModulesAll.clear();
jiabin81772902018-04-02 17:52:27 -07004112 mSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004113}
4114
Eric Laurente0720872014-03-11 09:30:41 -07004115status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004116{
Eric Laurent87ffa392015-05-22 10:32:38 -07004117 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004118}
4119
Eric Laurente552edb2014-03-10 17:42:56 -07004120// ---
4121
Eric Laurent98e38192018-02-15 18:31:53 -08004122void AudioPolicyManager::addOutput(audio_io_handle_t output,
4123 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004124{
Eric Laurent1c333e22014-05-20 10:48:17 -07004125 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08004126 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004127 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004128 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004129 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004130}
4131
François Gaffie53615e22015-03-19 09:24:12 +01004132void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4133{
4134 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004135 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004136}
4137
Eric Laurent98e38192018-02-15 18:31:53 -08004138void AudioPolicyManager::addInput(audio_io_handle_t input,
4139 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004140{
Eric Laurent1c333e22014-05-20 10:48:17 -07004141 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004142 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004143}
Eric Laurente552edb2014-03-10 17:42:56 -07004144
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004145void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08004146 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004147 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004148 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08004149 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004150 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08004151 if (devDesc != 0) {
4152 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
4153 desc->mIoHandle, address.string());
4154 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004155 }
4156}
4157
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004158status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004159 audio_policy_dev_state_t state,
4160 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004161 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07004162{
François Gaffie53615e22015-03-19 09:24:12 +01004163 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07004164 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004165
4166 if (audio_device_is_digital(device)) {
4167 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004168 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004169 }
Eric Laurente552edb2014-03-10 17:42:56 -07004170
Eric Laurent3b73df72014-03-11 09:06:29 -07004171 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004172 // first list already open outputs that can be routed to this device
4173 for (size_t i = 0; i < mOutputs.size(); i++) {
4174 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07004175 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004176 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004177 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
4178 outputs.add(mOutputs.keyAt(i));
4179 } else {
4180 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08004181 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004182 }
Eric Laurente552edb2014-03-10 17:42:56 -07004183 }
4184 }
4185 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004186 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004187 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004188 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4189 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004190 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004191 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004192 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004193 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004194 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4195 j, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004196 }
Eric Laurente552edb2014-03-10 17:42:56 -07004197 }
4198 }
4199 }
4200
Eric Laurent7b279bb2015-12-14 10:18:23 -08004201 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004202
Eric Laurente552edb2014-03-10 17:42:56 -07004203 if (profiles.isEmpty() && outputs.isEmpty()) {
4204 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4205 return BAD_VALUE;
4206 }
4207
4208 // open outputs for matching profiles if needed. Direct outputs are also opened to
4209 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4210 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004211 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004212
4213 // nothing to do if one output is already opened for this profile
4214 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004215 for (j = 0; j < outputs.size(); j++) {
4216 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004217 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004218 // matching profile: save the sample rates, format and channel masks supported
4219 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07004220 if (audio_device_is_digital(device)) {
4221 devDesc->importAudioPort(profile);
4222 }
Eric Laurente552edb2014-03-10 17:42:56 -07004223 break;
4224 }
4225 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004226 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004227 continue;
4228 }
4229
Eric Laurent3974e3b2017-12-07 17:58:43 -08004230 if (!profile->canOpenNewIo()) {
4231 ALOGW("Max Output number %u already opened for this profile %s",
4232 profile->maxOpenCount, profile->getTagName().c_str());
4233 continue;
4234 }
4235
Eric Laurent83efe1c2017-07-09 16:51:08 -07004236 ALOGV("opening output for device %08x with params %s profile %p name %s",
4237 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004238 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004239 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004240 status_t status = desc->open(nullptr, device, address,
4241 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004242
Eric Laurentfe231122017-11-17 17:48:06 -08004243 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004244 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004245 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004246 char *param = audio_device_address_to_parameter(device, address);
4247 mpClientInterface->setParameters(output, String8(param));
4248 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004249 }
Phil Burk00eeb322016-03-31 12:41:00 -07004250 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004251 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004252 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004253 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004254 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004255 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004256 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004257 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004258 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4259 profile->pickAudioProfile(
4260 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004261 config.offload_info.sample_rate = config.sample_rate;
4262 config.offload_info.channel_mask = config.channel_mask;
4263 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004264
4265 status_t status = desc->open(&config, device, address, AUDIO_STREAM_DEFAULT,
4266 AUDIO_OUTPUT_FLAG_NONE, &output);
4267 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004268 output = AUDIO_IO_HANDLE_NONE;
4269 }
Eric Laurentd4692962014-05-05 18:13:44 -07004270 }
4271
Eric Laurentcf2c0212014-07-25 16:20:43 -07004272 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004273 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01004274 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004275 sp<AudioPolicyMix> policyMix;
4276 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004277 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
4278 address.string());
4279 }
François Gaffie036e1e92015-03-19 10:16:24 +01004280 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07004281 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01004282
Eric Laurent87ffa392015-05-22 10:32:38 -07004283 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4284 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004285 // no duplicated output for direct outputs and
4286 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004287 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004288
Eric Laurentd4692962014-05-05 18:13:44 -07004289 //TODO: configure audio effect output stage here
4290
4291 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004292 sp<SwAudioOutputDescriptor> dupOutputDesc =
4293 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4294 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4295 &duplicatedOutput);
4296 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004297 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004298 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004299 } else {
4300 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004301 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004302 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004303 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004304 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004305 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004306 }
Eric Laurente552edb2014-03-10 17:42:56 -07004307 }
4308 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004309 } else {
4310 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004311 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004312 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004313 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004314 profiles.removeAt(profile_index);
4315 profile_index--;
4316 } else {
4317 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004318 // Load digital format info only for digital devices
4319 if (audio_device_is_digital(device)) {
4320 devDesc->importAudioPort(profile);
4321 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004322
François Gaffie53615e22015-03-19 09:24:12 +01004323 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004324 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4325 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004326 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004327 NULL/*patch handle*/, address.string());
4328 }
Eric Laurente552edb2014-03-10 17:42:56 -07004329 ALOGV("checkOutputsForDevice(): adding output %d", output);
4330 }
4331 }
4332
4333 if (profiles.isEmpty()) {
4334 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4335 return BAD_VALUE;
4336 }
Eric Laurentd4692962014-05-05 18:13:44 -07004337 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004338 // check if one opened output is not needed any more after disconnecting one device
4339 for (size_t i = 0; i < mOutputs.size(); i++) {
4340 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004341 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004342 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004343 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004344 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004345 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004346 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004347 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4348 mOutputs.keyAt(i));
4349 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004350 }
Eric Laurente552edb2014-03-10 17:42:56 -07004351 }
4352 }
Eric Laurentd4692962014-05-05 18:13:44 -07004353 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004354 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004355 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4356 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004357 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004358 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004359 "clearing direct output profile %zu on module %s",
4360 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004361 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004362 }
4363 }
4364 }
4365 }
4366 return NO_ERROR;
4367}
4368
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004369status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004370 audio_policy_dev_state_t state,
4371 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004372 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004373{
Paul McLean9080a4c2015-06-18 08:24:02 -07004374 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004375 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004376
4377 if (audio_device_is_digital(device)) {
4378 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004379 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004380 }
4381
Eric Laurentd4692962014-05-05 18:13:44 -07004382 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4383 // first list already open inputs that can be routed to this device
4384 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4385 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004386 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004387 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4388 inputs.add(mInputs.keyAt(input_index));
4389 }
4390 }
4391
4392 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004393 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004394 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004395 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004396 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004397 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004398 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004399
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004400 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004401 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004402 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004403 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004404 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4405 profile_index, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004406 }
Eric Laurentd4692962014-05-05 18:13:44 -07004407 }
4408 }
4409 }
4410
4411 if (profiles.isEmpty() && inputs.isEmpty()) {
4412 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4413 return BAD_VALUE;
4414 }
4415
4416 // open inputs for matching profiles if needed. Direct inputs are also opened to
4417 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4418 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4419
Eric Laurent1c333e22014-05-20 10:48:17 -07004420 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004421
Eric Laurentd4692962014-05-05 18:13:44 -07004422 // nothing to do if one input is already opened for this profile
4423 size_t input_index;
4424 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4425 desc = mInputs.valueAt(input_index);
4426 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004427 if (audio_device_is_digital(device)) {
4428 devDesc->importAudioPort(profile);
4429 }
Eric Laurentd4692962014-05-05 18:13:44 -07004430 break;
4431 }
4432 }
4433 if (input_index != mInputs.size()) {
4434 continue;
4435 }
4436
Eric Laurent3974e3b2017-12-07 17:58:43 -08004437 if (!profile->canOpenNewIo()) {
4438 ALOGW("Max Input number %u already opened for this profile %s",
4439 profile->maxOpenCount, profile->getTagName().c_str());
4440 continue;
4441 }
4442
Eric Laurentfe231122017-11-17 17:48:06 -08004443 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004444 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004445 status_t status = desc->open(nullptr,
4446 device,
4447 address,
4448 AUDIO_SOURCE_MIC,
4449 AUDIO_INPUT_FLAG_NONE,
4450 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004451
Eric Laurentcf2c0212014-07-25 16:20:43 -07004452 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004453 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004454 char *param = audio_device_address_to_parameter(device, address);
4455 mpClientInterface->setParameters(input, String8(param));
4456 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004457 }
Phil Burk00eeb322016-03-31 12:41:00 -07004458 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004459 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004460 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004461 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004462 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004463 }
4464
4465 if (input != 0) {
4466 addInput(input, desc);
4467 }
4468 } // endif input != 0
4469
Eric Laurentcf2c0212014-07-25 16:20:43 -07004470 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004471 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004472 profiles.removeAt(profile_index);
4473 profile_index--;
4474 } else {
4475 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004476 if (audio_device_is_digital(device)) {
4477 devDesc->importAudioPort(profile);
4478 }
Eric Laurentd4692962014-05-05 18:13:44 -07004479 ALOGV("checkInputsForDevice(): adding input %d", input);
4480 }
4481 } // end scan profiles
4482
4483 if (profiles.isEmpty()) {
4484 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4485 return BAD_VALUE;
4486 }
4487 } else {
4488 // Disconnect
4489 // check if one opened input is not needed any more after disconnecting one device
4490 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4491 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004492 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004493 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4494 mInputs.keyAt(input_index));
4495 inputs.add(mInputs.keyAt(input_index));
4496 }
4497 }
4498 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004499 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004500 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004501 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004502 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004503 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004504 if (profile->supportDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004505 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4506 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004507 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004508 }
4509 }
4510 }
4511 } // end disconnect
4512
4513 return NO_ERROR;
4514}
4515
4516
Eric Laurente0720872014-03-11 09:30:41 -07004517void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004518{
4519 ALOGV("closeOutput(%d)", output);
4520
Eric Laurentc75307b2015-03-17 15:29:32 -07004521 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004522 if (outputDesc == NULL) {
4523 ALOGW("closeOutput() unknown output %d", output);
4524 return;
4525 }
François Gaffie036e1e92015-03-19 10:16:24 +01004526 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004527
Eric Laurente552edb2014-03-10 17:42:56 -07004528 // look for duplicated outputs connected to the output being removed.
4529 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004530 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004531 if (dupOutputDesc->isDuplicated() &&
4532 (dupOutputDesc->mOutput1 == outputDesc ||
4533 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004534 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004535 if (dupOutputDesc->mOutput1 == outputDesc) {
4536 outputDesc2 = dupOutputDesc->mOutput2;
4537 } else {
4538 outputDesc2 = dupOutputDesc->mOutput1;
4539 }
4540 // As all active tracks on duplicated output will be deleted,
4541 // and as they were also referenced on the other output, the reference
4542 // count for their stream type must be adjusted accordingly on
4543 // the other output.
Eric Laurent733ce942017-12-07 12:18:25 -08004544 bool wasActive = outputDesc2->isActive();
Eric Laurent3b73df72014-03-11 09:06:29 -07004545 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004546 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07004547 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004548 }
Eric Laurent733ce942017-12-07 12:18:25 -08004549 // stop() will be a no op if the output is still active but is needed in case all
4550 // active streams refcounts where cleared above
4551 if (wasActive) {
4552 outputDesc2->stop();
4553 }
Eric Laurente552edb2014-03-10 17:42:56 -07004554 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4555 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4556
4557 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004558 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004559 }
4560 }
4561
Eric Laurent05b90f82014-08-27 15:32:29 -07004562 nextAudioPortGeneration();
4563
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004564 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004565 if (index >= 0) {
4566 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004567 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004568 mAudioPatches.removeItemsAt(index);
4569 mpClientInterface->onAudioPatchListUpdate();
4570 }
4571
Eric Laurentfe231122017-11-17 17:48:06 -08004572 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004573
François Gaffie53615e22015-03-19 09:24:12 +01004574 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004575 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004576}
4577
4578void AudioPolicyManager::closeInput(audio_io_handle_t input)
4579{
4580 ALOGV("closeInput(%d)", input);
4581
4582 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4583 if (inputDesc == NULL) {
4584 ALOGW("closeInput() unknown input %d", input);
4585 return;
4586 }
4587
Eric Laurent6a94d692014-05-20 11:18:06 -07004588 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004589
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004590 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004591 if (index >= 0) {
4592 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004593 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004594 mAudioPatches.removeItemsAt(index);
4595 mpClientInterface->onAudioPatchListUpdate();
4596 }
4597
Eric Laurentfe231122017-11-17 17:48:06 -08004598 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004599 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004600}
4601
Eric Laurentc75307b2015-03-17 15:29:32 -07004602SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4603 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004604 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004605{
4606 SortedVector<audio_io_handle_t> outputs;
4607
4608 ALOGVV("getOutputsForDevice() device %04x", device);
4609 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004610 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004611 i, openOutputs.valueAt(i)->isDuplicated(),
4612 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004613 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4614 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4615 outputs.add(openOutputs.keyAt(i));
4616 }
4617 }
4618 return outputs;
4619}
4620
Eric Laurente0720872014-03-11 09:30:41 -07004621bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
François Gaffie53615e22015-03-19 09:24:12 +01004622 SortedVector<audio_io_handle_t>& outputs2)
Eric Laurente552edb2014-03-10 17:42:56 -07004623{
4624 if (outputs1.size() != outputs2.size()) {
4625 return false;
4626 }
4627 for (size_t i = 0; i < outputs1.size(); i++) {
4628 if (outputs1[i] != outputs2[i]) {
4629 return false;
4630 }
4631 }
4632 return true;
4633}
4634
Eric Laurente0720872014-03-11 09:30:41 -07004635void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004636{
4637 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4638 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4639 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4640 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4641
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004642 // also take into account external policy-related changes: add all outputs which are
4643 // associated with policies in the "before" and "after" output vectors
4644 ALOGVV("checkOutputForStrategy(): policy related outputs");
4645 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004646 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004647 if (desc != 0 && desc->mPolicyMix != NULL) {
4648 srcOutputs.add(desc->mIoHandle);
4649 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4650 }
4651 }
4652 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004653 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004654 if (desc != 0 && desc->mPolicyMix != NULL) {
4655 dstOutputs.add(desc->mIoHandle);
4656 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4657 }
4658 }
4659
Eric Laurente552edb2014-03-10 17:42:56 -07004660 if (!vectorsEqual(srcOutputs,dstOutputs)) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004661 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4662 // audio from invalidated tracks will be rendered when unmuting
4663 uint32_t maxLatency = 0;
4664 for (audio_io_handle_t srcOut : srcOutputs) {
4665 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4666 if (desc != 0 && maxLatency < desc->latency()) {
4667 maxLatency = desc->latency();
4668 }
4669 }
Eric Laurente552edb2014-03-10 17:42:56 -07004670 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4671 strategy, srcOutputs[0], dstOutputs[0]);
4672 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004673 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004674 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4675 if (desc != 0 && isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004676 setStrategyMute(strategy, true, desc);
Eric Laurentac3a6902018-05-11 16:39:10 -07004677 setStrategyMute(strategy, false, desc, maxLatency * LATENCY_MUTE_FACTOR, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004678 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004679 sp<AudioSourceDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004680 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004681 if (source != 0){
4682 connectAudioSource(source);
4683 }
Eric Laurente552edb2014-03-10 17:42:56 -07004684 }
4685
4686 // Move effects associated to this strategy from previous output to new output
4687 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004688 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004689 }
4690 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004691 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004692 if (getStrategy((audio_stream_type_t)i) == strategy) {
4693 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004694 }
4695 }
4696 }
4697}
4698
Eric Laurente0720872014-03-11 09:30:41 -07004699void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004700{
François Gaffie2110e042015-03-24 08:41:51 +01004701 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004702 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004703 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004704 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004705 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004706 checkOutputForStrategy(STRATEGY_SONIFICATION);
4707 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004708 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004709 checkOutputForStrategy(STRATEGY_MEDIA);
4710 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004711 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004712}
4713
Eric Laurente0720872014-03-11 09:30:41 -07004714void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004715{
François Gaffie53615e22015-03-19 09:24:12 +01004716 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004717 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004718 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004719 return;
4720 }
4721
Eric Laurent3a4311c2014-03-17 12:00:47 -07004722 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004723 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4724 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4725 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004726
4727 // if suspended, restore A2DP output if:
4728 // ((SCO device is NOT connected) ||
4729 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4730 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004731 //
Eric Laurentf732e072016-08-03 19:30:28 -07004732 // if not suspended, suspend A2DP output if:
4733 // (SCO device is connected) &&
4734 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4735 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004736 //
4737 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004738 if (!isScoConnected ||
4739 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4740 AUDIO_POLICY_FORCE_BT_SCO) &&
4741 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4742 AUDIO_POLICY_FORCE_BT_SCO) &&
4743 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004744 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004745
4746 mpClientInterface->restoreOutput(a2dpOutput);
4747 mA2dpSuspended = false;
4748 }
4749 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004750 if (isScoConnected &&
4751 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4752 AUDIO_POLICY_FORCE_BT_SCO) ||
4753 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4754 AUDIO_POLICY_FORCE_BT_SCO) ||
4755 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004756 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004757
4758 mpClientInterface->suspendOutput(a2dpOutput);
4759 mA2dpSuspended = true;
4760 }
4761 }
4762}
4763
Eric Laurentc75307b2015-03-17 15:29:32 -07004764audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4765 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004766{
4767 audio_devices_t device = AUDIO_DEVICE_NONE;
4768
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004769 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004770 if (index >= 0) {
4771 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4772 if (patchDesc->mUid != mUidCached) {
4773 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004774 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004775 return outputDesc->device();
4776 }
4777 }
4778
Eric Laurentf3a5a602018-05-22 18:42:55 -07004779 // Check if an explicit routing request exists for an active stream on this output and
4780 // use it in priority before any other rule
4781 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
4782 if (outputDesc->isStreamActive((audio_stream_type_t)stream)) {
4783 audio_devices_t forcedDevice =
4784 mOutputRoutes.getActiveDeviceForStream(
4785 (audio_stream_type_t)stream, mAvailableOutputDevices);
4786
4787 if (forcedDevice != AUDIO_DEVICE_NONE) {
4788 return forcedDevice;
4789 }
4790 }
4791 }
4792
Eric Laurente552edb2014-03-10 17:42:56 -07004793 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004794 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004795 // use device for strategy enforced audible
4796 // 2: we are in call or the strategy phone is active on the output:
4797 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004798 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004799 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004800 // 4: the strategy for enforced audible is active but not enforced on the output:
4801 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004802 // 5: the strategy accessibility is active on the output:
4803 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004804 // 6: the strategy "respectful" sonification is active on the output:
4805 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004806 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004807 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004808 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004809 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004810 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004811 // use device for strategy t-t-s
Eric Laurent484e9272018-06-07 17:29:23 -07004812
4813 // FIXME: extend use of isStrategyActiveOnSameModule() to all strategies
4814 // with a refined rule considering mutually exclusive devices (using same backend)
4815 // as opposed to all streams on the same audio HAL module.
François Gaffiead3183e2015-03-18 16:55:35 +01004816 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004817 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004818 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4819 } else if (isInCall() ||
Eric Laurent484e9272018-06-07 17:29:23 -07004820 isStrategyActiveOnSameModule(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004821 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004822 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004823 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004824 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
4825 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004826 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4827 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004828 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004829 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004830 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004831 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004832 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004833 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004834 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004835 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004836 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004837 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004838 }
4839
Eric Laurent1c333e22014-05-20 10:48:17 -07004840 ALOGV("getNewOutputDevice() selected device %x", device);
4841 return device;
4842}
4843
Eric Laurentfb66dd92016-01-28 18:32:03 -08004844audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004845{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004846 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004847
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004848 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004849 if (index >= 0) {
4850 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4851 if (patchDesc->mUid != mUidCached) {
4852 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004853 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004854 return inputDesc->mDevice;
4855 }
4856 }
4857
Eric Laurentdc95a252018-04-12 12:46:56 -07004858 // If we are not in call and no client is active on this input, this methods returns
4859 // AUDIO_DEVICE_NONE, causing the patch on the input stream to be released.
Eric Laurentfb66dd92016-01-28 18:32:03 -08004860 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
Eric Laurentdc95a252018-04-12 12:46:56 -07004861 if (source == AUDIO_SOURCE_DEFAULT && isInCall()) {
4862 source = AUDIO_SOURCE_VOICE_COMMUNICATION;
4863 }
4864 if (source != AUDIO_SOURCE_DEFAULT) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08004865 device = getDeviceAndMixForInputSource(source);
4866 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004867
Eric Laurente552edb2014-03-10 17:42:56 -07004868 return device;
4869}
4870
Eric Laurent794fde22016-03-11 09:50:45 -08004871bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4872 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004873 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004874}
4875
Eric Laurente0720872014-03-11 09:30:41 -07004876uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004877 return (uint32_t)getStrategy(stream);
4878}
4879
Eric Laurente0720872014-03-11 09:30:41 -07004880audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004881 // By checking the range of stream before calling getStrategy, we avoid
4882 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4883 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004884 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004885 return AUDIO_DEVICE_NONE;
4886 }
Eric Laurent28d09f02016-03-08 10:43:05 -08004887 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004888 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4889 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004890 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004891 }
Eric Laurent794fde22016-03-11 09:50:45 -08004892 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004893 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004894 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004895 for (audio_io_handle_t output : getOutputsForDevice(curDevices, mOutputs)) {
4896 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08004897 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004898 curDevices |= outputDesc->device();
4899 }
4900 }
4901 devices |= curDevices;
Eric Laurente552edb2014-03-10 17:42:56 -07004902 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004903
4904 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4905 and doesn't really need to.*/
4906 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4907 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4908 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4909 }
Eric Laurente552edb2014-03-10 17:42:56 -07004910 return devices;
4911}
4912
François Gaffie2110e042015-03-24 08:41:51 +01004913routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4914{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004915 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004916 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004917}
4918
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004919uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4920 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004921 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4922 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4923 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004924 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4925 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4926 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004927 // usage to strategy mapping
François Gaffie2110e042015-03-24 08:41:51 +01004928 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004929}
4930
Eric Laurente0720872014-03-11 09:30:41 -07004931void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004932 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004933 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004934 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4935 updateDevicesAndOutputs();
4936 break;
4937 default:
4938 break;
4939 }
4940}
4941
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004942uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004943
4944 // skip beacon mute management if a dedicated TTS output is available
4945 if (mTtsOutputAvailable) {
4946 return 0;
4947 }
4948
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004949 switch(event) {
4950 case STARTING_OUTPUT:
4951 mBeaconMuteRefCount++;
4952 break;
4953 case STOPPING_OUTPUT:
4954 if (mBeaconMuteRefCount > 0) {
4955 mBeaconMuteRefCount--;
4956 }
4957 break;
4958 case STARTING_BEACON:
4959 mBeaconPlayingRefCount++;
4960 break;
4961 case STOPPING_BEACON:
4962 if (mBeaconPlayingRefCount > 0) {
4963 mBeaconPlayingRefCount--;
4964 }
4965 break;
4966 }
4967
4968 if (mBeaconMuteRefCount > 0) {
4969 // any playback causes beacon to be muted
4970 return setBeaconMute(true);
4971 } else {
4972 // no other playback: unmute when beacon starts playing, mute when it stops
4973 return setBeaconMute(mBeaconPlayingRefCount == 0);
4974 }
4975}
4976
4977uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4978 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4979 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4980 // keep track of muted state to avoid repeating mute/unmute operations
4981 if (mBeaconMuted != mute) {
4982 // mute/unmute AUDIO_STREAM_TTS on all outputs
4983 ALOGV("\t muting %d", mute);
4984 uint32_t maxLatency = 0;
4985 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004986 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004987 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07004988 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004989 0 /*delay*/, AUDIO_DEVICE_NONE);
4990 const uint32_t latency = desc->latency() * 2;
4991 if (latency > maxLatency) {
4992 maxLatency = latency;
4993 }
4994 }
4995 mBeaconMuted = mute;
4996 return maxLatency;
4997 }
4998 return 0;
4999}
5000
Eric Laurente0720872014-03-11 09:30:41 -07005001audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01005002 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005003{
Eric Laurentf3a5a602018-05-22 18:42:55 -07005004 // Check if an explicit routing request exists for a stream type corresponding to the
5005 // specified strategy and use it in priority over default routing rules.
5006 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
5007 if (getStrategy((audio_stream_type_t)stream) == strategy) {
5008 audio_devices_t forcedDevice =
5009 mOutputRoutes.getActiveDeviceForStream(
5010 (audio_stream_type_t)stream, mAvailableOutputDevices);
5011 if (forcedDevice != AUDIO_DEVICE_NONE) {
5012 return forcedDevice;
5013 }
Paul McLeanaa981192015-03-21 09:55:15 -07005014 }
5015 }
5016
Eric Laurente552edb2014-03-10 17:42:56 -07005017 if (fromCache) {
5018 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
5019 strategy, mDeviceForStrategy[strategy]);
5020 return mDeviceForStrategy[strategy];
5021 }
François Gaffie2110e042015-03-24 08:41:51 +01005022 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07005023}
5024
Eric Laurente0720872014-03-11 09:30:41 -07005025void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005026{
5027 for (int i = 0; i < NUM_STRATEGIES; i++) {
5028 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
5029 }
5030 mPreviousOutputs = mOutputs;
5031}
5032
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005033uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005034 audio_devices_t prevDevice,
5035 uint32_t delayMs)
5036{
5037 // mute/unmute strategies using an incompatible device combination
5038 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5039 // if unmuting, unmute only after the specified delay
5040 if (outputDesc->isDuplicated()) {
5041 return 0;
5042 }
5043
5044 uint32_t muteWaitMs = 0;
5045 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07005046 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005047
5048 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
5049 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07005050 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07005051 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
5052 bool doMute = false;
5053
5054 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
5055 doMute = true;
5056 outputDesc->mStrategyMutedByDevice[i] = true;
5057 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
5058 doMute = true;
5059 outputDesc->mStrategyMutedByDevice[i] = false;
5060 }
Eric Laurent99401132014-05-07 19:48:15 -07005061 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005062 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005063 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005064 // skip output if it does not share any device with current output
5065 if ((desc->supportedDevices() & outputDesc->supportedDevices())
5066 == AUDIO_DEVICE_NONE) {
5067 continue;
5068 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005069 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07005070 mute ? "muting" : "unmuting", i, curDevice);
5071 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005072 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005073 if (mute) {
5074 // FIXME: should not need to double latency if volume could be applied
5075 // immediately by the audioflinger mixer. We must account for the delay
5076 // between now and the next time the audioflinger thread for this output
5077 // will process a buffer (which corresponds to one buffer size,
5078 // usually 1/2 or 1/4 of the latency).
5079 if (muteWaitMs < desc->latency() * 2) {
5080 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005081 }
5082 }
5083 }
5084 }
5085 }
5086 }
5087
Eric Laurent99401132014-05-07 19:48:15 -07005088 // temporary mute output if device selection changes to avoid volume bursts due to
5089 // different per device volumes
5090 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005091 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5092 // temporary mute duration is conservatively set to 4 times the reported latency
5093 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5094 if (muteWaitMs < tempMuteWaitMs) {
5095 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005096 }
Eric Laurentdc462862016-07-19 12:29:53 -07005097
Eric Laurent99401132014-05-07 19:48:15 -07005098 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005099 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005100 // make sure that we do not start the temporary mute period too early in case of
5101 // delayed device change
5102 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005103 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07005104 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07005105 }
5106 }
5107 }
5108
Eric Laurente552edb2014-03-10 17:42:56 -07005109 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5110 if (muteWaitMs > delayMs) {
5111 muteWaitMs -= delayMs;
5112 usleep(muteWaitMs * 1000);
5113 return muteWaitMs;
5114 }
5115 return 0;
5116}
5117
Eric Laurentc75307b2015-03-17 15:29:32 -07005118uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005119 audio_devices_t device,
5120 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07005121 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005122 audio_patch_handle_t *patchHandle,
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005123 const char *address,
5124 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005125{
Eric Laurentc75307b2015-03-17 15:29:32 -07005126 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005127 AudioParameter param;
5128 uint32_t muteWaitMs;
5129
5130 if (outputDesc->isDuplicated()) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005131 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs,
5132 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
5133 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs,
5134 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005135 return muteWaitMs;
5136 }
5137 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5138 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07005139 if ((device != AUDIO_DEVICE_NONE) &&
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005140 ((device & outputDesc->supportedDevices()) == AUDIO_DEVICE_NONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005141 return 0;
5142 }
5143
5144 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07005145 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07005146
5147 audio_devices_t prevDevice = outputDesc->mDevice;
5148
Paul McLeanaa981192015-03-21 09:55:15 -07005149 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005150
5151 if (device != AUDIO_DEVICE_NONE) {
5152 outputDesc->mDevice = device;
5153 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005154
5155 // if the outputs are not materially active, there is no need to mute.
5156 if (requiresMuteCheck) {
5157 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
5158 } else {
5159 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5160 muteWaitMs = 0;
5161 }
Eric Laurente552edb2014-03-10 17:42:56 -07005162
5163 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005164 // the requested device is AUDIO_DEVICE_NONE
5165 // OR the requested device is the same as current device
5166 // AND force is not specified
5167 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07005168 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07005169 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
5170 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005171 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005172 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005173 return muteWaitMs;
5174 }
5175
5176 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07005177
Eric Laurente552edb2014-03-10 17:42:56 -07005178 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07005179 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005180 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005181 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07005182 DeviceVector deviceList;
5183 if ((address == NULL) || (strlen(address) == 0)) {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005184 deviceList = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurentc40d9692016-04-13 19:14:13 -07005185 } else {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005186 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
5187 device, String8(address));
5188 if (deviceDesc) deviceList.add(deviceDesc);
Eric Laurentc40d9692016-04-13 19:14:13 -07005189 }
5190
Eric Laurent1c333e22014-05-20 10:48:17 -07005191 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005192 PatchBuilder patchBuilder;
5193 patchBuilder.addSource(outputDesc);
Eric Laurent1c333e22014-05-20 10:48:17 -07005194 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005195 patchBuilder.addSink(deviceList.itemAt(i));
Eric Laurent1c333e22014-05-20 10:48:17 -07005196 }
Mikhail Naganovdc769682018-05-04 15:34:08 -07005197 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005198 }
bryant_liuf5e7e792014-08-19 20:07:05 +08005199
5200 // inform all input as well
5201 for (size_t i = 0; i < mInputs.size(); i++) {
5202 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01005203 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08005204 AudioParameter inputCmd = AudioParameter();
5205 ALOGV("%s: inform input %d of device:%d", __func__,
5206 inputDescriptor->mIoHandle, device);
5207 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
5208 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
5209 inputCmd.toString(),
5210 delayMs);
5211 }
5212 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005213 }
Eric Laurente552edb2014-03-10 17:42:56 -07005214
5215 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07005216 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005217
5218 return muteWaitMs;
5219}
5220
Eric Laurentc75307b2015-03-17 15:29:32 -07005221status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005222 int delayMs,
5223 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005224{
Eric Laurent6a94d692014-05-20 11:18:06 -07005225 ssize_t index;
5226 if (patchHandle) {
5227 index = mAudioPatches.indexOfKey(*patchHandle);
5228 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005229 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005230 }
5231 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005232 return INVALID_OPERATION;
5233 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005234 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5235 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005236 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005237 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005238 removeAudioPatch(patchDesc->mHandle);
5239 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005240 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005241 return status;
5242}
5243
5244status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5245 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005246 bool force,
5247 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005248{
5249 status_t status = NO_ERROR;
5250
Eric Laurent1f2f2232014-06-02 12:01:23 -07005251 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005252 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5253 inputDesc->mDevice = device;
5254
Mikhail Naganov708e0382018-05-30 09:53:04 -07005255 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005256 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005257 PatchBuilder patchBuilder;
5258 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005259 // AUDIO_SOURCE_HOTWORD is for internal use only:
5260 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07005261 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5262 auto result = usecase;
5263 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5264 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5265 }
5266 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07005267 //only one input device for now
Mikhail Naganovdc769682018-05-04 15:34:08 -07005268 addSource(deviceList.itemAt(0));
5269 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005270 }
5271 }
5272 return status;
5273}
5274
Eric Laurent6a94d692014-05-20 11:18:06 -07005275status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5276 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005277{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005278 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005279 ssize_t index;
5280 if (patchHandle) {
5281 index = mAudioPatches.indexOfKey(*patchHandle);
5282 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005283 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005284 }
5285 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005286 return INVALID_OPERATION;
5287 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005288 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5289 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005290 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005291 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005292 removeAudioPatch(patchDesc->mHandle);
5293 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005294 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005295 return status;
5296}
5297
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005298sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005299 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005300 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005301 audio_format_t& format,
5302 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005303 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005304{
5305 // Choose an input profile based on the requested capture parameters: select the first available
5306 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005307 //
5308 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5309 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005310
Glenn Kasten730b9262018-03-29 15:01:26 -07005311 sp<IOProfile> firstInexact;
5312 uint32_t updatedSamplingRate = 0;
5313 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5314 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005315 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005316 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005317 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005318 //updatedFormat = format;
Eric Laurent275e8e92014-11-30 15:14:47 -08005319 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005320 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005321 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005322 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005323 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005324 &channelMask /*updatedChannelMask*/,
5325 // FIXME ugly cast
5326 (audio_output_flags_t) flags,
5327 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005328 return profile;
5329 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005330 if (firstInexact == nullptr && profile->isCompatibleProfile(device, address,
5331 samplingRate,
5332 &updatedSamplingRate,
5333 format,
5334 &updatedFormat,
5335 channelMask,
5336 &updatedChannelMask,
5337 // FIXME ugly cast
5338 (audio_output_flags_t) flags,
5339 false /*exactMatchRequiredForInputFlags*/)) {
5340 firstInexact = profile;
5341 }
5342
Eric Laurente552edb2014-03-10 17:42:56 -07005343 }
5344 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005345 if (firstInexact != nullptr) {
5346 samplingRate = updatedSamplingRate;
5347 format = updatedFormat;
5348 channelMask = updatedChannelMask;
5349 return firstInexact;
5350 }
Eric Laurente552edb2014-03-10 17:42:56 -07005351 return NULL;
5352}
5353
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005354
5355audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005356 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005357{
François Gaffie036e1e92015-03-19 10:16:24 +01005358 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5359 audio_devices_t selectedDeviceFromMix =
5360 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005361
François Gaffie036e1e92015-03-19 10:16:24 +01005362 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5363 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005364 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005365 return getDeviceForInputSource(inputSource);
5366}
5367
5368audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5369{
Eric Laurentad2e7b92017-09-14 20:06:42 -07005370 // Routing
5371 // Scan the whole RouteMap to see if we have an explicit route:
5372 // if the input source in the RouteMap is the same as the argument above,
5373 // and activity count is non-zero and the device in the route descriptor is available
5374 // then select this device.
Paul McLean466dc8e2015-04-17 13:15:36 -06005375 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
5376 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
Eric Laurent2157f5b2018-04-25 18:33:02 -07005377 if ((inputSource == route->mSource) && route->isActiveOrChanged() &&
Eric Laurentad2e7b92017-09-14 20:06:42 -07005378 (mAvailableInputDevices.indexOf(route->mDeviceDescriptor) >= 0)) {
Paul McLean466dc8e2015-04-17 13:15:36 -06005379 return route->mDeviceDescriptor->type();
5380 }
5381 }
5382
5383 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005384}
5385
Eric Laurente0720872014-03-11 09:30:41 -07005386float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005387 int index,
5388 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005389{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005390 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005391
5392 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5393 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5394 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5395 // the ringtone volume
5396 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5397 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5398 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5399 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5400 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5401 }
5402
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005403 // in-call: always cap volume by voice volume + some low headroom
5404 if ((stream != AUDIO_STREAM_VOICE_CALL) &&
Eric Laurent7731b5a2018-04-06 15:47:22 -07005405 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005406 switch (stream) {
5407 case AUDIO_STREAM_SYSTEM:
5408 case AUDIO_STREAM_RING:
5409 case AUDIO_STREAM_MUSIC:
5410 case AUDIO_STREAM_ALARM:
5411 case AUDIO_STREAM_NOTIFICATION:
5412 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5413 case AUDIO_STREAM_DTMF:
5414 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005415 int voiceVolumeIndex =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005416 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, device);
Eric Laurent7731b5a2018-04-06 15:47:22 -07005417 const float maxVoiceVolDb =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005418 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, device)
Eric Laurent7731b5a2018-04-06 15:47:22 -07005419 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005420 if (volumeDB > maxVoiceVolDb) {
5421 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5422 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5423 volumeDB = maxVoiceVolDb;
5424 }
5425 } break;
5426 default:
5427 break;
5428 }
5429 }
5430
Eric Laurente552edb2014-03-10 17:42:56 -07005431 // if a headset is connected, apply the following rules to ring tones and notifications
5432 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005433 // - always attenuate notifications volume by 6dB
5434 // - attenuate ring tones volume by 6dB unless music is not playing and
5435 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005436 // - if music is playing, always limit the volume to current music volume,
5437 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005438 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005439 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5440 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5441 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005442 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005443 AUDIO_DEVICE_OUT_USB_HEADSET |
5444 AUDIO_DEVICE_OUT_HEARING_AID)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005445 ((stream_strategy == STRATEGY_SONIFICATION)
5446 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005447 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005448 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005449 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005450 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005451 // when the phone is ringing we must consider that music could have been paused just before
5452 // by the music application and behave as if music was active if the last music track was
5453 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005454 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005455 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005456 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005457 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005458 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005459 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5460 musicDevice),
5461 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005462 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5463 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005464 if (volumeDB > minVolDB) {
5465 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005466 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005467 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005468 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5469 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5470 // on A2DP, also ensure notification volume is not too low compared to media when
5471 // intended to be played
5472 if ((volumeDB > -96.0f) &&
5473 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5474 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5475 stream, device,
5476 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5477 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5478 }
5479 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005480 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5481 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005482 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005483 }
5484 }
5485
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005486 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005487}
5488
Eric Laurente0720872014-03-11 09:30:41 -07005489status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005490 int index,
5491 const sp<AudioOutputDescriptor>& outputDesc,
5492 audio_devices_t device,
5493 int delayMs,
5494 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005495{
Eric Laurente552edb2014-03-10 17:42:56 -07005496 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005497 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005498 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005499 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005500 return NO_ERROR;
5501 }
François Gaffie2110e042015-03-24 08:41:51 +01005502 audio_policy_forced_cfg_t forceUseForComm =
5503 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005504 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005505 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5506 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005507 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005508 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005509 return INVALID_OPERATION;
5510 }
5511
Eric Laurentc75307b2015-03-17 15:29:32 -07005512 if (device == AUDIO_DEVICE_NONE) {
5513 device = outputDesc->device();
5514 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005515
Eric Laurentffbc80f2015-03-18 18:30:19 -07005516 float volumeDb = computeVolume(stream, index, device);
HW Leeda7581e2018-05-22 18:31:34 +08005517 if (outputDesc->isFixedVolume(device) ||
5518 // Force VoIP volume to max for bluetooth SCO
5519 ((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
5520 (device & AUDIO_DEVICE_OUT_ALL_SCO) != 0)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005521 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005522 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005523
Eric Laurentffbc80f2015-03-18 18:30:19 -07005524 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005525
Eric Laurent3b73df72014-03-11 09:06:29 -07005526 if (stream == AUDIO_STREAM_VOICE_CALL ||
5527 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005528 float voiceVolume;
5529 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005530 if (stream == AUDIO_STREAM_VOICE_CALL) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005531 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005532 } else {
5533 voiceVolume = 1.0;
5534 }
5535
Eric Laurent18fba842016-03-31 14:41:26 -07005536 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005537 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5538 mLastVoiceVolume = voiceVolume;
5539 }
5540 }
5541
5542 return NO_ERROR;
5543}
5544
Eric Laurentc75307b2015-03-17 15:29:32 -07005545void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5546 audio_devices_t device,
5547 int delayMs,
5548 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005549{
Eric Laurentc75307b2015-03-17 15:29:32 -07005550 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005551
Eric Laurent794fde22016-03-11 09:50:45 -08005552 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005553 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005554 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005555 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005556 device,
5557 delayMs,
5558 force);
5559 }
5560}
5561
Eric Laurente0720872014-03-11 09:30:41 -07005562void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005563 bool on,
5564 const sp<AudioOutputDescriptor>& outputDesc,
5565 int delayMs,
5566 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005567{
Eric Laurent72249d52015-06-08 11:12:15 -07005568 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5569 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005570 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005571 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005572 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005573 }
5574 }
5575}
5576
Eric Laurente0720872014-03-11 09:30:41 -07005577void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005578 bool on,
5579 const sp<AudioOutputDescriptor>& outputDesc,
5580 int delayMs,
5581 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005582{
Eric Laurente552edb2014-03-10 17:42:56 -07005583 if (device == AUDIO_DEVICE_NONE) {
5584 device = outputDesc->device();
5585 }
5586
Eric Laurentc75307b2015-03-17 15:29:32 -07005587 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5588 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005589
5590 if (on) {
5591 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005592 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005593 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005594 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005595 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005596 }
5597 }
5598 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5599 outputDesc->mMuteCount[stream]++;
5600 } else {
5601 if (outputDesc->mMuteCount[stream] == 0) {
5602 ALOGV("setStreamMute() unmuting non muted stream!");
5603 return;
5604 }
5605 if (--outputDesc->mMuteCount[stream] == 0) {
5606 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005607 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005608 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005609 device,
5610 delayMs);
5611 }
5612 }
5613}
5614
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005615audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5616{
5617 // flags to stream type mapping
5618 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5619 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5620 }
5621 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5622 return AUDIO_STREAM_BLUETOOTH_SCO;
5623 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005624 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5625 return AUDIO_STREAM_TTS;
5626 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005627
5628 // usage to stream type mapping
5629 switch (attr->usage) {
5630 case AUDIO_USAGE_MEDIA:
5631 case AUDIO_USAGE_GAME:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005632 case AUDIO_USAGE_ASSISTANT:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005633 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5634 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005635 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5636 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005637 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5638 return AUDIO_STREAM_SYSTEM;
5639 case AUDIO_USAGE_VOICE_COMMUNICATION:
5640 return AUDIO_STREAM_VOICE_CALL;
5641
5642 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5643 return AUDIO_STREAM_DTMF;
5644
5645 case AUDIO_USAGE_ALARM:
5646 return AUDIO_STREAM_ALARM;
5647 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5648 return AUDIO_STREAM_RING;
5649
5650 case AUDIO_USAGE_NOTIFICATION:
5651 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5652 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5653 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5654 case AUDIO_USAGE_NOTIFICATION_EVENT:
5655 return AUDIO_STREAM_NOTIFICATION;
5656
5657 case AUDIO_USAGE_UNKNOWN:
5658 default:
5659 return AUDIO_STREAM_MUSIC;
5660 }
5661}
Eric Laurente83b55d2014-11-14 10:06:21 -08005662
François Gaffie53615e22015-03-19 09:24:12 +01005663bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5664{
Eric Laurente83b55d2014-11-14 10:06:21 -08005665 // has flags that map to a strategy?
5666 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5667 return true;
5668 }
5669
5670 // has known usage?
5671 switch (paa->usage) {
5672 case AUDIO_USAGE_UNKNOWN:
5673 case AUDIO_USAGE_MEDIA:
5674 case AUDIO_USAGE_VOICE_COMMUNICATION:
5675 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5676 case AUDIO_USAGE_ALARM:
5677 case AUDIO_USAGE_NOTIFICATION:
5678 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5679 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5680 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5681 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5682 case AUDIO_USAGE_NOTIFICATION_EVENT:
5683 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5684 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5685 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5686 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005687 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005688 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005689 break;
5690 default:
5691 return false;
5692 }
5693 return true;
5694}
5695
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005696bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005697 routing_strategy strategy, uint32_t inPastMs,
5698 nsecs_t sysTime) const
5699{
5700 if ((sysTime == 0) && (inPastMs != 0)) {
5701 sysTime = systemTime();
5702 }
Eric Laurent794fde22016-03-11 09:50:45 -08005703 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005704 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5705 (NUM_STRATEGIES == strategy)) &&
5706 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5707 return true;
5708 }
5709 }
5710 return false;
5711}
5712
Eric Laurent484e9272018-06-07 17:29:23 -07005713bool AudioPolicyManager::isStrategyActiveOnSameModule(const sp<AudioOutputDescriptor>& outputDesc,
5714 routing_strategy strategy, uint32_t inPastMs,
5715 nsecs_t sysTime) const
5716{
5717 for (size_t i = 0; i < mOutputs.size(); i++) {
5718 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5719 if (outputDesc->sharesHwModuleWith(desc)
5720 && isStrategyActive(desc, strategy, inPastMs, sysTime)) {
5721 return true;
5722 }
5723 }
5724 return false;
5725}
5726
François Gaffie2110e042015-03-24 08:41:51 +01005727audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5728{
5729 return mEngine->getForceUse(usage);
5730}
5731
5732bool AudioPolicyManager::isInCall()
5733{
5734 return isStateInCall(mEngine->getPhoneState());
5735}
5736
5737bool AudioPolicyManager::isStateInCall(int state)
5738{
5739 return is_state_in_call(state);
5740}
5741
Eric Laurentd60560a2015-04-10 11:31:20 -07005742void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5743{
5744 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5745 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
5746 if (sourceDesc->mDevice->equals(deviceDesc)) {
5747 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle());
5748 stopAudioSource(sourceDesc->getHandle());
5749 }
5750 }
5751
5752 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5753 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5754 bool release = false;
5755 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5756 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5757 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5758 source->ext.device.type == deviceDesc->type()) {
5759 release = true;
5760 }
5761 }
5762 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5763 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5764 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5765 sink->ext.device.type == deviceDesc->type()) {
5766 release = true;
5767 }
5768 }
5769 if (release) {
5770 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5771 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5772 }
5773 }
5774}
5775
Phil Burk09bc4612016-02-24 15:58:15 -08005776// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005777void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5778 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005779 // TODO Set this based on Config properties.
5780 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005781
5782 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5783 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005784 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005785
jiabin81772902018-04-02 17:52:27 -07005786 // If MANUAL, keep the supported surround sound formats as current enabled ones.
5787 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
5788 formats.clear();
5789 for (auto it = mSurroundFormats.begin(); it != mSurroundFormats.end(); it++) {
5790 formats.add(*it);
Phil Burk09bc4612016-02-24 15:58:15 -08005791 }
jiabin81772902018-04-02 17:52:27 -07005792 // Always enable IEC61937 when in MANUAL mode.
5793 formats.add(AUDIO_FORMAT_IEC61937);
5794 } else { // NEVER, AUTO or ALWAYS
5795 // Analyze original support for various formats.
5796 bool supportsAC3 = false;
5797 bool supportsOtherSurround = false;
5798 bool supportsIEC61937 = false;
5799 mSurroundFormats.clear();
5800 for (ssize_t formatIndex = 0; formatIndex < (ssize_t)formats.size(); formatIndex++) {
5801 audio_format_t format = formats[formatIndex];
5802 switch (format) {
5803 case AUDIO_FORMAT_AC3:
5804 supportsAC3 = true;
5805 break;
5806 case AUDIO_FORMAT_E_AC3:
5807 case AUDIO_FORMAT_DTS:
5808 case AUDIO_FORMAT_DTS_HD:
5809 // If ALWAYS, remove all other surround formats here
5810 // since we will add them later.
5811 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5812 formats.removeAt(formatIndex);
5813 formatIndex--;
5814 }
5815 supportsOtherSurround = true;
5816 break;
5817 case AUDIO_FORMAT_IEC61937:
5818 supportsIEC61937 = true;
5819 break;
5820 default:
5821 break;
5822 }
5823 }
Phil Burk09bc4612016-02-24 15:58:15 -08005824
jiabin81772902018-04-02 17:52:27 -07005825 // Modify formats based on surround preferences.
5826 // If NEVER, remove support for surround formats.
5827 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5828 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5829 // Remove surround sound related formats.
5830 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5831 audio_format_t format = formats[formatIndex];
5832 switch(format) {
5833 case AUDIO_FORMAT_AC3:
5834 case AUDIO_FORMAT_E_AC3:
5835 case AUDIO_FORMAT_DTS:
5836 case AUDIO_FORMAT_DTS_HD:
5837 case AUDIO_FORMAT_IEC61937:
5838 formats.removeAt(formatIndex);
5839 break;
5840 default:
5841 formatIndex++; // keep it
5842 break;
5843 }
5844 }
5845 supportsAC3 = false;
5846 supportsOtherSurround = false;
5847 supportsIEC61937 = false;
5848 }
5849 } else { // AUTO or ALWAYS
5850 // Most TVs support AC3 even if they do not report it in the EDID.
5851 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
5852 && !supportsAC3) {
5853 formats.add(AUDIO_FORMAT_AC3);
5854 supportsAC3 = true;
5855 }
5856
5857 // If ALWAYS, add support for raw surround formats if all are missing.
5858 // This assumes that if any of these formats are reported by the HAL
5859 // then the report is valid and should not be modified.
5860 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5861 formats.add(AUDIO_FORMAT_E_AC3);
5862 formats.add(AUDIO_FORMAT_DTS);
5863 formats.add(AUDIO_FORMAT_DTS_HD);
5864 supportsOtherSurround = true;
5865 }
5866
5867 // Add support for IEC61937 if any raw surround supported.
5868 // The HAL could do this but add it here, just in case.
5869 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
5870 formats.add(AUDIO_FORMAT_IEC61937);
5871 supportsIEC61937 = true;
5872 }
5873
5874 // Add reported surround sound formats to enabled surround formats.
5875 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
Phil Burk07ac1142016-03-25 13:39:29 -07005876 audio_format_t format = formats[formatIndex];
5877 switch(format) {
5878 case AUDIO_FORMAT_AC3:
5879 case AUDIO_FORMAT_E_AC3:
5880 case AUDIO_FORMAT_DTS:
5881 case AUDIO_FORMAT_DTS_HD:
jiabin81772902018-04-02 17:52:27 -07005882 case AUDIO_FORMAT_AAC_LC:
5883 case AUDIO_FORMAT_DOLBY_TRUEHD:
5884 case AUDIO_FORMAT_E_AC3_JOC:
5885 mSurroundFormats.insert(format);
Phil Burk07ac1142016-03-25 13:39:29 -07005886 default:
Phil Burk07ac1142016-03-25 13:39:29 -07005887 break;
5888 }
Phil Burk09bc4612016-02-24 15:58:15 -08005889 }
Phil Burk07ac1142016-03-25 13:39:29 -07005890 }
Phil Burk09bc4612016-02-24 15:58:15 -08005891 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005892}
5893
5894// Modify the list of channel masks supported.
5895void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
5896 ChannelsVector &channelMasks = *channelMasksPtr;
5897 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5898 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5899
5900 // If NEVER, then remove support for channelMasks > stereo.
5901 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5902 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5903 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5904 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5905 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5906 channelMasks.removeAt(maskIndex);
5907 } else {
5908 maskIndex++;
5909 }
5910 }
jiabin81772902018-04-02 17:52:27 -07005911 // If ALWAYS or MANUAL, then make sure we at least support 5.1
5912 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
5913 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005914 bool supports5dot1 = false;
5915 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005916 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005917 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5918 supports5dot1 = true;
5919 break;
5920 }
5921 }
5922 // If not then add 5.1 support.
5923 if (!supports5dot1) {
5924 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
5925 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
5926 }
Phil Burk09bc4612016-02-24 15:58:15 -08005927 }
5928}
5929
Phil Burk00eeb322016-03-31 12:41:00 -07005930void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
5931 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005932 AudioProfileVector &profiles)
5933{
5934 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07005935
François Gaffie112b0af2015-11-19 16:13:25 +01005936 // Format MUST be checked first to update the list of AudioProfile
5937 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005938 reply = mpClientInterface->getParameters(
5939 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07005940 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005941 AudioParameter repliedParameters(reply);
5942 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005943 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005944 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5945 return;
5946 }
Phil Burk09bc4612016-02-24 15:58:15 -08005947 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07005948 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005949 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005950 }
Phil Burk09bc4612016-02-24 15:58:15 -08005951 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005952 }
François Gaffie112b0af2015-11-19 16:13:25 +01005953
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005954 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08005955 ChannelsVector channelMasks;
5956 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005957 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07005958 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01005959
5960 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005961 reply = mpClientInterface->getParameters(
5962 ioHandle,
5963 requestedParameters.toString() + ";" +
5964 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01005965 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005966 AudioParameter repliedParameters(reply);
5967 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005968 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005969 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005970 }
5971 }
5972 if (profiles.hasDynamicChannelsFor(format)) {
5973 reply = mpClientInterface->getParameters(ioHandle,
5974 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07005975 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01005976 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005977 AudioParameter repliedParameters(reply);
5978 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005979 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005980 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07005981 if (device == AUDIO_DEVICE_OUT_HDMI) {
5982 filterSurroundChannelMasks(&channelMasks);
5983 }
François Gaffie112b0af2015-11-19 16:13:25 +01005984 }
5985 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08005986 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01005987 }
5988}
Eric Laurentd60560a2015-04-10 11:31:20 -07005989
Mikhail Naganovdc769682018-05-04 15:34:08 -07005990status_t AudioPolicyManager::installPatch(const char *caller,
5991 audio_patch_handle_t *patchHandle,
5992 AudioIODescriptorInterface *ioDescriptor,
5993 const struct audio_patch *patch,
5994 int delayMs)
5995{
5996 ssize_t index = mAudioPatches.indexOfKey(
5997 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
5998 *patchHandle : ioDescriptor->getPatchHandle());
5999 sp<AudioPatch> patchDesc;
6000 status_t status = installPatch(
6001 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6002 if (status == NO_ERROR) {
6003 ioDescriptor->setPatchHandle(patchDesc->mHandle);
6004 }
6005 return status;
6006}
6007
6008status_t AudioPolicyManager::installPatch(const char *caller,
6009 ssize_t index,
6010 audio_patch_handle_t *patchHandle,
6011 const struct audio_patch *patch,
6012 int delayMs,
6013 uid_t uid,
6014 sp<AudioPatch> *patchDescPtr)
6015{
6016 sp<AudioPatch> patchDesc;
6017 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6018 if (index >= 0) {
6019 patchDesc = mAudioPatches.valueAt(index);
6020 afPatchHandle = patchDesc->mAfPatchHandle;
6021 }
6022
6023 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6024 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6025 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6026 if (status == NO_ERROR) {
6027 if (index < 0) {
6028 patchDesc = new AudioPatch(patch, uid);
6029 addAudioPatch(patchDesc->mHandle, patchDesc);
6030 } else {
6031 patchDesc->mPatch = *patch;
6032 }
6033 patchDesc->mAfPatchHandle = afPatchHandle;
6034 if (patchHandle) {
6035 *patchHandle = patchDesc->mHandle;
6036 }
6037 nextAudioPortGeneration();
6038 mpClientInterface->onAudioPatchListUpdate();
6039 }
6040 if (patchDescPtr) *patchDescPtr = patchDesc;
6041 return status;
6042}
6043
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006044} // namespace android