blob: 9b10d687420bdc35beef840fbca1270191924795 [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
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700804 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
805 " session %d selectedDeviceId %d",
806 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700807 session, *selectedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700808
Scott Randolph7b1fd232018-06-18 15:33:03 -0700809 // TODO: check for existing client for this port ID
810 if (*portId == AUDIO_PORT_HANDLE_NONE) {
811 *portId = AudioPort::getNextUniqueId();
812 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700813
Scott Randolph7b1fd232018-06-18 15:33:03 -0700814 // First check for explicit routing (eg. setPreferredDevice)
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700815 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -0700816 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800817 deviceDesc = mAvailableOutputDevices.getDeviceFromId(*selectedDeviceId);
Scott Randolph7b1fd232018-06-18 15:33:03 -0700818 } else {
819 // If no explict route, is there a matching dynamic policy that applies?
820 sp<SwAudioOutputDescriptor> desc;
821 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
822 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
823 if (!audio_has_proportional_frames(config->format)) {
824 return BAD_VALUE;
825 }
826 *stream = streamTypefromAttributesInt(&attributes);
827 *output = desc->mIoHandle;
828 ALOGV("getOutputForAttr() returns output %d", *output);
829 return NO_ERROR;
830 }
831
832 // Virtual sources must always be dynamicaly or explicitly routed
833 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
834 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
835 return BAD_VALUE;
836 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700837 }
Scott Randolph7b1fd232018-06-18 15:33:03 -0700838
839 // Virtual sources must always be dynamicaly or explicitly routed
840 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
841 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
842 return BAD_VALUE;
843 }
844
845 *stream = streamTypefromAttributesInt(&attributes);
846
847 // TODO: Should this happen only if an explicit route is active?
848 // the previous code structure meant that this would always happen which
849 // would appear to result in adding a null deviceDesc when not using an
850 // explicit route. Is that the intended and necessary behavior?
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700851 mOutputRoutes.addRoute(session, *stream, SessionRoute::SOURCE_TYPE_NA, deviceDesc, uid);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700852
Eric Laurente83b55d2014-11-14 10:06:21 -0800853 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700854 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700855
Eric Laurente83b55d2014-11-14 10:06:21 -0800856 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200857 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -0700858 }
859
Glenn Kasten49f36ba2017-12-06 13:02:02 -0800860 ALOGV("getOutputForAttr() device 0x%x, sampling rate %d, format %#x, channel mask %#x, "
861 "flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +0200862 device, config->sample_rate, config->format, config->channel_mask, *flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700863
Andy Hungc88b0642018-04-27 15:42:35 -0700864 *output = getOutputForDevice(device, session, *stream, config, flags);
Eric Laurente83b55d2014-11-14 10:06:21 -0800865 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700866 mOutputRoutes.removeRoute(session);
Eric Laurente83b55d2014-11-14 10:06:21 -0800867 return INVALID_OPERATION;
868 }
Paul McLeanaa981192015-03-21 09:55:15 -0700869
Mikhail Naganov708e0382018-05-30 09:53:04 -0700870 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -0700871 *selectedDeviceId = outputDevices.size() > 0 ? outputDevices.itemAt(0)->getId()
872 : AUDIO_PORT_HANDLE_NONE;
873
874 ALOGV(" getOutputForAttr() returns output %d selectedDeviceId %d", *output, *selectedDeviceId);
875
Eric Laurente83b55d2014-11-14 10:06:21 -0800876 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700877}
878
879audio_io_handle_t AudioPolicyManager::getOutputForDevice(
880 audio_devices_t device,
Kevin Rocard169753c2017-03-06 14:18:23 -0800881 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700882 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -0800883 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200884 audio_output_flags_t *flags)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700885{
Andy Hungc88b0642018-04-27 15:42:35 -0700886 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700887 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700888
Eric Laurente552edb2014-03-10 17:42:56 -0700889 // open a direct output if required by specified parameters
890 //force direct flag if offload flag is set: offloading implies a direct output stream
891 // and all common behaviors are driven by checking only the direct flag
892 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +0200893 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
894 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700895 }
Nadav Bar766fb022018-01-07 12:18:03 +0200896 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
897 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -0700898 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800899 // only allow deep buffering for music stream type
900 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +0200901 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700902 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +0200903 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700904 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
905 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +0200906 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800907 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700908 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +0200909 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700910 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Eric Laurentfe231122017-11-17 17:48:06 -0800911 audio_is_linear_pcm(config->format)) {
Nadav Bar766fb022018-01-07 12:18:03 +0200912 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700913 AUDIO_OUTPUT_FLAG_DIRECT);
914 ALOGV("Set VoIP and Direct output flags for PCM format");
Nadav Bar766fb022018-01-07 12:18:03 +0200915 } else if (device == AUDIO_DEVICE_OUT_TELEPHONY_TX &&
916 stream == AUDIO_STREAM_MUSIC &&
917 audio_is_linear_pcm(config->format) &&
918 isInCall()) {
919 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700920 }
Eric Laurente552edb2014-03-10 17:42:56 -0700921
Nadav Bar766fb022018-01-07 12:18:03 +0200922
Eric Laurentb732cf52014-09-24 19:08:21 -0700923 sp<IOProfile> profile;
924
925 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700926 // and not explicitly requested
Nadav Bar766fb022018-01-07 12:18:03 +0200927 if (((*flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Eric Laurentfe231122017-11-17 17:48:06 -0800928 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
929 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
Eric Laurentb732cf52014-09-24 19:08:21 -0700930 goto non_direct_output;
931 }
932
Andy Hung2ddee192015-12-18 17:34:44 -0800933 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
934 // This prevents creating an offloaded track and tearing it down immediately after start
935 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700936 // FIXME: We should check the audio session here but we do not have it in this context.
937 // This may prevent offloading in rare situations where effects are left active by apps
938 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700939
Nadav Bar766fb022018-01-07 12:18:03 +0200940 if (((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800941 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700942 profile = getProfileForDirectOutput(device,
Eric Laurentfe231122017-11-17 17:48:06 -0800943 config->sample_rate,
944 config->format,
945 config->channel_mask,
Nadav Bar766fb022018-01-07 12:18:03 +0200946 (audio_output_flags_t)*flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700947 }
948
Eric Laurent1c333e22014-05-20 10:48:17 -0700949 if (profile != 0) {
Andy Hungc88b0642018-04-27 15:42:35 -0700950 // exclusive outputs for MMAP and Offload are enforced by different session ids.
951 for (size_t i = 0; i < mOutputs.size(); i++) {
952 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
953 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
954 // reuse direct output if currently open by the same client
955 // and configured with same parameters
956 if ((config->sample_rate == desc->mSamplingRate) &&
Andy Hung5659ed52018-04-30 10:31:26 -0700957 (config->format == desc->mFormat) &&
Andy Hungc88b0642018-04-27 15:42:35 -0700958 (config->channel_mask == desc->mChannelMask) &&
959 (session == desc->mDirectClientSession)) {
960 desc->mDirectOpenCount++;
961 ALOGI("getOutputForDevice() reusing direct output %d for session %d",
962 mOutputs.keyAt(i), session);
963 return mOutputs.keyAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700964 }
965 }
966 }
Eric Laurent3974e3b2017-12-07 17:58:43 -0800967
968 if (!profile->canOpenNewIo()) {
969 goto non_direct_output;
Eric Laurente552edb2014-03-10 17:42:56 -0700970 }
Eric Laurent861a6282015-05-18 15:40:16 -0700971
Eric Laurent3974e3b2017-12-07 17:58:43 -0800972 sp<SwAudioOutputDescriptor> outputDesc =
973 new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurent53b810e2017-12-10 17:25:10 -0800974
Mikhail Naganov708e0382018-05-30 09:53:04 -0700975 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -0800976 String8 address = outputDevices.size() > 0 ? outputDevices.itemAt(0)->mAddress
977 : String8("");
978
Nadav Bar766fb022018-01-07 12:18:03 +0200979 status = outputDesc->open(config, device, address, stream, *flags, &output);
Eric Laurente552edb2014-03-10 17:42:56 -0700980
981 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -0700982 if (status != NO_ERROR ||
Eric Laurentfe231122017-11-17 17:48:06 -0800983 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
Andy Hung5659ed52018-04-30 10:31:26 -0700984 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->mFormat) ||
Eric Laurentfe231122017-11-17 17:48:06 -0800985 (config->channel_mask != 0 && config->channel_mask != outputDesc->mChannelMask)) {
986 ALOGV("getOutputForDevice() failed opening direct output: output %d sample rate %d %d,"
987 "format %d %d, channel mask %04x %04x", output, config->sample_rate,
988 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
989 config->channel_mask, outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700990 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -0800991 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -0700992 }
Eric Laurenta82797f2015-01-30 11:49:43 -0800993 // fall back to mixer output if possible when the direct output could not be open
Eric Laurentfe231122017-11-17 17:48:06 -0800994 if (audio_is_linear_pcm(config->format) &&
995 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -0800996 goto non_direct_output;
997 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700998 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -0700999 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001000 outputDesc->mRefCount[stream] = 0;
1001 outputDesc->mStopTime[stream] = 0;
1002 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -08001003 outputDesc->mDirectClientSession = session;
1004
Eric Laurente552edb2014-03-10 17:42:56 -07001005 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001006 mPreviousOutputs = mOutputs;
Eric Laurentf4e63452017-11-06 19:31:46 +00001007 ALOGV("getOutputForDevice() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001008 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001009 return output;
1010 }
1011
Eric Laurentb732cf52014-09-24 19:08:21 -07001012non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001013
1014 // A request for HW A/V sync cannot fallback to a mixed output because time
1015 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001016 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001017 return AUDIO_IO_HANDLE_NONE;
1018 }
1019
Eric Laurente552edb2014-03-10 17:42:56 -07001020 // ignoring channel mask due to downmix capability in mixer
1021
1022 // open a non direct output
1023
1024 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001025 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001026 // get which output is suitable for the specified stream. The actual
1027 // routing change will happen when startOutput() will be called
1028 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1029
Eric Laurent8838a382014-09-08 16:44:28 -07001030 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001031 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1032 output = selectOutput(outputs, *flags, config->format);
Eric Laurente552edb2014-03-10 17:42:56 -07001033 }
Eric Laurentf4e63452017-11-06 19:31:46 +00001034 ALOGW_IF((output == 0), "getOutputForDevice() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001035 "sampling rate %d, format %#x, channels %#x, flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +02001036 stream, config->sample_rate, config->format, config->channel_mask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001037
Eric Laurente552edb2014-03-10 17:42:56 -07001038 return output;
1039}
1040
Eric Laurente0720872014-03-11 09:30:41 -07001041audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001042 audio_output_flags_t flags,
1043 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001044{
1045 // select one output among several that provide a path to a particular device or set of
1046 // devices (the list was previously build by getOutputsForDevice()).
1047 // The priority is as follows:
1048 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001049 // 2: the output with the bit depth the closest to the requested one
1050 // 3: the primary output
1051 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001052
1053 if (outputs.size() == 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001054 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001055 }
1056 if (outputs.size() == 1) {
1057 return outputs[0];
1058 }
1059
1060 int maxCommonFlags = 0;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001061 audio_io_handle_t outputForFlags = AUDIO_IO_HANDLE_NONE;
1062 audio_io_handle_t outputForPrimary = AUDIO_IO_HANDLE_NONE;
1063 audio_io_handle_t outputForFormat = AUDIO_IO_HANDLE_NONE;
Eric Laurente6930022016-02-11 10:20:40 -08001064 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1065 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001066
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001067 for (audio_io_handle_t output : outputs) {
1068 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001069 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001070 // if a valid format is specified, skip output if not compatible
1071 if (format != AUDIO_FORMAT_INVALID) {
1072 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Andy Hung5659ed52018-04-30 10:31:26 -07001073 if (format != outputDesc->mFormat) {
Eric Laurent8838a382014-09-08 16:44:28 -07001074 continue;
1075 }
1076 } else if (!audio_is_linear_pcm(format)) {
1077 continue;
1078 }
Eric Laurente6930022016-02-11 10:20:40 -08001079 if (AudioPort::isBetterFormatMatch(
1080 outputDesc->mFormat, bestFormat, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001081 outputForFormat = output;
Eric Laurente6930022016-02-11 10:20:40 -08001082 bestFormat = outputDesc->mFormat;
1083 }
Eric Laurent8838a382014-09-08 16:44:28 -07001084 }
1085
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001086 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001087 if (commonFlags >= maxCommonFlags) {
1088 if (commonFlags == maxCommonFlags) {
Andy Hungc9901522017-11-10 20:07:54 -08001089 if (format != AUDIO_FORMAT_INVALID
1090 && AudioPort::isBetterFormatMatch(
1091 outputDesc->mFormat, bestFormatForFlags, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001092 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001093 bestFormatForFlags = outputDesc->mFormat;
1094 }
1095 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001096 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001097 maxCommonFlags = commonFlags;
1098 bestFormatForFlags = outputDesc->mFormat;
1099 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001100 ALOGV("selectOutput() commonFlags for output %d, %04x", output, commonFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001101 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001102 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001103 outputForPrimary = output;
Eric Laurente552edb2014-03-10 17:42:56 -07001104 }
1105 }
1106 }
1107
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001108 if (outputForFlags != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001109 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001110 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001111 if (outputForFormat != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001112 return outputForFormat;
1113 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001114 if (outputForPrimary != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001115 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001116 }
1117
1118 return outputs[0];
1119}
1120
Eric Laurente0720872014-03-11 09:30:41 -07001121status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001122 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001123 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001124{
Paul McLeanaa981192015-03-21 09:55:15 -07001125 ALOGV("startOutput() output %d, stream %d, session %d",
1126 output, stream, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001127 ssize_t index = mOutputs.indexOfKey(output);
1128 if (index < 0) {
1129 ALOGW("startOutput() unknown output %d", output);
1130 return BAD_VALUE;
1131 }
1132
Eric Laurentc75307b2015-03-17 15:29:32 -07001133 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1134
Eric Laurent733ce942017-12-07 12:18:25 -08001135 status_t status = outputDesc->start();
1136 if (status != NO_ERROR) {
1137 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001138 }
1139
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001140 // Routing?
1141 mOutputRoutes.incRouteActivity(session);
1142
Eric Laurentc75307b2015-03-17 15:29:32 -07001143 audio_devices_t newDevice;
Eric Laurentc40d9692016-04-13 19:14:13 -07001144 AudioMix *policyMix = NULL;
1145 const char *address = NULL;
Eric Laurentc75307b2015-03-17 15:29:32 -07001146 if (outputDesc->mPolicyMix != NULL) {
Eric Laurentc40d9692016-04-13 19:14:13 -07001147 policyMix = outputDesc->mPolicyMix;
1148 address = policyMix->mDeviceAddress.string();
1149 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1150 newDevice = policyMix->mDeviceType;
1151 } else {
1152 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1153 }
Eric Laurent2157f5b2018-04-25 18:33:02 -07001154 } else if (mOutputRoutes.getAndClearRouteChanged(session)) {
Eric Laurent493404d2015-04-21 15:07:36 -07001155 newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurentf3a5a602018-05-22 18:42:55 -07001156 if (newDevice != outputDesc->device()) {
1157 checkStrategyRoute(getStrategy(stream), output);
1158 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001159 } else {
1160 newDevice = AUDIO_DEVICE_NONE;
1161 }
1162
1163 uint32_t delayMs = 0;
1164
Eric Laurent733ce942017-12-07 12:18:25 -08001165 status = startSource(outputDesc, stream, newDevice, address, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001166
1167 if (status != NO_ERROR) {
1168 mOutputRoutes.decRouteActivity(session);
Eric Laurent733ce942017-12-07 12:18:25 -08001169 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001170 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001171 }
1172 // Automatically enable the remote submix input when output is started on a re routing mix
1173 // of type MIX_TYPE_RECORDERS
Eric Laurentc40d9692016-04-13 19:14:13 -07001174 if (audio_is_remote_submix_device(newDevice) && policyMix != NULL &&
1175 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001176 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1177 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Eric Laurentc40d9692016-04-13 19:14:13 -07001178 address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001179 "remote-submix");
1180 }
1181
1182 if (delayMs != 0) {
1183 usleep(delayMs * 1000);
1184 }
1185
1186 return status;
1187}
1188
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001189status_t AudioPolicyManager::startSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurentc75307b2015-03-17 15:29:32 -07001190 audio_stream_type_t stream,
1191 audio_devices_t device,
Eric Laurentc40d9692016-04-13 19:14:13 -07001192 const char *address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001193 uint32_t *delayMs)
1194{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001195 // cannot start playback of STREAM_TTS if any other output is being used
1196 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001197
1198 *delayMs = 0;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001199 if (stream == AUDIO_STREAM_TTS) {
1200 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001201 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001202 return INVALID_OPERATION;
1203 } else {
1204 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1205 }
1206 } else {
1207 // some playback other than beacon starts
1208 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1209 }
1210
Eric Laurent77305a62016-07-25 16:39:22 -07001211 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001212 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001213 bool force = !outputDesc->isActive() &&
1214 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001215
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001216 // requiresMuteCheck is false when we can bypass mute strategy.
1217 // It covers a common case when there is no materially active audio
1218 // and muting would result in unnecessary delay and dropped audio.
1219 const uint32_t outputLatencyMs = outputDesc->latency();
1220 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1221
Eric Laurente552edb2014-03-10 17:42:56 -07001222 // increment usage count for this stream on the requested output:
1223 // NOTE that the usage count is the same for duplicated output and hardware output which is
1224 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1225 outputDesc->changeRefCount(stream, 1);
1226
Eric Laurent36829f92017-04-07 19:04:42 -07001227 if (stream == AUDIO_STREAM_MUSIC) {
1228 selectOutputForMusicEffects();
1229 }
1230
Eric Laurent493404d2015-04-21 15:07:36 -07001231 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001232 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001233 if (device == AUDIO_DEVICE_NONE) {
1234 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001235 }
Eric Laurent36829f92017-04-07 19:04:42 -07001236
Eric Laurente552edb2014-03-10 17:42:56 -07001237 routing_strategy strategy = getStrategy(stream);
1238 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001239 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1240 (beaconMuteLatency > 0);
1241 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001242 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001243 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001244 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001245 // An output has a shared device if
1246 // - managed by the same hw module
1247 // - supports the currently selected device
1248 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
1249 && (desc->supportedDevices() & device) != AUDIO_DEVICE_NONE;
1250
Eric Laurent77305a62016-07-25 16:39:22 -07001251 // force a device change if any other output is:
1252 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001253 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001254 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001255 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001256 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001257 // change the device currently selected by the other output.
1258 if (sharedDevice &&
Eric Laurent77305a62016-07-25 16:39:22 -07001259 desc->device() != device &&
Eric Laurent77305a62016-07-25 16:39:22 -07001260 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001261 force = true;
1262 }
1263 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001264 // a notification so that audio focus effect can propagate, or that a mute/unmute
1265 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001266 const uint32_t latencyMs = desc->latency();
1267 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1268
1269 if (shouldWait && isActive && (waitMs < latencyMs)) {
1270 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001271 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001272
1273 // Require mute check if another output is on a shared device
1274 // and currently active to have proper drain and avoid pops.
1275 // Note restoring AudioTracks onto this output needs to invoke
1276 // a volume ramp if there is no mute.
1277 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001278 }
1279 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001280
1281 const uint32_t muteWaitMs =
1282 setOutputDevice(outputDesc, device, force, 0, NULL, address, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001283
Eric Laurente552edb2014-03-10 17:42:56 -07001284 // apply volume rules for current stream and device if necessary
1285 checkAndSetVolume(stream,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001286 mVolumeCurves->getVolumeIndex(stream, outputDesc->device()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001287 outputDesc,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001288 outputDesc->device());
Eric Laurente552edb2014-03-10 17:42:56 -07001289
1290 // update the outputs if starting an output with a stream that can affect notification
1291 // routing
1292 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001293
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001294 // force reevaluating accessibility routing when ringtone or alarm starts
1295 if (strategy == STRATEGY_SONIFICATION) {
1296 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1297 }
Eric Laurentdc462862016-07-19 12:29:53 -07001298
1299 if (waitMs > muteWaitMs) {
1300 *delayMs = waitMs - muteWaitMs;
1301 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001302
1303 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1304 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1305 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1306 // change occurs after the MixerThread starts and causes a stream volume
1307 // glitch.
1308 //
1309 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001310 }
Eric Laurentdc462862016-07-19 12:29:53 -07001311
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001312 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1313 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1314 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1315 }
1316
Tomoharu Kasaharaa81f0982018-01-18 20:55:02 +09001317 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1318 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1319 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1320 }
1321
Eric Laurente552edb2014-03-10 17:42:56 -07001322 return NO_ERROR;
1323}
1324
1325
Eric Laurente0720872014-03-11 09:30:41 -07001326status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001327 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001328 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001329{
1330 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1331 ssize_t index = mOutputs.indexOfKey(output);
1332 if (index < 0) {
1333 ALOGW("stopOutput() unknown output %d", output);
1334 return BAD_VALUE;
1335 }
1336
Eric Laurentc75307b2015-03-17 15:29:32 -07001337 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001338
Eric Laurentc75307b2015-03-17 15:29:32 -07001339 if (outputDesc->mRefCount[stream] == 1) {
1340 // Automatically disable the remote submix input when output is stopped on a
1341 // re routing mix of type MIX_TYPE_RECORDERS
1342 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1343 outputDesc->mPolicyMix != NULL &&
1344 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1345 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1346 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001347 outputDesc->mPolicyMix->mDeviceAddress,
Eric Laurentc75307b2015-03-17 15:29:32 -07001348 "remote-submix");
1349 }
1350 }
1351
1352 // Routing?
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001353 bool forceDeviceUpdate = false;
Eric Laurentc75307b2015-03-17 15:29:32 -07001354 if (outputDesc->mRefCount[stream] > 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001355 int activityCount = mOutputRoutes.decRouteActivity(session);
1356 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1357
1358 if (forceDeviceUpdate) {
1359 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1360 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001361 }
1362
Eric Laurent3974e3b2017-12-07 17:58:43 -08001363 status_t status = stopSource(outputDesc, stream, forceDeviceUpdate);
1364
Eric Laurent733ce942017-12-07 12:18:25 -08001365 if (status == NO_ERROR ) {
1366 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001367 }
1368 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001369}
1370
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001371status_t AudioPolicyManager::stopSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001372 audio_stream_type_t stream,
1373 bool forceDeviceUpdate)
Eric Laurentc75307b2015-03-17 15:29:32 -07001374{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001375 // always handle stream stop, check which stream type is stopping
1376 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1377
Eric Laurente552edb2014-03-10 17:42:56 -07001378 if (outputDesc->mRefCount[stream] > 0) {
1379 // decrement usage count of this stream on the output
1380 outputDesc->changeRefCount(stream, -1);
Paul McLeanaa981192015-03-21 09:55:15 -07001381
Eric Laurente552edb2014-03-10 17:42:56 -07001382 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001383 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001384 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001385 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001386 // delay the device switch by twice the latency because stopOutput() is executed when
1387 // the track stop() command is received and at that time the audio track buffer can
1388 // still contain data that needs to be drained. The latency only covers the audio HAL
1389 // and kernel buffers. Also the latency does not always include additional delay in the
1390 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001391 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001392
1393 // force restoring the device selection on other active outputs if it differs from the
1394 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001395 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001396 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001397 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001398 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001399 desc->isActive() &&
1400 outputDesc->sharesHwModuleWith(desc) &&
1401 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001402 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1403 bool force = desc->device() != newDevice2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001404
Eric Laurentc75307b2015-03-17 15:29:32 -07001405 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001406 newDevice2,
1407 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001408 delayMs);
1409 // re-apply device specific volume if not done by setOutputDevice()
1410 if (!force) {
1411 applyStreamVolumes(desc, newDevice2, delayMs);
1412 }
Eric Laurente552edb2014-03-10 17:42:56 -07001413 }
1414 }
1415 // update the outputs if stopping one with a stream that can affect notification routing
1416 handleNotificationRoutingForStream(stream);
1417 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001418
1419 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1420 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1421 setStrategyMute(STRATEGY_SONIFICATION, false, outputDesc);
1422 }
1423
Eric Laurent36829f92017-04-07 19:04:42 -07001424 if (stream == AUDIO_STREAM_MUSIC) {
1425 selectOutputForMusicEffects();
1426 }
Eric Laurente552edb2014-03-10 17:42:56 -07001427 return NO_ERROR;
1428 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001429 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001430 return INVALID_OPERATION;
1431 }
1432}
1433
Eric Laurente83b55d2014-11-14 10:06:21 -08001434void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001435 audio_stream_type_t stream __unused,
1436 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001437{
1438 ALOGV("releaseOutput() %d", output);
1439 ssize_t index = mOutputs.indexOfKey(output);
1440 if (index < 0) {
1441 ALOGW("releaseOutput() releasing unknown output %d", output);
1442 return;
1443 }
1444
Paul McLeanaa981192015-03-21 09:55:15 -07001445 // Routing
1446 mOutputRoutes.removeRoute(session);
1447
Eric Laurentc75307b2015-03-17 15:29:32 -07001448 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001449 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001450 if (desc->mDirectOpenCount <= 0) {
1451 ALOGW("releaseOutput() invalid open count %d for output %d",
1452 desc->mDirectOpenCount, output);
1453 return;
1454 }
1455 if (--desc->mDirectOpenCount == 0) {
1456 closeOutput(output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001457 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001458 }
1459 }
1460}
1461
1462
Eric Laurentcaf7f482014-11-25 17:50:47 -08001463status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1464 audio_io_handle_t *input,
1465 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001466 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001467 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001468 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001469 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001470 input_type_t *inputType,
1471 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001472{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001473 ALOGV("getInputForAttr() source %d, sampling rate %d, format %#x, channel mask %#x,"
Eric Laurentcaf7f482014-11-25 17:50:47 -08001474 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001475 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001476
Eric Laurentad2e7b92017-09-14 20:06:42 -07001477 status_t status = NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -08001478 // handle legacy remote submix case where the address was not always specified
1479 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001480 audio_source_t halInputSource;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001481 audio_source_t inputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001482 AudioMix *policyMix = NULL;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001483 DeviceVector inputDevices;
Eric Laurent20b9ef02016-12-05 11:03:16 -08001484
Eric Laurentfe231122017-11-17 17:48:06 -08001485 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1486 inputSource = AUDIO_SOURCE_MIC;
1487 }
1488
Paul McLean466dc8e2015-04-17 13:15:36 -06001489 // Explicit routing?
1490 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -07001491 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
jiabinc0c831a2018-01-29 17:55:15 -08001492 deviceDesc = mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001493 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001494 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
Paul McLean466dc8e2015-04-17 13:15:36 -06001495
Eric Laurentad2e7b92017-09-14 20:06:42 -07001496 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1497 // possible
1498 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1499 *input != AUDIO_IO_HANDLE_NONE) {
1500 ssize_t index = mInputs.indexOfKey(*input);
1501 if (index < 0) {
1502 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1503 status = BAD_VALUE;
1504 goto error;
1505 }
1506 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1507 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1508 if (audioSession == 0) {
1509 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1510 status = BAD_VALUE;
1511 goto error;
1512 }
1513 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1514 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001515 // corresponds to a new client and is only permitted from the same UID.
1516 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurentad2e7b92017-09-14 20:06:42 -07001517 if (audioSession->openCount() == 1) {
1518 audioSession->setUid(uid);
1519 } else if (audioSession->uid() != uid) {
Eric Laurent331679c2018-04-16 17:03:16 -07001520 if (!audioSession->isSilenced()) {
1521 ALOGW("getInputForAttr() bad uid %d for session %d uid %d",
1522 uid, session, audioSession->uid());
1523 status = INVALID_OPERATION;
1524 goto error;
1525 }
1526 audioSession->setUid(uid);
1527 audioSession->setSilenced(false);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001528 }
1529 audioSession->changeOpenCount(1);
1530 *inputType = API_INPUT_LEGACY;
1531 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1532 *portId = AudioPort::getNextUniqueId();
1533 }
Mikhail Naganov708e0382018-05-30 09:53:04 -07001534 inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(inputDesc->mDevice);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001535 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1536 : AUDIO_PORT_HANDLE_NONE;
1537 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
1538
1539 return NO_ERROR;
1540 }
1541
1542 *input = AUDIO_IO_HANDLE_NONE;
1543 *inputType = API_INPUT_INVALID;
1544
Eric Laurentad2e7b92017-09-14 20:06:42 -07001545 halInputSource = inputSource;
1546
1547 // TODO: check for existing client for this port ID
1548 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1549 *portId = AudioPort::getNextUniqueId();
1550 }
1551
1552 audio_devices_t device;
1553
Eric Laurentc447ded2015-01-06 08:47:05 -08001554 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001555 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001556 status = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
1557 if (status != NO_ERROR) {
1558 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001559 }
1560 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001561 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1562 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001563 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001564 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001565 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001566 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001567 status = BAD_VALUE;
1568 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001569 }
Eric Laurentc722f302014-12-10 11:21:49 -08001570 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001571 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001572 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1573 // there is an external policy, but this input is attached to a mix of recorders,
1574 // meaning it receives audio injected into the framework, so the recorder doesn't
1575 // know about it and is therefore considered "legacy"
1576 *inputType = API_INPUT_LEGACY;
1577 } else {
1578 // recording a mix of players defined by an external policy, we're rerouting for
1579 // an external policy
1580 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1581 }
Eric Laurentc722f302014-12-10 11:21:49 -08001582 } else if (audio_is_remote_submix_device(device)) {
1583 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001584 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001585 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1586 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001587 } else {
1588 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001589 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001590
Eric Laurent599c7582015-12-07 18:05:55 -08001591 }
1592
1593 *input = getInputForDevice(device, address, session, uid, inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001594 config, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001595 policyMix);
1596 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001597 status = INVALID_OPERATION;
1598 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001599 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001600
Mikhail Naganov708e0382018-05-30 09:53:04 -07001601 inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -07001602 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1603 : AUDIO_PORT_HANDLE_NONE;
1604
1605 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d",
1606 *input, *inputType, *selectedDeviceId);
1607
Eric Laurent599c7582015-12-07 18:05:55 -08001608 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001609
1610error:
1611 mInputRoutes.removeRoute(session);
1612 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001613}
1614
1615
1616audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1617 String8 address,
1618 audio_session_t session,
1619 uid_t uid,
1620 audio_source_t inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001621 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08001622 audio_input_flags_t flags,
1623 AudioMix *policyMix)
1624{
1625 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1626 audio_source_t halInputSource = inputSource;
1627 bool isSoundTrigger = false;
1628
1629 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1630 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1631 if (index >= 0) {
1632 input = mSoundTriggerSessions.valueFor(session);
1633 isSoundTrigger = true;
1634 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1635 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1636 } else {
1637 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001638 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001639 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08001640 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001641 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001642 }
1643
Andy Hungf129b032015-04-07 13:45:50 -07001644 // find a compatible input profile (not necessarily identical in parameters)
1645 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08001646 // sampling rate and flags may be updated by getInputProfile
1647 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
1648 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07001649 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08001650 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07001651 audio_input_flags_t profileFlags = flags;
1652 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07001653 profileFormat = config->format; // reset each time through loop, in case it is updated
Eric Laurent275e8e92014-11-30 15:14:47 -08001654 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001655 profileSamplingRate, profileFormat, profileChannelMask,
1656 profileFlags);
1657 if (profile != 0) {
1658 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001659 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1660 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001661 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1662 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1663 } else { // fail
Glenn Kastenfaa10a62017-05-25 15:52:05 -07001664 ALOGW("getInputForDevice() could not find profile for device 0x%X, "
Eric Laurentfe231122017-11-17 17:48:06 -08001665 "sampling rate %u, format %#x, channel mask 0x%X, flags %#x",
1666 device, config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001667 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001668 }
Eric Laurente552edb2014-03-10 17:42:56 -07001669 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001670 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08001671 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08001672 if (samplingRate == 0) {
1673 samplingRate = profileSamplingRate;
1674 }
Eric Laurente552edb2014-03-10 17:42:56 -07001675
Eric Laurent322b4d22015-04-03 15:57:54 -07001676 if (profile->getModuleHandle() == 0) {
1677 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001678 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001679 }
1680
Eric Laurent599c7582015-12-07 18:05:55 -08001681 sp<AudioSession> audioSession = new AudioSession(session,
Eric Laurentfe231122017-11-17 17:48:06 -08001682 inputSource,
1683 config->format,
1684 samplingRate,
1685 config->channel_mask,
1686 flags,
1687 uid,
1688 isSoundTrigger,
1689 policyMix, mpClientInterface);
Eric Laurent599c7582015-12-07 18:05:55 -08001690
Eric Laurent74708e72017-04-07 17:13:42 -07001691// FIXME: disable concurrent capture until UI is ready
1692#if 0
Eric Laurent599c7582015-12-07 18:05:55 -08001693 // reuse an open input if possible
Eric Laurent555530a2017-02-07 18:17:24 -08001694 sp<AudioInputDescriptor> reusedInputDesc;
Eric Laurent599c7582015-12-07 18:05:55 -08001695 for (size_t i = 0; i < mInputs.size(); i++) {
1696 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001697 // reuse input if:
1698 // - it shares the same profile
1699 // AND
1700 // - it is not a reroute submix input
1701 // AND
1702 // - it is: not used for sound trigger
1703 // OR
1704 // used for sound trigger and all clients use the same session ID
1705 //
1706 if ((profile == desc->mProfile) &&
1707 (isSoundTrigger == desc->isSoundTrigger()) &&
1708 !is_virtual_input_device(device)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001709
1710 sp<AudioSession> as = desc->getAudioSession(session);
1711 if (as != 0) {
1712 // do not allow unmatching properties on same session
1713 if (as->matches(audioSession)) {
1714 as->changeOpenCount(1);
1715 } else {
1716 ALOGW("getInputForDevice() record with different attributes"
1717 " exists for session %d", session);
Eric Laurent555530a2017-02-07 18:17:24 -08001718 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001719 }
Eric Laurentfb66dd92016-01-28 18:32:03 -08001720 } else if (isSoundTrigger) {
Eric Laurent555530a2017-02-07 18:17:24 -08001721 continue;
Eric Laurentfb66dd92016-01-28 18:32:03 -08001722 }
Eric Laurentbb948092017-01-23 18:33:30 -08001723
Eric Laurent555530a2017-02-07 18:17:24 -08001724 // Reuse the already opened input stream on this profile if:
1725 // - the new capture source is background OR
1726 // - the path requested configurations match OR
1727 // - the new source priority is less than the highest source priority on this input
1728 // If the input stream cannot be reused, close it before opening a new stream
1729 // on the same profile for the new client so that the requested path configuration
1730 // can be selected.
1731 if (!isConcurrentSource(inputSource) &&
Eric Laurentbb948092017-01-23 18:33:30 -08001732 ((desc->mSamplingRate != samplingRate ||
Eric Laurentfe231122017-11-17 17:48:06 -08001733 desc->mChannelMask != config->channel_mask ||
1734 !audio_formats_match(desc->mFormat, config->format)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001735 (source_priority(desc->getHighestPrioritySource(false /*activeOnly*/)) <
Eric Laurentbb948092017-01-23 18:33:30 -08001736 source_priority(inputSource)))) {
Eric Laurent555530a2017-02-07 18:17:24 -08001737 reusedInputDesc = desc;
1738 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001739 } else {
1740 desc->addAudioSession(session, audioSession);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001741 ALOGV("%s: reusing input %d", __FUNCTION__, mInputs.keyAt(i));
1742 return mInputs.keyAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08001743 }
Eric Laurent599c7582015-12-07 18:05:55 -08001744 }
1745 }
Eric Laurent599c7582015-12-07 18:05:55 -08001746
Eric Laurent555530a2017-02-07 18:17:24 -08001747 if (reusedInputDesc != 0) {
1748 AudioSessionCollection sessions = reusedInputDesc->getAudioSessions(false /*activeOnly*/);
1749 for (size_t j = 0; j < sessions.size(); j++) {
1750 audio_session_t currentSession = sessions.keyAt(j);
1751 stopInput(reusedInputDesc->mIoHandle, currentSession);
1752 releaseInput(reusedInputDesc->mIoHandle, currentSession);
1753 }
1754 }
Eric Laurent74708e72017-04-07 17:13:42 -07001755#endif
Eric Laurent555530a2017-02-07 18:17:24 -08001756
Eric Laurent3974e3b2017-12-07 17:58:43 -08001757 if (!profile->canOpenNewIo()) {
1758 return AUDIO_IO_HANDLE_NONE;
1759 }
1760
Eric Laurentfe231122017-11-17 17:48:06 -08001761 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001762
Eric Laurentfe231122017-11-17 17:48:06 -08001763 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
1764 lConfig.sample_rate = profileSamplingRate;
1765 lConfig.channel_mask = profileChannelMask;
1766 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07001767
Eric Laurent53b810e2017-12-10 17:25:10 -08001768 if (address == "") {
Mikhail Naganov708e0382018-05-30 09:53:04 -07001769 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -08001770 // the inputs vector must be of size >= 1, but we don't want to crash here
1771 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress : String8("");
1772 }
1773
Eric Laurentfe231122017-11-17 17:48:06 -08001774 status_t status = inputDesc->open(&lConfig, device, address,
1775 halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001776
1777 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001778 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08001779 (profileSamplingRate != lConfig.sample_rate) ||
1780 !audio_formats_match(profileFormat, lConfig.format) ||
1781 (profileChannelMask != lConfig.channel_mask)) {
1782 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001783 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08001784 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001785 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001786 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07001787 }
Eric Laurent599c7582015-12-07 18:05:55 -08001788 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001789 }
1790
Eric Laurentc722f302014-12-10 11:21:49 -08001791 inputDesc->mPolicyMix = policyMix;
Eric Laurent599c7582015-12-07 18:05:55 -08001792 inputDesc->addAudioSession(session, audioSession);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001793
Eric Laurent599c7582015-12-07 18:05:55 -08001794 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001795 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001796
Eric Laurent599c7582015-12-07 18:05:55 -08001797 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001798}
1799
Eric Laurentbb948092017-01-23 18:33:30 -08001800//static
1801bool AudioPolicyManager::isConcurrentSource(audio_source_t source)
1802{
1803 return (source == AUDIO_SOURCE_HOTWORD) ||
1804 (source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
1805 (source == AUDIO_SOURCE_FM_TUNER);
1806}
1807
Eric Laurentfb66dd92016-01-28 18:32:03 -08001808bool AudioPolicyManager::isConcurentCaptureAllowed(const sp<AudioInputDescriptor>& inputDesc,
1809 const sp<AudioSession>& audioSession)
1810{
1811 // Do not allow capture if an active voice call is using a software patch and
1812 // the call TX source device is on the same HW module.
1813 // FIXME: would be better to refine to only inputs whose profile connects to the
1814 // call TX device but this information is not in the audio patch
1815 if (mCallTxPatch != 0 &&
1816 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1817 return false;
1818 }
1819
1820 // starting concurrent capture is enabled if:
1821 // 1) capturing for re-routing
1822 // 2) capturing for HOTWORD source
1823 // 3) capturing for FM TUNER source
1824 // 3) All other active captures are either for re-routing or HOTWORD
1825
1826 if (is_virtual_input_device(inputDesc->mDevice) ||
Eric Laurentbb948092017-01-23 18:33:30 -08001827 isConcurrentSource(audioSession->inputSource())) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001828 return true;
1829 }
1830
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001831 for (const auto& activeInput : mInputs.getActiveInputs()) {
Eric Laurentbb948092017-01-23 18:33:30 -08001832 if (!isConcurrentSource(activeInput->inputSource(true)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001833 !is_virtual_input_device(activeInput->mDevice)) {
1834 return false;
1835 }
1836 }
1837
1838 return true;
1839}
1840
Chris Thornton2b864642017-06-27 21:26:07 -07001841// FIXME: remove when concurrent capture is ready. This is a hack to work around bug b/63083537.
1842bool AudioPolicyManager::soundTriggerSupportsConcurrentCapture() {
1843 if (!mHasComputedSoundTriggerSupportsConcurrentCapture) {
1844 bool soundTriggerSupportsConcurrentCapture = false;
1845 unsigned int numModules = 0;
1846 struct sound_trigger_module_descriptor* nModules = NULL;
1847
1848 status_t status = SoundTrigger::listModules(nModules, &numModules);
1849 if (status == NO_ERROR && numModules != 0) {
1850 nModules = (struct sound_trigger_module_descriptor*) calloc(
1851 numModules, sizeof(struct sound_trigger_module_descriptor));
1852 if (nModules == NULL) {
1853 // We failed to malloc the buffer, so just say no for now, and hope that we have more
1854 // ram the next time this function is called.
1855 ALOGE("Failed to allocate buffer for module descriptors");
1856 return false;
1857 }
1858
1859 status = SoundTrigger::listModules(nModules, &numModules);
1860 if (status == NO_ERROR) {
1861 soundTriggerSupportsConcurrentCapture = true;
1862 for (size_t i = 0; i < numModules; ++i) {
1863 soundTriggerSupportsConcurrentCapture &=
1864 nModules[i].properties.concurrent_capture;
1865 }
1866 }
1867 free(nModules);
1868 }
1869 mSoundTriggerSupportsConcurrentCapture = soundTriggerSupportsConcurrentCapture;
1870 mHasComputedSoundTriggerSupportsConcurrentCapture = true;
1871 }
1872 return mSoundTriggerSupportsConcurrentCapture;
1873}
1874
Eric Laurentfb66dd92016-01-28 18:32:03 -08001875
Eric Laurent4dc68062014-07-28 17:26:49 -07001876status_t AudioPolicyManager::startInput(audio_io_handle_t input,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001877 audio_session_t session,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001878 bool silenced,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001879 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07001880{
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001881
1882 ALOGV("AudioPolicyManager::startInput(input:%d, session:%d, silenced:%d, concurrency:%d)",
1883 input, session, silenced, *concurrency);
1884
Eric Laurentfb66dd92016-01-28 18:32:03 -08001885 *concurrency = API_INPUT_CONCURRENCY_NONE;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001886
Eric Laurente552edb2014-03-10 17:42:56 -07001887 ssize_t index = mInputs.indexOfKey(input);
1888 if (index < 0) {
1889 ALOGW("startInput() unknown input %d", input);
1890 return BAD_VALUE;
1891 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001892 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001893
Eric Laurent599c7582015-12-07 18:05:55 -08001894 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1895 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07001896 ALOGW("startInput() unknown session %d on input %d", session, input);
1897 return BAD_VALUE;
1898 }
1899
Eric Laurent74708e72017-04-07 17:13:42 -07001900// FIXME: disable concurrent capture until UI is ready
1901#if 0
Eric Laurentfb66dd92016-01-28 18:32:03 -08001902 if (!isConcurentCaptureAllowed(inputDesc, audioSession)) {
1903 ALOGW("startInput(%d) failed: other input already started", input);
1904 return INVALID_OPERATION;
1905 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001906
Eric Laurentfb66dd92016-01-28 18:32:03 -08001907 if (isInCall()) {
1908 *concurrency |= API_INPUT_CONCURRENCY_CALL;
1909 }
Eric Laurentf7c50102016-09-30 15:19:43 -07001910 if (mInputs.activeInputsCountOnDevices() != 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001911 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurente552edb2014-03-10 17:42:56 -07001912 }
Eric Laurent74708e72017-04-07 17:13:42 -07001913#else
1914 if (!is_virtual_input_device(inputDesc->mDevice)) {
1915 if (mCallTxPatch != 0 &&
1916 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1917 ALOGW("startInput(%d) failed: call in progress", input);
Ray Essick84e84a52018-05-03 18:45:07 -07001918 *concurrency |= API_INPUT_CONCURRENCY_CALL;
Eric Laurent74708e72017-04-07 17:13:42 -07001919 return INVALID_OPERATION;
1920 }
1921
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001922 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07001923
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001924 // If a UID is idle and records silence and another not silenced recording starts
1925 // from another UID (idle or active) we stop the current idle UID recording in
1926 // favor of the new one - "There can be only one" TM
1927 if (!silenced) {
1928 for (const auto& activeDesc : activeInputs) {
1929 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
1930 activeDesc->getId() == inputDesc->getId()) {
1931 continue;
1932 }
1933
1934 AudioSessionCollection activeSessions = activeDesc->getAudioSessions(
1935 true /*activeOnly*/);
1936 sp<AudioSession> activeSession = activeSessions.valueAt(0);
1937 if (activeSession->isSilenced()) {
1938 audio_io_handle_t activeInput = activeDesc->mIoHandle;
1939 audio_session_t activeSessionId = activeSession->session();
1940 stopInput(activeInput, activeSessionId);
1941 releaseInput(activeInput, activeSessionId);
1942 ALOGV("startInput(%d) stopping silenced input %d", input, activeInput);
1943 activeInputs = mInputs.getActiveInputs();
1944 }
1945 }
1946 }
1947
1948 for (const auto& activeDesc : activeInputs) {
Eric Laurentcb4dae22017-07-01 19:39:32 -07001949 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
1950 activeDesc->getId() == inputDesc->getId()) {
1951 continue;
1952 }
1953
Eric Laurent74708e72017-04-07 17:13:42 -07001954 audio_source_t activeSource = activeDesc->inputSource(true);
1955 if (audioSession->inputSource() == AUDIO_SOURCE_HOTWORD) {
1956 if (activeSource == AUDIO_SOURCE_HOTWORD) {
1957 if (activeDesc->hasPreemptedSession(session)) {
1958 ALOGW("startInput(%d) failed for HOTWORD: "
1959 "other input %d already started for HOTWORD",
1960 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07001961 *concurrency |= API_INPUT_CONCURRENCY_HOTWORD;
Eric Laurent74708e72017-04-07 17:13:42 -07001962 return INVALID_OPERATION;
1963 }
1964 } else {
1965 ALOGV("startInput(%d) failed for HOTWORD: other input %d already started",
1966 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07001967 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07001968 return INVALID_OPERATION;
1969 }
1970 } else {
1971 if (activeSource != AUDIO_SOURCE_HOTWORD) {
1972 ALOGW("startInput(%d) failed: other input %d already started",
1973 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07001974 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07001975 return INVALID_OPERATION;
1976 }
1977 }
1978 }
1979
Chris Thornton2b864642017-06-27 21:26:07 -07001980 // We only need to check if the sound trigger session supports concurrent capture if the
1981 // input is also a sound trigger input. Otherwise, we should preempt any hotword stream
1982 // that's running.
1983 const bool allowConcurrentWithSoundTrigger =
1984 inputDesc->isSoundTrigger() ? soundTriggerSupportsConcurrentCapture() : false;
1985
Eric Laurent74708e72017-04-07 17:13:42 -07001986 // if capture is allowed, preempt currently active HOTWORD captures
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001987 for (const auto& activeDesc : activeInputs) {
Chris Thornton2b864642017-06-27 21:26:07 -07001988 if (allowConcurrentWithSoundTrigger && activeDesc->isSoundTrigger()) {
1989 continue;
1990 }
1991
Eric Laurent74708e72017-04-07 17:13:42 -07001992 audio_source_t activeSource = activeDesc->inputSource(true);
1993 if (activeSource == AUDIO_SOURCE_HOTWORD) {
1994 AudioSessionCollection activeSessions =
1995 activeDesc->getAudioSessions(true /*activeOnly*/);
1996 audio_session_t activeSession = activeSessions.keyAt(0);
1997 audio_io_handle_t activeHandle = activeDesc->mIoHandle;
1998 SortedVector<audio_session_t> sessions = activeDesc->getPreemptedSessions();
Ray Essick84e84a52018-05-03 18:45:07 -07001999 *concurrency |= API_INPUT_CONCURRENCY_PREEMPT;
Eric Laurent74708e72017-04-07 17:13:42 -07002000 sessions.add(activeSession);
2001 inputDesc->setPreemptedSessions(sessions);
2002 stopInput(activeHandle, activeSession);
2003 releaseInput(activeHandle, activeSession);
2004 ALOGV("startInput(%d) for HOTWORD preempting HOTWORD input %d",
2005 input, activeDesc->mIoHandle);
2006 }
2007 }
2008 }
2009#endif
Eric Laurente552edb2014-03-10 17:42:56 -07002010
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002011 // Make sure we start with the correct silence state
2012 audioSession->setSilenced(silenced);
2013
Eric Laurent313d1e72016-01-29 09:56:57 -08002014 // increment activity count before calling getNewInputDevice() below as only active sessions
2015 // are considered for device selection
2016 audioSession->changeActiveCount(1);
2017
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002018 // Routing?
2019 mInputRoutes.incRouteActivity(session);
2020
Eric Laurent2157f5b2018-04-25 18:33:02 -07002021 if (audioSession->activeCount() == 1 || mInputRoutes.getAndClearRouteChanged(session)) {
Eric Laurent271a93e2016-09-29 14:47:06 -07002022 // indicate active capture to sound trigger service if starting capture from a mic on
2023 // primary HW module
Eric Laurentf7c50102016-09-30 15:19:43 -07002024 audio_devices_t device = getNewInputDevice(inputDesc);
Eric Laurent271a93e2016-09-29 14:47:06 -07002025 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002026
Eric Laurent733ce942017-12-07 12:18:25 -08002027 status_t status = inputDesc->start();
2028 if (status != NO_ERROR) {
2029 mInputRoutes.decRouteActivity(session);
2030 audioSession->changeActiveCount(-1);
2031 return status;
2032 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002033
Eric Laurent733ce942017-12-07 12:18:25 -08002034 if (inputDesc->getAudioSessionCount(true/*activeOnly*/) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002035 // if input maps to a dynamic policy with an activity listener, notify of state change
2036 if ((inputDesc->mPolicyMix != NULL)
2037 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2038 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2039 MIX_STATE_MIXING);
Eric Laurentc722f302014-12-10 11:21:49 -08002040 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002041
Eric Laurentf7c50102016-09-30 15:19:43 -07002042 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2043 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Eric Laurent05b345e2016-11-18 12:36:27 -08002044 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002045 SoundTrigger::setCaptureState(true);
2046 }
2047
2048 // automatically enable the remote submix output when input is started if not
2049 // used by a policy mix of type MIX_TYPE_RECORDERS
2050 // For remote submix (a virtual device), we open only one input per capture request.
2051 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2052 String8 address = String8("");
2053 if (inputDesc->mPolicyMix == NULL) {
2054 address = String8("0");
2055 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2056 address = inputDesc->mPolicyMix->mDeviceAddress;
2057 }
2058 if (address != "") {
2059 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2060 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2061 address, "remote-submix");
2062 }
Eric Laurentc722f302014-12-10 11:21:49 -08002063 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002064 }
Eric Laurente552edb2014-03-10 17:42:56 -07002065 }
2066
Eric Laurent599c7582015-12-07 18:05:55 -08002067 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
Eric Laurente552edb2014-03-10 17:42:56 -07002068
Eric Laurente552edb2014-03-10 17:42:56 -07002069 return NO_ERROR;
2070}
2071
Eric Laurent4dc68062014-07-28 17:26:49 -07002072status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
2073 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07002074{
2075 ALOGV("stopInput() input %d", input);
2076 ssize_t index = mInputs.indexOfKey(input);
2077 if (index < 0) {
2078 ALOGW("stopInput() unknown input %d", input);
2079 return BAD_VALUE;
2080 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002081 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07002082
Eric Laurent599c7582015-12-07 18:05:55 -08002083 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07002084 if (index < 0) {
2085 ALOGW("stopInput() unknown session %d on input %d", session, input);
2086 return BAD_VALUE;
2087 }
2088
Eric Laurent599c7582015-12-07 18:05:55 -08002089 if (audioSession->activeCount() == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002090 ALOGW("stopInput() input %d already stopped", input);
2091 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002092 }
2093
Eric Laurent599c7582015-12-07 18:05:55 -08002094 audioSession->changeActiveCount(-1);
Paul McLean466dc8e2015-04-17 13:15:36 -06002095
2096 // Routing?
2097 mInputRoutes.decRouteActivity(session);
2098
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002099 if (audioSession->activeCount() == 0) {
Eric Laurent733ce942017-12-07 12:18:25 -08002100 inputDesc->stop();
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002101 if (inputDesc->isActive()) {
2102 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2103 } else {
2104 // if input maps to a dynamic policy with an activity listener, notify of state change
2105 if ((inputDesc->mPolicyMix != NULL)
2106 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2107 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2108 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002109 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002110
2111 // automatically disable the remote submix output when input is stopped if not
2112 // used by a policy mix of type MIX_TYPE_RECORDERS
2113 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2114 String8 address = String8("");
2115 if (inputDesc->mPolicyMix == NULL) {
2116 address = String8("0");
2117 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2118 address = inputDesc->mPolicyMix->mDeviceAddress;
2119 }
2120 if (address != "") {
2121 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2122 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2123 address, "remote-submix");
2124 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002125 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002126
Eric Laurentf7c50102016-09-30 15:19:43 -07002127 audio_devices_t device = inputDesc->mDevice;
Eric Laurentfb66dd92016-01-28 18:32:03 -08002128 resetInputDevice(input);
Eric Laurent84332aa2016-01-28 22:19:18 +00002129
Eric Laurentf7c50102016-09-30 15:19:43 -07002130 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2131 // primary HW module
2132 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2133 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2134 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08002135 SoundTrigger::setCaptureState(false);
2136 }
2137 inputDesc->clearPreemptedSessions();
Eric Laurent84332aa2016-01-28 22:19:18 +00002138 }
Eric Laurente552edb2014-03-10 17:42:56 -07002139 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002140 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002141}
2142
Eric Laurent4dc68062014-07-28 17:26:49 -07002143void AudioPolicyManager::releaseInput(audio_io_handle_t input,
2144 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07002145{
2146 ALOGV("releaseInput() %d", input);
2147 ssize_t index = mInputs.indexOfKey(input);
2148 if (index < 0) {
2149 ALOGW("releaseInput() releasing unknown input %d", input);
2150 return;
2151 }
Paul McLean466dc8e2015-04-17 13:15:36 -06002152
2153 // Routing
2154 mInputRoutes.removeRoute(session);
2155
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002156 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
2157 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07002158
Eric Laurent599c7582015-12-07 18:05:55 -08002159 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
vivek mehta587b8df2017-01-31 14:58:44 -08002160 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07002161 ALOGW("releaseInput() unknown session %d on input %d", session, input);
2162 return;
2163 }
Eric Laurent599c7582015-12-07 18:05:55 -08002164
2165 if (audioSession->openCount() == 0) {
2166 ALOGW("releaseInput() invalid open count %d on session %d",
2167 audioSession->openCount(), session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002168 return;
2169 }
Eric Laurent599c7582015-12-07 18:05:55 -08002170
2171 if (audioSession->changeOpenCount(-1) == 0) {
2172 inputDesc->removeAudioSession(session);
2173 }
2174
Jean-Michel Trivi65bfe912015-12-04 15:56:47 -08002175 if (inputDesc->getOpenRefCount() > 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002176 ALOGV("releaseInput() exit > 0");
2177 return;
2178 }
2179
Eric Laurent05b90f82014-08-27 15:32:29 -07002180 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002181 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002182 ALOGV("releaseInput() exit");
2183}
2184
Eric Laurentd4692962014-05-05 18:13:44 -07002185void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002186 bool patchRemoved = false;
2187
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002188 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002189 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002190 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002191 if (patch_index >= 0) {
2192 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002193 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002194 mAudioPatches.removeItemsAt(patch_index);
2195 patchRemoved = true;
2196 }
Eric Laurentfe231122017-11-17 17:48:06 -08002197 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002198 }
jiabin829a00b2018-04-04 16:28:32 -07002199 mInputRoutes.clear();
Eric Laurentd4692962014-05-05 18:13:44 -07002200 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002201 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002202 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002203
2204 if (patchRemoved) {
2205 mpClientInterface->onAudioPatchListUpdate();
2206 }
Eric Laurentd4692962014-05-05 18:13:44 -07002207}
2208
Eric Laurente0720872014-03-11 09:30:41 -07002209void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002210 int indexMin,
2211 int indexMax)
2212{
2213 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002214 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002215
2216 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002217 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2218 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002219 continue;
2220 }
2221 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002222 }
Eric Laurente552edb2014-03-10 17:42:56 -07002223}
2224
Eric Laurente0720872014-03-11 09:30:41 -07002225status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002226 int index,
2227 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002228{
2229
Nadav Bar7c605f62017-12-25 00:01:52 +02002230 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2231 // app that has MODIFY_PHONE_STATE permission.
2232 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
2233 !(stream == AUDIO_STREAM_VOICE_CALL && index == 0)) ||
François Gaffied1ab2bd2015-12-02 18:20:06 +01002234 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002235 return BAD_VALUE;
2236 }
2237 if (!audio_is_output_device(device)) {
2238 return BAD_VALUE;
2239 }
2240
2241 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002242 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002243
Eric Laurent1fd372e2016-04-06 14:23:53 -07002244 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002245 stream, device, index);
2246
Eric Laurent28d09f02016-03-08 10:43:05 -08002247 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002248 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2249 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002250 continue;
2251 }
2252 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2253 }
Eric Laurente552edb2014-03-10 17:42:56 -07002254
Eric Laurent1fd372e2016-04-06 14:23:53 -07002255 // update volume on all outputs and streams matching the following:
2256 // - The requested stream (or a stream matching for volume control) is active on the output
2257 // - The device (or devices) selected by the strategy corresponding to this stream includes
2258 // the requested device
2259 // - For non default requested device, currently selected device on the output is either the
2260 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002261 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2262 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002263 status_t status = NO_ERROR;
2264 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002265 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2266 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08002267 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
Eric Laurent3839bc02018-07-10 18:33:34 -07002268 if (!(streamsMatchForvolume(stream, (audio_stream_type_t)curStream))) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002269 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002270 }
Eric Laurentdcd4ab12018-06-29 17:45:13 -07002271 if (!(desc->isStreamActive((audio_stream_type_t)curStream) || isInCall())) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002272 continue;
2273 }
Eric Laurent794fde22016-03-11 09:50:45 -08002274 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002275 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2276 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002277 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2278 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002279 continue;
2280 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002281 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002282 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002283 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07002284 applyVolume = (curDevice & curStreamDevice) != 0;
2285 } else {
2286 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002287 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002288 }
Eric Laurent3839bc02018-07-10 18:33:34 -07002289 // rescale index before applying to curStream as ranges may be different for
2290 // stream and curStream
2291 int idx = rescaleVolumeIndex(index, stream, (audio_stream_type_t)curStream);
Eric Laurente76f29c2016-09-14 17:17:53 -07002292 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002293 //FIXME: workaround for truncated touch sounds
2294 // delayed volume change for system stream to be removed when the problem is
2295 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002296 status_t volStatus =
Eric Laurent3839bc02018-07-10 18:33:34 -07002297 checkAndSetVolume((audio_stream_type_t)curStream, idx, desc, curDevice,
Eric Laurentdc462862016-07-19 12:29:53 -07002298 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002299 if (volStatus != NO_ERROR) {
2300 status = volStatus;
2301 }
2302 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002303 }
Eric Laurente552edb2014-03-10 17:42:56 -07002304 }
2305 return status;
2306}
2307
Eric Laurente0720872014-03-11 09:30:41 -07002308status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002309 int *index,
2310 audio_devices_t device)
2311{
2312 if (index == NULL) {
2313 return BAD_VALUE;
2314 }
2315 if (!audio_is_output_device(device)) {
2316 return BAD_VALUE;
2317 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002318 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002319 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002320 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002321 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2322 }
François Gaffiedfd74092015-03-19 12:10:59 +01002323 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002324
François Gaffied1ab2bd2015-12-02 18:20:06 +01002325 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002326 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2327 return NO_ERROR;
2328}
2329
Eric Laurent36829f92017-04-07 19:04:42 -07002330audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002331{
2332 // select one output among several suitable for global effects.
2333 // The priority is as follows:
2334 // 1: An offloaded output. If the effect ends up not being offloadable,
2335 // AudioFlinger will invalidate the track and the offloaded output
2336 // will be closed causing the effect to be moved to a PCM output.
2337 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002338 // 3: The primary output
2339 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002340
Eric Laurent3b73df72014-03-11 09:06:29 -07002341 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002342 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent36829f92017-04-07 19:04:42 -07002343 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002344
Eric Laurent36829f92017-04-07 19:04:42 -07002345 if (outputs.size() == 0) {
2346 return AUDIO_IO_HANDLE_NONE;
2347 }
Eric Laurente552edb2014-03-10 17:42:56 -07002348
Eric Laurent36829f92017-04-07 19:04:42 -07002349 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2350 bool activeOnly = true;
2351
2352 while (output == AUDIO_IO_HANDLE_NONE) {
2353 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2354 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2355 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2356
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002357 for (audio_io_handle_t output : outputs) {
2358 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002359 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2360 continue;
2361 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002362 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2363 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002364 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002365 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002366 }
2367 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002368 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002369 }
2370 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002371 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002372 }
2373 }
2374 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2375 output = outputOffloaded;
2376 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2377 output = outputDeepBuffer;
2378 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2379 output = outputPrimary;
2380 } else {
2381 output = outputs[0];
2382 }
2383 activeOnly = false;
2384 }
2385
2386 if (output != mMusicEffectOutput) {
2387 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2388 mMusicEffectOutput = output;
2389 }
2390
2391 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002392 return output;
2393}
2394
Eric Laurent36829f92017-04-07 19:04:42 -07002395audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2396{
2397 return selectOutputForMusicEffects();
2398}
2399
Eric Laurente0720872014-03-11 09:30:41 -07002400status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002401 audio_io_handle_t io,
2402 uint32_t strategy,
2403 int session,
2404 int id)
2405{
2406 ssize_t index = mOutputs.indexOfKey(io);
2407 if (index < 0) {
2408 index = mInputs.indexOfKey(io);
2409 if (index < 0) {
2410 ALOGW("registerEffect() unknown io %d", io);
2411 return INVALID_OPERATION;
2412 }
2413 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002414 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002415}
2416
Eric Laurentc75307b2015-03-17 15:29:32 -07002417bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2418{
Eric Laurent28d09f02016-03-08 10:43:05 -08002419 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002420 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2421 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002422 continue;
2423 }
2424 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2425 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002426 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002427}
2428
2429bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2430{
2431 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2432}
2433
Eric Laurente0720872014-03-11 09:30:41 -07002434bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002435{
2436 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002437 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002438 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002439 return true;
2440 }
2441 }
2442 return false;
2443}
2444
Eric Laurent275e8e92014-11-30 15:14:47 -08002445// Register a list of custom mixes with their attributes and format.
2446// When a mix is registered, corresponding input and output profiles are
2447// added to the remote submix hw module. The profile contains only the
2448// parameters (sampling rate, format...) specified by the mix.
2449// The corresponding input remote submix device is also connected.
2450//
2451// When a remote submix device is connected, the address is checked to select the
2452// appropriate profile and the corresponding input or output stream is opened.
2453//
2454// When capture starts, getInputForAttr() will:
2455// - 1 look for a mix matching the address passed in attribtutes tags if any
2456// - 2 if none found, getDeviceForInputSource() will:
2457// - 2.1 look for a mix matching the attributes source
2458// - 2.2 if none found, default to device selection by policy rules
2459// At this time, the corresponding output remote submix device is also connected
2460// and active playback use cases can be transferred to this mix if needed when reconnecting
2461// after AudioTracks are invalidated
2462//
2463// When playback starts, getOutputForAttr() will:
2464// - 1 look for a mix matching the address passed in attribtutes tags if any
2465// - 2 if none found, look for a mix matching the attributes usage
2466// - 3 if none found, default to device and output selection by policy rules.
2467
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002468status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002469{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002470 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2471 status_t res = NO_ERROR;
2472
2473 sp<HwModule> rSubmixModule;
2474 // examine each mix's route type
2475 for (size_t i = 0; i < mixes.size(); i++) {
2476 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
2477 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
2478 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002479 break;
2480 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002481 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002482 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002483 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002484 rSubmixModule = mHwModules.getModuleFromName(
2485 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2486 if (rSubmixModule == 0) {
2487 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2488 i);
2489 res = INVALID_OPERATION;
2490 break;
2491 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002492 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002493
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002494 String8 address = mixes[i].mDeviceAddress;
François Gaffie036e1e92015-03-19 10:16:24 +01002495
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002496 if (mPolicyMixes.registerMix(address, mixes[i], 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002497 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002498 res = INVALID_OPERATION;
2499 break;
2500 }
2501 audio_config_t outputConfig = mixes[i].mFormat;
2502 audio_config_t inputConfig = mixes[i].mFormat;
2503 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2504 // stereo and let audio flinger do the channel conversion if needed.
2505 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2506 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2507 rSubmixModule->addOutputProfile(address, &outputConfig,
2508 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2509 rSubmixModule->addInputProfile(address, &inputConfig,
2510 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002511
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002512 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
2513 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2514 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2515 address.string(), "remote-submix");
2516 } else {
2517 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2518 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2519 address.string(), "remote-submix");
2520 }
2521 } else if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002522 String8 address = mixes[i].mDeviceAddress;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002523 audio_devices_t device = mixes[i].mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002524 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2525 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002526
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002527 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002528 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2529 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2530 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2531 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2532 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2533 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002534 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2535 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002536 if (mPolicyMixes.registerMix(address, mixes[i], desc) != NO_ERROR) {
2537 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002538 } else {
2539 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002540 }
2541 break;
2542 }
2543 }
2544
2545 if (res != NO_ERROR) {
2546 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002547 i, device, address.string());
2548 res = INVALID_OPERATION;
2549 break;
2550 } else if (!foundOutput) {
2551 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2552 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002553 res = INVALID_OPERATION;
2554 break;
2555 }
Eric Laurentc722f302014-12-10 11:21:49 -08002556 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002557 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002558 if (res != NO_ERROR) {
2559 unregisterPolicyMixes(mixes);
2560 }
2561 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002562}
2563
2564status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2565{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002566 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002567 status_t res = NO_ERROR;
2568 sp<HwModule> rSubmixModule;
2569 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002570 for (const auto& mix : mixes) {
2571 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002572
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002573 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002574 rSubmixModule = mHwModules.getModuleFromName(
2575 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2576 if (rSubmixModule == 0) {
2577 res = INVALID_OPERATION;
2578 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002579 }
2580 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002581
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002582 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002583
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002584 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2585 res = INVALID_OPERATION;
2586 continue;
2587 }
2588
2589 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2590 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2591 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2592 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2593 address.string(), "remote-submix");
2594 }
2595 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2596 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2597 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2598 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2599 address.string(), "remote-submix");
2600 }
2601 rSubmixModule->removeOutputProfile(address);
2602 rSubmixModule->removeInputProfile(address);
2603
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002604 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2605 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002606 res = INVALID_OPERATION;
2607 continue;
2608 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002609 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002610 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002611 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002612}
2613
Eric Laurente552edb2014-03-10 17:42:56 -07002614
Eric Laurente0720872014-03-11 09:30:41 -07002615status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002616{
Eric Laurente552edb2014-03-10 17:42:56 -07002617 String8 result;
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002618 result.appendFormat("\nAudioPolicyManager Dump: %p\n", this);
2619 result.appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07002620 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002621 std::string stateLiteral;
2622 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002623 result.appendFormat(" Phone state: %s\n", stateLiteral.c_str());
2624 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
2625 "communications", "media", "record", "dock", "system",
2626 "HDMI system audio", "encoded surround output", "vibrate ringing" };
2627 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
2628 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
2629 result.appendFormat(" Force use for %s: %d\n",
2630 forceUses[i], mEngine->getForceUse(i));
2631 }
2632 result.appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
2633 result.appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
2634 result.appendFormat(" Config source: %s\n", getConfig().getSource().c_str());
François Gaffie2110e042015-03-24 08:41:51 +01002635 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002636
François Gaffie112b0af2015-11-19 16:13:25 +01002637 mAvailableOutputDevices.dump(fd, String8("Available output"));
2638 mAvailableInputDevices.dump(fd, String8("Available input"));
Mikhail Naganovd4120142017-12-06 15:49:22 -08002639 mHwModulesAll.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002640 mOutputs.dump(fd);
2641 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002642 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002643 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002644 mAudioPatches.dump(fd);
Mikhail Naganov44344b02016-12-13 11:21:02 -08002645 mPolicyMixes.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002646
2647 return NO_ERROR;
2648}
2649
2650// This function checks for the parameters which can be offloaded.
2651// This can be enhanced depending on the capability of the DSP and policy
2652// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002653bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002654{
2655 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002656 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002657 offloadInfo.sample_rate, offloadInfo.channel_mask,
2658 offloadInfo.format,
2659 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2660 offloadInfo.has_video);
2661
Andy Hung2ddee192015-12-18 17:34:44 -08002662 if (mMasterMono) {
2663 return false; // no offloading if mono is set.
2664 }
2665
Eric Laurente552edb2014-03-10 17:42:56 -07002666 // Check if offload has been disabled
2667 char propValue[PROPERTY_VALUE_MAX];
2668 if (property_get("audio.offload.disable", propValue, "0")) {
2669 if (atoi(propValue) != 0) {
2670 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2671 return false;
2672 }
2673 }
2674
2675 // Check if stream type is music, then only allow offload as of now.
2676 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2677 {
2678 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2679 return false;
2680 }
2681
2682 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002683 const bool allowOffloadWithVideo =
2684 property_get_bool("audio.offload.video", false /* default_value */);
2685 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002686 ALOGV("isOffloadSupported: has_video == true, returning false");
2687 return false;
2688 }
2689
2690 //If duration is less than minimum value defined in property, return false
2691 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2692 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2693 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2694 return false;
2695 }
2696 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2697 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2698 return false;
2699 }
2700
2701 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2702 // creating an offloaded track and tearing it down immediately after start when audioflinger
2703 // detects there is an active non offloadable effect.
2704 // FIXME: We should check the audio session here but we do not have it in this context.
2705 // This may prevent offloading in rare situations where effects are left active by apps
2706 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002707 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002708 return false;
2709 }
2710
2711 // See if there is a profile to support this.
2712 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002713 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002714 offloadInfo.sample_rate,
2715 offloadInfo.format,
2716 offloadInfo.channel_mask,
2717 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002718 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2719 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002720}
2721
Eric Laurent6a94d692014-05-20 11:18:06 -07002722status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2723 audio_port_type_t type,
2724 unsigned int *num_ports,
2725 struct audio_port *ports,
2726 unsigned int *generation)
2727{
2728 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2729 generation == NULL) {
2730 return BAD_VALUE;
2731 }
2732 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2733 if (ports == NULL) {
2734 *num_ports = 0;
2735 }
2736
2737 size_t portsWritten = 0;
2738 size_t portsMax = *num_ports;
2739 *num_ports = 0;
2740 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002741 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2742 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002743 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002744 for (const auto& dev : mAvailableOutputDevices) {
2745 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002746 continue;
2747 }
2748 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002749 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002750 }
2751 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002752 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002753 }
2754 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002755 for (const auto& dev : mAvailableInputDevices) {
2756 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002757 continue;
2758 }
2759 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002760 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002761 }
2762 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002763 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002764 }
2765 }
2766 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2767 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2768 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2769 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2770 }
2771 *num_ports += mInputs.size();
2772 }
2773 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002774 size_t numOutputs = 0;
2775 for (size_t i = 0; i < mOutputs.size(); i++) {
2776 if (!mOutputs[i]->isDuplicated()) {
2777 numOutputs++;
2778 if (portsWritten < portsMax) {
2779 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2780 }
2781 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002782 }
Eric Laurent84c70242014-06-23 08:46:27 -07002783 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002784 }
2785 }
2786 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002787 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002788 return NO_ERROR;
2789}
2790
Eric Laurent99fcae42018-05-17 16:59:18 -07002791status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07002792{
Eric Laurent99fcae42018-05-17 16:59:18 -07002793 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
2794 return BAD_VALUE;
2795 }
2796 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
2797 if (dev != 0) {
2798 dev->toAudioPort(port);
2799 return NO_ERROR;
2800 }
2801 dev = mAvailableInputDevices.getDeviceFromId(port->id);
2802 if (dev != 0) {
2803 dev->toAudioPort(port);
2804 return NO_ERROR;
2805 }
2806 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
2807 if (out != 0) {
2808 out->toAudioPort(port);
2809 return NO_ERROR;
2810 }
2811 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
2812 if (in != 0) {
2813 in->toAudioPort(port);
2814 return NO_ERROR;
2815 }
2816 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002817}
2818
Eric Laurent6a94d692014-05-20 11:18:06 -07002819status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2820 audio_patch_handle_t *handle,
2821 uid_t uid)
2822{
2823 ALOGV("createAudioPatch()");
2824
2825 if (handle == NULL || patch == NULL) {
2826 return BAD_VALUE;
2827 }
2828 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2829
Mikhail Naganovac9858b2018-06-15 13:12:37 -07002830 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07002831 return BAD_VALUE;
2832 }
2833 // only one source per audio patch supported for now
2834 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002835 return INVALID_OPERATION;
2836 }
Eric Laurent874c42872014-08-08 15:13:39 -07002837
2838 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002839 return INVALID_OPERATION;
2840 }
Eric Laurent874c42872014-08-08 15:13:39 -07002841 for (size_t i = 0; i < patch->num_sinks; i++) {
2842 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2843 return INVALID_OPERATION;
2844 }
2845 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002846
2847 sp<AudioPatch> patchDesc;
2848 ssize_t index = mAudioPatches.indexOfKey(*handle);
2849
Eric Laurent6a94d692014-05-20 11:18:06 -07002850 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2851 patch->sources[0].role,
2852 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002853#if LOG_NDEBUG == 0
2854 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002855 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002856 patch->sinks[i].role,
2857 patch->sinks[i].type);
2858 }
2859#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002860
2861 if (index >= 0) {
2862 patchDesc = mAudioPatches.valueAt(index);
2863 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2864 mUidCached, patchDesc->mUid, uid);
2865 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2866 return INVALID_OPERATION;
2867 }
2868 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002869 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002870 }
2871
2872 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002873 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002874 if (outputDesc == NULL) {
2875 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2876 return BAD_VALUE;
2877 }
Eric Laurent84c70242014-06-23 08:46:27 -07002878 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2879 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002880 if (patchDesc != 0) {
2881 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2882 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2883 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2884 return BAD_VALUE;
2885 }
2886 }
Eric Laurent874c42872014-08-08 15:13:39 -07002887 DeviceVector devices;
2888 for (size_t i = 0; i < patch->num_sinks; i++) {
2889 // Only support mix to devices connection
2890 // TODO add support for mix to mix connection
2891 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2892 ALOGV("createAudioPatch() source mix but sink is not a device");
2893 return INVALID_OPERATION;
2894 }
2895 sp<DeviceDescriptor> devDesc =
2896 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2897 if (devDesc == 0) {
2898 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2899 return BAD_VALUE;
2900 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002901
François Gaffie53615e22015-03-19 09:24:12 +01002902 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002903 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002904 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002905 NULL, // updatedSamplingRate
2906 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002907 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002908 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002909 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002910 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002911 ALOGV("createAudioPatch() profile not supported for device %08x",
2912 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002913 return INVALID_OPERATION;
2914 }
2915 devices.add(devDesc);
2916 }
2917 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002918 return INVALID_OPERATION;
2919 }
Eric Laurent874c42872014-08-08 15:13:39 -07002920
Eric Laurent6a94d692014-05-20 11:18:06 -07002921 // TODO: reconfigure output format and channels here
2922 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002923 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002924 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002925 index = mAudioPatches.indexOfKey(*handle);
2926 if (index >= 0) {
2927 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2928 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2929 }
2930 patchDesc = mAudioPatches.valueAt(index);
2931 patchDesc->mUid = uid;
2932 ALOGV("createAudioPatch() success");
2933 } else {
2934 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2935 return INVALID_OPERATION;
2936 }
2937 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2938 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2939 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002940 // only one sink supported when connecting an input device to a mix
2941 if (patch->num_sinks > 1) {
2942 return INVALID_OPERATION;
2943 }
François Gaffie53615e22015-03-19 09:24:12 +01002944 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002945 if (inputDesc == NULL) {
2946 return BAD_VALUE;
2947 }
2948 if (patchDesc != 0) {
2949 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2950 return BAD_VALUE;
2951 }
2952 }
2953 sp<DeviceDescriptor> devDesc =
2954 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2955 if (devDesc == 0) {
2956 return BAD_VALUE;
2957 }
2958
François Gaffie53615e22015-03-19 09:24:12 +01002959 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002960 devDesc->mAddress,
2961 patch->sinks[0].sample_rate,
2962 NULL, /*updatedSampleRate*/
2963 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002964 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002965 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002966 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002967 // FIXME for the parameter type,
2968 // and the NONE
2969 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002970 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002971 return INVALID_OPERATION;
2972 }
2973 // TODO: reconfigure output format and channels here
2974 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01002975 devDesc->type(), inputDesc->mIoHandle);
2976 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002977 index = mAudioPatches.indexOfKey(*handle);
2978 if (index >= 0) {
2979 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2980 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2981 }
2982 patchDesc = mAudioPatches.valueAt(index);
2983 patchDesc->mUid = uid;
2984 ALOGV("createAudioPatch() success");
2985 } else {
2986 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2987 return INVALID_OPERATION;
2988 }
2989 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2990 // device to device connection
2991 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002992 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002993 return BAD_VALUE;
2994 }
2995 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002996 sp<DeviceDescriptor> srcDeviceDesc =
2997 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002998 if (srcDeviceDesc == 0) {
2999 return BAD_VALUE;
3000 }
Eric Laurent874c42872014-08-08 15:13:39 -07003001
Eric Laurent6a94d692014-05-20 11:18:06 -07003002 //update source and sink with our own data as the data passed in the patch may
3003 // be incomplete.
3004 struct audio_patch newPatch = *patch;
3005 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003006
Eric Laurent874c42872014-08-08 15:13:39 -07003007 for (size_t i = 0; i < patch->num_sinks; i++) {
3008 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3009 ALOGV("createAudioPatch() source device but one sink is not a device");
3010 return INVALID_OPERATION;
3011 }
3012
3013 sp<DeviceDescriptor> sinkDeviceDesc =
3014 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3015 if (sinkDeviceDesc == 0) {
3016 return BAD_VALUE;
3017 }
3018 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
3019
Eric Laurent3bcf8592015-04-03 12:13:24 -07003020 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003021 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003022 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08003023 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003024 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003025 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003026 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003027 return INVALID_OPERATION;
3028 }
Eric Laurent874c42872014-08-08 15:13:39 -07003029 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01003030 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003031 // if the sink device is reachable via an opened output stream, request to go via
3032 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07003033 audio_io_handle_t output = selectOutput(outputs,
3034 AUDIO_OUTPUT_FLAG_NONE,
3035 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07003036 if (output != AUDIO_IO_HANDLE_NONE) {
3037 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3038 if (outputDesc->isDuplicated()) {
3039 return INVALID_OPERATION;
3040 }
3041 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003042 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003043 newPatch.num_sources = 2;
3044 }
Eric Laurent83b88082014-06-20 18:31:16 -07003045 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003046 }
3047 // TODO: check from routing capabilities in config file and other conflicting patches
3048
Mikhail Naganovdc769682018-05-04 15:34:08 -07003049 status_t status = installPatch(__func__, index, handle, &newPatch, 0, uid, &patchDesc);
3050 if (status != NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003051 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3052 status);
3053 return INVALID_OPERATION;
3054 }
3055 } else {
3056 return BAD_VALUE;
3057 }
3058 } else {
3059 return BAD_VALUE;
3060 }
3061 return NO_ERROR;
3062}
3063
3064status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3065 uid_t uid)
3066{
3067 ALOGV("releaseAudioPatch() patch %d", handle);
3068
3069 ssize_t index = mAudioPatches.indexOfKey(handle);
3070
3071 if (index < 0) {
3072 return BAD_VALUE;
3073 }
3074 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3075 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3076 mUidCached, patchDesc->mUid, uid);
3077 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3078 return INVALID_OPERATION;
3079 }
3080
3081 struct audio_patch *patch = &patchDesc->mPatch;
3082 patchDesc->mUid = mUidCached;
3083 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003084 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003085 if (outputDesc == NULL) {
3086 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3087 return BAD_VALUE;
3088 }
3089
Eric Laurentc75307b2015-03-17 15:29:32 -07003090 setOutputDevice(outputDesc,
3091 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07003092 true,
3093 0,
3094 NULL);
3095 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3096 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003097 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003098 if (inputDesc == NULL) {
3099 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3100 return BAD_VALUE;
3101 }
3102 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003103 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003104 true,
3105 NULL);
3106 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003107 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3108 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3109 status, patchDesc->mAfPatchHandle);
3110 removeAudioPatch(patchDesc->mHandle);
3111 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003112 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003113 } else {
3114 return BAD_VALUE;
3115 }
3116 } else {
3117 return BAD_VALUE;
3118 }
3119 return NO_ERROR;
3120}
3121
3122status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3123 struct audio_patch *patches,
3124 unsigned int *generation)
3125{
François Gaffie53615e22015-03-19 09:24:12 +01003126 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003127 return BAD_VALUE;
3128 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003129 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003130 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003131}
3132
Eric Laurente1715a42014-05-20 11:30:42 -07003133status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003134{
Eric Laurente1715a42014-05-20 11:30:42 -07003135 ALOGV("setAudioPortConfig()");
3136
3137 if (config == NULL) {
3138 return BAD_VALUE;
3139 }
3140 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3141 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003142 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3143 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003144 }
3145
Eric Laurenta121f902014-06-03 13:32:54 -07003146 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003147 if (config->type == AUDIO_PORT_TYPE_MIX) {
3148 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003149 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003150 if (outputDesc == NULL) {
3151 return BAD_VALUE;
3152 }
Eric Laurent84c70242014-06-23 08:46:27 -07003153 ALOG_ASSERT(!outputDesc->isDuplicated(),
3154 "setAudioPortConfig() called on duplicated output %d",
3155 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003156 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003157 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003158 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003159 if (inputDesc == NULL) {
3160 return BAD_VALUE;
3161 }
Eric Laurenta121f902014-06-03 13:32:54 -07003162 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003163 } else {
3164 return BAD_VALUE;
3165 }
3166 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3167 sp<DeviceDescriptor> deviceDesc;
3168 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3169 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3170 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3171 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3172 } else {
3173 return BAD_VALUE;
3174 }
3175 if (deviceDesc == NULL) {
3176 return BAD_VALUE;
3177 }
Eric Laurenta121f902014-06-03 13:32:54 -07003178 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003179 } else {
3180 return BAD_VALUE;
3181 }
3182
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003183 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003184 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3185 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003186 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003187 audioPortConfig->toAudioPortConfig(&newConfig, config);
3188 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003189 }
Eric Laurenta121f902014-06-03 13:32:54 -07003190 if (status != NO_ERROR) {
3191 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003192 }
Eric Laurente1715a42014-05-20 11:30:42 -07003193
3194 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003195}
3196
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003197void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3198{
Eric Laurentd60560a2015-04-10 11:31:20 -07003199 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003200 clearAudioPatches(uid);
3201 clearSessionRoutes(uid);
3202}
3203
Eric Laurent6a94d692014-05-20 11:18:06 -07003204void AudioPolicyManager::clearAudioPatches(uid_t uid)
3205{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003206 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003207 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3208 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003209 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003210 }
3211 }
3212}
3213
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003214void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3215 audio_io_handle_t ouptutToSkip)
3216{
3217 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3218 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3219 for (size_t j = 0; j < mOutputs.size(); j++) {
3220 if (mOutputs.keyAt(j) == ouptutToSkip) {
3221 continue;
3222 }
3223 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3224 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3225 continue;
3226 }
3227 // If the default device for this strategy is on another output mix,
3228 // invalidate all tracks in this strategy to force re connection.
3229 // Otherwise select new device on the output mix.
3230 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003231 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003232 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3233 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3234 }
3235 }
3236 } else {
3237 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3238 setOutputDevice(outputDesc, newDevice, false);
3239 }
3240 }
3241}
3242
3243void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3244{
3245 // remove output routes associated with this uid
3246 SortedVector<routing_strategy> affectedStrategies;
3247 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
3248 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
3249 if (route->mUid == uid) {
3250 mOutputRoutes.removeItemsAt(i);
3251 if (route->mDeviceDescriptor != 0) {
3252 affectedStrategies.add(getStrategy(route->mStreamType));
3253 }
3254 }
3255 }
3256 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003257 for (const auto& strategy : affectedStrategies) {
3258 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003259 }
3260
3261 // remove input routes associated with this uid
3262 SortedVector<audio_source_t> affectedSources;
3263 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
3264 sp<SessionRoute> route = mInputRoutes.valueAt(i);
3265 if (route->mUid == uid) {
3266 mInputRoutes.removeItemsAt(i);
3267 if (route->mDeviceDescriptor != 0) {
3268 affectedSources.add(route->mSource);
3269 }
3270 }
3271 }
3272 // reroute inputs if necessary
3273 SortedVector<audio_io_handle_t> inputsToClose;
3274 for (size_t i = 0; i < mInputs.size(); i++) {
3275 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003276 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003277 inputsToClose.add(inputDesc->mIoHandle);
3278 }
3279 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003280 for (const auto& input : inputsToClose) {
3281 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003282 }
3283}
3284
Eric Laurentd60560a2015-04-10 11:31:20 -07003285void AudioPolicyManager::clearAudioSources(uid_t uid)
3286{
3287 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
3288 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3289 if (sourceDesc->mUid == uid) {
3290 stopAudioSource(mAudioSources.keyAt(i));
3291 }
3292 }
3293}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003294
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003295status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3296 audio_io_handle_t *ioHandle,
3297 audio_devices_t *device)
3298{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003299 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3300 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003301 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003302
François Gaffiedf372692015-03-19 10:43:27 +01003303 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003304}
3305
Eric Laurentd60560a2015-04-10 11:31:20 -07003306status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
3307 const audio_attributes_t *attributes,
Glenn Kasten559d4392016-03-29 13:42:57 -07003308 audio_patch_handle_t *handle,
Eric Laurentd60560a2015-04-10 11:31:20 -07003309 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003310{
Eric Laurentd60560a2015-04-10 11:31:20 -07003311 ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle);
3312 if (source == NULL || attributes == NULL || handle == NULL) {
3313 return BAD_VALUE;
3314 }
3315
Glenn Kasten559d4392016-03-29 13:42:57 -07003316 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003317
3318 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3319 source->type != AUDIO_PORT_TYPE_DEVICE) {
3320 ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type);
3321 return INVALID_OPERATION;
3322 }
3323
3324 sp<DeviceDescriptor> srcDeviceDesc =
3325 mAvailableInputDevices.getDevice(source->ext.device.type,
3326 String8(source->ext.device.address));
3327 if (srcDeviceDesc == 0) {
3328 ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
3329 return BAD_VALUE;
3330 }
3331 sp<AudioSourceDescriptor> sourceDesc =
3332 new AudioSourceDescriptor(srcDeviceDesc, attributes, uid);
3333
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003334 struct audio_patch dummyPatch = {};
Eric Laurentd60560a2015-04-10 11:31:20 -07003335 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
3336 sourceDesc->mPatchDesc = patchDesc;
3337
3338 status_t status = connectAudioSource(sourceDesc);
3339 if (status == NO_ERROR) {
3340 mAudioSources.add(sourceDesc->getHandle(), sourceDesc);
3341 *handle = sourceDesc->getHandle();
3342 }
3343 return status;
3344}
3345
3346status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3347{
3348 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3349
3350 // make sure we only have one patch per source.
3351 disconnectAudioSource(sourceDesc);
3352
3353 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
Eric Laurent28d09f02016-03-08 10:43:05 -08003354 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003355 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice;
3356
3357 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3358 sp<DeviceDescriptor> sinkDeviceDesc =
3359 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3360
3361 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003362
3363 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3364 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003365 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003366 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3367 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3368 // create patch between src device and output device
3369 // create Hwoutput and add to mHwOutputs
3370 } else {
3371 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3372 audio_io_handle_t output =
3373 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3374 if (output == AUDIO_IO_HANDLE_NONE) {
3375 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3376 return INVALID_OPERATION;
3377 }
3378 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3379 if (outputDesc->isDuplicated()) {
3380 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3381 return INVALID_OPERATION;
3382 }
Eric Laurent733ce942017-12-07 12:18:25 -08003383 status_t status = outputDesc->start();
3384 if (status != NO_ERROR) {
3385 return status;
3386 }
3387
Eric Laurentd60560a2015-04-10 11:31:20 -07003388 // create a special patch with no sink and two sources:
3389 // - the second source indicates to PatchPanel through which output mix this patch should
3390 // be connected as well as the stream type for volume control
3391 // - the sink is defined by whatever output device is currently selected for the output
3392 // though which this patch is routed.
Mikhail Naganovdc769682018-05-04 15:34:08 -07003393 PatchBuilder patchBuilder;
3394 patchBuilder.addSource(srcDeviceDesc).addSource(outputDesc, { .stream = stream });
3395 status = mpClientInterface->createAudioPatch(patchBuilder.patch(),
Eric Laurentd60560a2015-04-10 11:31:20 -07003396 &afPatchHandle,
3397 0);
3398 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3399 status, afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07003400 sourceDesc->mPatchDesc->mPatch = *patchBuilder.patch();
Eric Laurentd60560a2015-04-10 11:31:20 -07003401 if (status != NO_ERROR) {
3402 ALOGW("%s patch panel could not connect device patch, error %d",
3403 __FUNCTION__, status);
3404 return INVALID_OPERATION;
3405 }
3406 uint32_t delayMs = 0;
Eric Laurentc40d9692016-04-13 19:14:13 -07003407 status = startSource(outputDesc, stream, sinkDevice, NULL, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003408
3409 if (status != NO_ERROR) {
3410 mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0);
3411 return status;
3412 }
3413 sourceDesc->mSwOutput = outputDesc;
3414 if (delayMs != 0) {
3415 usleep(delayMs * 1000);
3416 }
3417 }
3418
3419 sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle;
3420 addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc);
3421
3422 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003423}
3424
Glenn Kasten559d4392016-03-29 13:42:57 -07003425status_t AudioPolicyManager::stopAudioSource(audio_patch_handle_t handle __unused)
Eric Laurent554a2772015-04-10 11:29:24 -07003426{
Eric Laurentd60560a2015-04-10 11:31:20 -07003427 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle);
3428 ALOGV("%s handle %d", __FUNCTION__, handle);
3429 if (sourceDesc == 0) {
3430 ALOGW("%s unknown source for handle %d", __FUNCTION__, handle);
3431 return BAD_VALUE;
3432 }
3433 status_t status = disconnectAudioSource(sourceDesc);
3434
3435 mAudioSources.removeItem(handle);
3436 return status;
3437}
3438
Andy Hung2ddee192015-12-18 17:34:44 -08003439status_t AudioPolicyManager::setMasterMono(bool mono)
3440{
3441 if (mMasterMono == mono) {
3442 return NO_ERROR;
3443 }
3444 mMasterMono = mono;
3445 // if enabling mono we close all offloaded devices, which will invalidate the
3446 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3447 // for recreating the new AudioTrack as non-offloaded PCM.
3448 //
3449 // If disabling mono, we leave all tracks as is: we don't know which clients
3450 // and tracks are able to be recreated as offloaded. The next "song" should
3451 // play back offloaded.
3452 if (mMasterMono) {
3453 Vector<audio_io_handle_t> offloaded;
3454 for (size_t i = 0; i < mOutputs.size(); ++i) {
3455 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3456 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3457 offloaded.push(desc->mIoHandle);
3458 }
3459 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003460 for (const auto& handle : offloaded) {
3461 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003462 }
3463 }
3464 // update master mono for all remaining outputs
3465 for (size_t i = 0; i < mOutputs.size(); ++i) {
3466 updateMono(mOutputs.keyAt(i));
3467 }
3468 return NO_ERROR;
3469}
3470
3471status_t AudioPolicyManager::getMasterMono(bool *mono)
3472{
3473 *mono = mMasterMono;
3474 return NO_ERROR;
3475}
3476
Eric Laurentac9cef52017-06-09 15:46:26 -07003477float AudioPolicyManager::getStreamVolumeDB(
3478 audio_stream_type_t stream, int index, audio_devices_t device)
3479{
3480 return computeVolume(stream, index, device);
3481}
3482
jiabin81772902018-04-02 17:52:27 -07003483status_t AudioPolicyManager::getSupportedFormats(audio_io_handle_t ioHandle,
3484 FormatVector& formats) {
3485 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
3486 return BAD_VALUE;
3487 }
3488 String8 reply;
3489 reply = mpClientInterface->getParameters(
3490 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
3491 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
3492 AudioParameter repliedParameters(reply);
3493 if (repliedParameters.get(
3494 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
3495 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
3496 return BAD_VALUE;
3497 }
3498 for (auto format : formatsFromString(reply.string())) {
3499 // Only AUDIO_FORMAT_AAC_LC will be used in Settings UI for all AAC formats.
3500 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3501 if (format == AAC_FORMATS[i]) {
3502 format = AUDIO_FORMAT_AAC_LC;
3503 break;
3504 }
3505 }
3506 bool exist = false;
3507 for (size_t i = 0; i < formats.size(); i++) {
3508 if (format == formats[i]) {
3509 exist = true;
3510 break;
3511 }
3512 }
3513 bool isSurroundFormat = false;
3514 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3515 if (SURROUND_FORMATS[i] == format) {
3516 isSurroundFormat = true;
3517 break;
3518 }
3519 }
3520 if (!exist && isSurroundFormat) {
3521 formats.add(format);
3522 }
3523 }
3524 return NO_ERROR;
3525}
3526
3527status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3528 audio_format_t *surroundFormats,
3529 bool *surroundFormatsEnabled,
3530 bool reported)
3531{
3532 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3533 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3534 return BAD_VALUE;
3535 }
3536 ALOGV("getSurroundFormats() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
3537 *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
3538
3539 // Only return value if there is HDMI output.
3540 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3541 return INVALID_OPERATION;
3542 }
3543
3544 size_t formatsWritten = 0;
3545 size_t formatsMax = *numSurroundFormats;
3546 *numSurroundFormats = 0;
3547 FormatVector formats;
3548 if (reported) {
3549 // Only get surround formats which are reported by device.
3550 // First list already open outputs that can be routed to this device
3551 audio_devices_t device = AUDIO_DEVICE_OUT_HDMI;
3552 SortedVector<audio_io_handle_t> outputs;
3553 bool reportedFormatFound = false;
3554 status_t status;
3555 sp<SwAudioOutputDescriptor> desc;
3556 for (size_t i = 0; i < mOutputs.size(); i++) {
3557 desc = mOutputs.valueAt(i);
3558 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
3559 outputs.add(mOutputs.keyAt(i));
3560 }
3561 }
3562 // Open an output to query dynamic parameters.
Mikhail Naganov708e0382018-05-30 09:53:04 -07003563 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003564 AUDIO_DEVICE_OUT_HDMI);
3565 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3566 String8 address = hdmiOutputDevices[i]->mAddress;
3567 for (const auto& hwModule : mHwModules) {
3568 for (size_t i = 0; i < hwModule->getOutputProfiles().size(); i++) {
3569 sp<IOProfile> profile = hwModule->getOutputProfiles()[i];
3570 if (profile->supportDevice(AUDIO_DEVICE_OUT_HDMI) &&
3571 profile->supportDeviceAddress(address)) {
3572 size_t j;
3573 for (j = 0; j < outputs.size(); j++) {
3574 desc = mOutputs.valueFor(outputs.itemAt(j));
3575 if (!desc->isDuplicated() && desc->mProfile == profile) {
3576 break;
3577 }
3578 }
3579 if (j != outputs.size()) {
3580 status = getSupportedFormats(outputs.itemAt(j), formats);
3581 reportedFormatFound |= (status == NO_ERROR);
3582 continue;
3583 }
3584
3585 if (!profile->canOpenNewIo()) {
3586 ALOGW("Max Output number %u already opened for this profile %s",
3587 profile->maxOpenCount, profile->getTagName().c_str());
3588 continue;
3589 }
3590
3591 ALOGV("opening output for device %08x with params %s profile %p name %s",
3592 device, address.string(), profile.get(), profile->getName().string());
3593 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
3594 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3595 status_t status = desc->open(nullptr, device, address,
3596 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE,
3597 &output);
3598
3599 if (status == NO_ERROR) {
3600 status = getSupportedFormats(output, formats);
3601 reportedFormatFound |= (status == NO_ERROR);
3602 desc->close();
3603 output = AUDIO_IO_HANDLE_NONE;
3604 }
3605 }
3606 }
3607 }
3608 }
3609
3610 if (!reportedFormatFound) {
3611 return UNKNOWN_ERROR;
3612 }
3613 } else {
3614 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3615 formats.add(SURROUND_FORMATS[i]);
3616 }
3617 }
3618 for (size_t i = 0; i < formats.size(); i++) {
3619 if (formatsWritten < formatsMax) {
3620 surroundFormats[formatsWritten] = formats[i];
3621 bool formatEnabled = false;
3622 if (formats[i] == AUDIO_FORMAT_AAC_LC) {
3623 for (size_t j = 0; j < ARRAY_SIZE(AAC_FORMATS); j++) {
3624 formatEnabled =
3625 mSurroundFormats.find(AAC_FORMATS[i]) != mSurroundFormats.end();
3626 break;
3627 }
3628 } else {
3629 formatEnabled = mSurroundFormats.find(formats[i]) != mSurroundFormats.end();
3630 }
3631 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3632 }
3633 (*numSurroundFormats)++;
3634 }
3635 return NO_ERROR;
3636}
3637
3638status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3639{
3640 // Check if audio format is a surround formats.
3641 bool isSurroundFormat = false;
3642 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3643 if (audioFormat == SURROUND_FORMATS[i]) {
3644 isSurroundFormat = true;
3645 break;
3646 }
3647 }
3648 if (!isSurroundFormat) {
3649 return BAD_VALUE;
3650 }
3651
3652 // Should only be called when MANUAL.
3653 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3654 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
3655 if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3656 return INVALID_OPERATION;
3657 }
3658
3659 if ((mSurroundFormats.find(audioFormat) != mSurroundFormats.end() && enabled)
3660 || (mSurroundFormats.find(audioFormat) == mSurroundFormats.end() && !enabled)) {
3661 return NO_ERROR;
3662 }
3663
3664 // The operation is valid only when there is HDMI output available.
3665 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3666 return INVALID_OPERATION;
3667 }
3668
3669 if (enabled) {
3670 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3671 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3672 mSurroundFormats.insert(AAC_FORMATS[i]);
3673 }
3674 } else {
3675 mSurroundFormats.insert(audioFormat);
3676 }
3677 } else {
3678 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3679 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3680 mSurroundFormats.erase(AAC_FORMATS[i]);
3681 }
3682 } else {
3683 mSurroundFormats.erase(audioFormat);
3684 }
3685 }
3686
3687 sp<SwAudioOutputDescriptor> outputDesc;
3688 bool profileUpdated = false;
Mikhail Naganov708e0382018-05-30 09:53:04 -07003689 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003690 AUDIO_DEVICE_OUT_HDMI);
3691 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3692 // Simulate reconnection to update enabled surround sound formats.
3693 String8 address = hdmiOutputDevices[i]->mAddress;
3694 String8 name = hdmiOutputDevices[i]->getName();
3695 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3696 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3697 address.c_str(),
3698 name.c_str());
3699 if (status != NO_ERROR) {
3700 continue;
3701 }
3702 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3703 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3704 address.c_str(),
3705 name.c_str());
3706 profileUpdated |= (status == NO_ERROR);
3707 }
Mikhail Naganov708e0382018-05-30 09:53:04 -07003708 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003709 AUDIO_DEVICE_IN_HDMI);
3710 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3711 // Simulate reconnection to update enabled surround sound formats.
3712 String8 address = hdmiInputDevices[i]->mAddress;
3713 String8 name = hdmiInputDevices[i]->getName();
3714 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3715 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3716 address.c_str(),
3717 name.c_str());
3718 if (status != NO_ERROR) {
3719 continue;
3720 }
3721 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3722 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3723 address.c_str(),
3724 name.c_str());
3725 profileUpdated |= (status == NO_ERROR);
3726 }
3727
3728 // Undo the surround formats change due to no audio profiles updated.
3729 if (!profileUpdated) {
3730 if (enabled) {
3731 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3732 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3733 mSurroundFormats.erase(AAC_FORMATS[i]);
3734 }
3735 } else {
3736 mSurroundFormats.erase(audioFormat);
3737 }
3738 } else {
3739 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3740 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3741 mSurroundFormats.insert(AAC_FORMATS[i]);
3742 }
3743 } else {
3744 mSurroundFormats.insert(audioFormat);
3745 }
3746 }
3747 }
3748
3749 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3750}
3751
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003752void AudioPolicyManager::setRecordSilenced(uid_t uid, bool silenced)
3753{
3754 ALOGV("AudioPolicyManager:setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
3755
3756 Vector<sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
3757 for (size_t i = 0; i < activeInputs.size(); i++) {
3758 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
3759 AudioSessionCollection activeSessions = activeDesc->getAudioSessions(true);
3760 for (size_t j = 0; j < activeSessions.size(); j++) {
3761 sp<AudioSession> activeSession = activeSessions.valueAt(j);
3762 if (activeSession->uid() == uid) {
3763 activeSession->setSilenced(silenced);
3764 }
3765 }
3766 }
3767}
3768
Eric Laurentd60560a2015-04-10 11:31:20 -07003769status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3770{
3771 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3772
3773 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle);
3774 if (patchDesc == 0) {
3775 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
3776 sourceDesc->mPatchDesc->mHandle);
3777 return BAD_VALUE;
3778 }
3779 removeAudioPatch(sourceDesc->mPatchDesc->mHandle);
3780
Eric Laurent28d09f02016-03-08 10:43:05 -08003781 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003782 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote();
3783 if (swOutputDesc != 0) {
Eric Laurent733ce942017-12-07 12:18:25 -08003784 status_t status = stopSource(swOutputDesc, stream, false);
3785 if (status == NO_ERROR) {
3786 swOutputDesc->stop();
3787 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003788 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3789 } else {
3790 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote();
3791 if (hwOutputDesc != 0) {
3792 // release patch between src device and output device
3793 // close Hwoutput and remove from mHwOutputs
3794 } else {
3795 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3796 }
3797 }
3798 return NO_ERROR;
3799}
3800
3801sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
3802 audio_io_handle_t output, routing_strategy strategy)
3803{
3804 sp<AudioSourceDescriptor> source;
3805 for (size_t i = 0; i < mAudioSources.size(); i++) {
3806 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3807 routing_strategy sourceStrategy =
3808 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
3809 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote();
3810 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3811 source = sourceDesc;
3812 break;
3813 }
3814 }
3815 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003816}
3817
Eric Laurente552edb2014-03-10 17:42:56 -07003818// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003819// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003820// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003821uint32_t AudioPolicyManager::nextAudioPortGeneration()
3822{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003823 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003824}
3825
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003826#ifdef USE_XML_AUDIO_POLICY_CONF
3827// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3828static const char *kConfigLocationList[] =
3829 {"/odm/etc", "/vendor/etc", "/system/etc"};
3830static const int kConfigLocationListSize =
3831 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3832
3833static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3834 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07003835 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003836 status_t ret;
3837
Petri Gyntherf497f292018-04-17 18:46:10 -07003838 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
3839 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
3840 // A2DP offload supported but disabled: try to use special XML file
3841 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
3842 }
3843 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3844
3845 for (const char* fileName : fileNames) {
3846 for (int i = 0; i < kConfigLocationListSize; i++) {
3847 PolicySerializer serializer;
3848 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
3849 "%s/%s", kConfigLocationList[i], fileName);
3850 ret = serializer.deserialize(audioPolicyXmlConfigFile, config);
3851 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003852 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07003853 return ret;
3854 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003855 }
3856 }
3857 return ret;
3858}
3859#endif
3860
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003861AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
3862 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07003863 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07003864 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003865 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07003866 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003867 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003868#ifdef USE_XML_AUDIO_POLICY_CONF
3869 mVolumeCurves(new VolumeCurvesCollection()),
3870 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08003871 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003872#else
3873 mVolumeCurves(new StreamDescriptorCollection()),
3874 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
3875 mDefaultOutputDevice),
3876#endif
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003877 mAudioPortGeneration(1),
3878 mBeaconMuteRefCount(0),
3879 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003880 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003881 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003882 mMasterMono(false),
Chris Thornton2b864642017-06-27 21:26:07 -07003883 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE),
3884 mHasComputedSoundTriggerSupportsConcurrentCapture(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003885{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003886}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003887
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003888AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
3889 : AudioPolicyManager(clientInterface, false /*forTesting*/)
3890{
3891 loadConfig();
3892 initialize();
3893}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003894
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003895void AudioPolicyManager::loadConfig() {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003896#ifdef USE_XML_AUDIO_POLICY_CONF
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003897 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003898#else
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003899 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, getConfig()) != NO_ERROR)
3900 && (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, getConfig()) != NO_ERROR)) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003901#endif
3902 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003903 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01003904 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003905}
3906
3907status_t AudioPolicyManager::initialize() {
3908 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01003909
3910 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003911 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3912 if (!engineInstance) {
3913 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003914 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003915 }
3916 // Retrieve the Policy Manager Interface
3917 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3918 if (mEngine == NULL) {
3919 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003920 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003921 }
3922 mEngine->setObserver(this);
3923 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003924 if (status != NO_ERROR) {
3925 LOG_FATAL("Policy engine not initialized(err=%d)", status);
3926 return status;
3927 }
François Gaffie2110e042015-03-24 08:41:51 +01003928
Eric Laurent3a4311c2014-03-17 12:00:47 -07003929 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003930 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003931 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3932 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Mikhail Naganovd4120142017-12-06 15:49:22 -08003933 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003934 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08003935 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
3936 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003937 continue;
3938 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08003939 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07003940 // open all output streams needed to access attached devices
3941 // except for direct output streams that are only opened when they are actually
3942 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003943 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003944 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003945 if (!outProfile->canOpenNewIo()) {
3946 ALOGE("Invalid Output profile max open count %u for profile %s",
3947 outProfile->maxOpenCount, outProfile->getTagName().c_str());
3948 continue;
3949 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003950 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003951 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003952 continue;
3953 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003954 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003955 mTtsOutputAvailable = true;
3956 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003957
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003958 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003959 continue;
3960 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003961 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003962 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3963 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003964 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003965 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003966 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003967 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003968 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003969 if ((profileType & outputDeviceTypes) == 0) {
3970 continue;
3971 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003972 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3973 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003974 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov708e0382018-05-30 09:53:04 -07003975 const DeviceVector &devicesForType = supportedDevices.getDevicesFromTypeMask(
3976 profileType);
Eric Laurentc40d9692016-04-13 19:14:13 -07003977 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3978 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003979 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08003980 status_t status = outputDesc->open(nullptr, profileType, address,
3981 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07003982
3983 if (status != NO_ERROR) {
3984 ALOGW("Cannot open output stream for device %08x on hw module %s",
3985 outputDesc->mDevice,
Mikhail Naganovd4120142017-12-06 15:49:22 -08003986 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003987 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003988 for (const auto& dev : supportedDevices) {
3989 ssize_t index = mAvailableOutputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07003990 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003991 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003992 mAvailableOutputDevices[index]->attach(hwModule);
Eric Laurentd78f1532014-09-16 16:38:20 -07003993 }
3994 }
3995 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003996 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003997 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003998 }
3999 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07004000 setOutputDevice(outputDesc,
Eric Laurentfe231122017-11-17 17:48:06 -08004001 profileType,
Eric Laurentc40d9692016-04-13 19:14:13 -07004002 true,
4003 0,
4004 NULL,
Eric Laurentfe231122017-11-17 17:48:06 -08004005 address);
Eric Laurentd78f1532014-09-16 16:38:20 -07004006 }
Eric Laurente552edb2014-03-10 17:42:56 -07004007 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004008 // open input streams needed to access attached devices to validate
4009 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004010 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004011 if (!inProfile->canOpenNewIo()) {
4012 ALOGE("Invalid Input profile max open count %u for profile %s",
4013 inProfile->maxOpenCount, inProfile->getTagName().c_str());
4014 continue;
4015 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004016 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004017 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004018 continue;
4019 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004020 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07004021 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004022 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
4023
Eric Laurentd78f1532014-09-16 16:38:20 -07004024 if ((profileType & inputDeviceTypes) == 0) {
4025 continue;
4026 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08004027 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08004028 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004029
Mikhail Naganov708e0382018-05-30 09:53:04 -07004030 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(profileType);
Eric Laurent53b810e2017-12-10 17:25:10 -08004031 // the inputs vector must be of size >= 1, but we don't want to crash here
4032 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
4033 : String8("");
4034 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
4035 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
4036
Eric Laurentd78f1532014-09-16 16:38:20 -07004037 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004038 status_t status = inputDesc->open(nullptr,
4039 profileType,
Eric Laurent53b810e2017-12-10 17:25:10 -08004040 address,
Eric Laurentfe231122017-11-17 17:48:06 -08004041 AUDIO_SOURCE_MIC,
4042 AUDIO_INPUT_FLAG_NONE,
4043 &input);
Eric Laurentd78f1532014-09-16 16:38:20 -07004044
4045 if (status == NO_ERROR) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004046 for (const auto& dev : inProfile->getSupportedDevices()) {
4047 ssize_t index = mAvailableInputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07004048 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07004049 if (index >= 0) {
4050 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
4051 if (!devDesc->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004052 devDesc->attach(hwModule);
Eric Laurent83efe1c2017-07-09 16:51:08 -07004053 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07004054 }
Eric Laurentd78f1532014-09-16 16:38:20 -07004055 }
4056 }
Eric Laurentfe231122017-11-17 17:48:06 -08004057 inputDesc->close();
Eric Laurentd78f1532014-09-16 16:38:20 -07004058 } else {
4059 ALOGW("Cannot open input stream for device %08x on hw module %s",
Eric Laurentfe231122017-11-17 17:48:06 -08004060 profileType,
Mikhail Naganovd4120142017-12-06 15:49:22 -08004061 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07004062 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004063 }
4064 }
4065 // make sure all attached devices have been allocated a unique ID
4066 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004067 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004068 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004069 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
4070 continue;
4071 }
François Gaffie2110e042015-03-24 08:41:51 +01004072 // The device is now validated and can be appended to the available devices of the engine
4073 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
4074 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004075 i++;
4076 }
4077 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004078 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01004079 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004080 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
4081 continue;
4082 }
François Gaffie2110e042015-03-24 08:41:51 +01004083 // The device is now validated and can be appended to the available devices of the engine
4084 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
4085 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004086 i++;
4087 }
4088 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004089 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01004090 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004091 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004092 }
jiabin9ff780e2018-03-19 18:19:52 -07004093 // If microphones address is empty, set it according to device type
4094 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
4095 if (mAvailableInputDevices[i]->mAddress.isEmpty()) {
4096 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
4097 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
4098 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
4099 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BACK_MICROPHONE_ADDRESS);
4100 }
4101 }
4102 }
Eric Laurente552edb2014-03-10 17:42:56 -07004103
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004104 if (mPrimaryOutput == 0) {
4105 ALOGE("Failed to open primary output");
4106 status = NO_INIT;
4107 }
Eric Laurente552edb2014-03-10 17:42:56 -07004108
4109 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004110 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004111}
4112
Eric Laurente0720872014-03-11 09:30:41 -07004113AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004114{
Eric Laurente552edb2014-03-10 17:42:56 -07004115 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004116 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004117 }
4118 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004119 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004120 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004121 mAvailableOutputDevices.clear();
4122 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004123 mOutputs.clear();
4124 mInputs.clear();
4125 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004126 mHwModulesAll.clear();
jiabin81772902018-04-02 17:52:27 -07004127 mSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004128}
4129
Eric Laurente0720872014-03-11 09:30:41 -07004130status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004131{
Eric Laurent87ffa392015-05-22 10:32:38 -07004132 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004133}
4134
Eric Laurente552edb2014-03-10 17:42:56 -07004135// ---
4136
Eric Laurent98e38192018-02-15 18:31:53 -08004137void AudioPolicyManager::addOutput(audio_io_handle_t output,
4138 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004139{
Eric Laurent1c333e22014-05-20 10:48:17 -07004140 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08004141 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004142 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004143 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004144 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004145}
4146
François Gaffie53615e22015-03-19 09:24:12 +01004147void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4148{
4149 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004150 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004151}
4152
Eric Laurent98e38192018-02-15 18:31:53 -08004153void AudioPolicyManager::addInput(audio_io_handle_t input,
4154 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004155{
Eric Laurent1c333e22014-05-20 10:48:17 -07004156 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004157 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004158}
Eric Laurente552edb2014-03-10 17:42:56 -07004159
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004160void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08004161 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004162 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004163 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08004164 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004165 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08004166 if (devDesc != 0) {
4167 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
4168 desc->mIoHandle, address.string());
4169 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004170 }
4171}
4172
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004173status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004174 audio_policy_dev_state_t state,
4175 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004176 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07004177{
François Gaffie53615e22015-03-19 09:24:12 +01004178 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07004179 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004180
4181 if (audio_device_is_digital(device)) {
4182 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004183 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004184 }
Eric Laurente552edb2014-03-10 17:42:56 -07004185
Eric Laurent3b73df72014-03-11 09:06:29 -07004186 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004187 // first list already open outputs that can be routed to this device
4188 for (size_t i = 0; i < mOutputs.size(); i++) {
4189 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07004190 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004191 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004192 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
4193 outputs.add(mOutputs.keyAt(i));
4194 } else {
4195 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08004196 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004197 }
Eric Laurente552edb2014-03-10 17:42:56 -07004198 }
4199 }
4200 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004201 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004202 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004203 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4204 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004205 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004206 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004207 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004208 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004209 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4210 j, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004211 }
Eric Laurente552edb2014-03-10 17:42:56 -07004212 }
4213 }
4214 }
4215
Eric Laurent7b279bb2015-12-14 10:18:23 -08004216 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004217
Eric Laurente552edb2014-03-10 17:42:56 -07004218 if (profiles.isEmpty() && outputs.isEmpty()) {
4219 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4220 return BAD_VALUE;
4221 }
4222
4223 // open outputs for matching profiles if needed. Direct outputs are also opened to
4224 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4225 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004226 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004227
4228 // nothing to do if one output is already opened for this profile
4229 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004230 for (j = 0; j < outputs.size(); j++) {
4231 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004232 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004233 // matching profile: save the sample rates, format and channel masks supported
4234 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07004235 if (audio_device_is_digital(device)) {
4236 devDesc->importAudioPort(profile);
4237 }
Eric Laurente552edb2014-03-10 17:42:56 -07004238 break;
4239 }
4240 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004241 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004242 continue;
4243 }
4244
Eric Laurent3974e3b2017-12-07 17:58:43 -08004245 if (!profile->canOpenNewIo()) {
4246 ALOGW("Max Output number %u already opened for this profile %s",
4247 profile->maxOpenCount, profile->getTagName().c_str());
4248 continue;
4249 }
4250
Eric Laurent83efe1c2017-07-09 16:51:08 -07004251 ALOGV("opening output for device %08x with params %s profile %p name %s",
4252 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004253 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004254 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004255 status_t status = desc->open(nullptr, device, address,
4256 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004257
Eric Laurentfe231122017-11-17 17:48:06 -08004258 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004259 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004260 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004261 char *param = audio_device_address_to_parameter(device, address);
4262 mpClientInterface->setParameters(output, String8(param));
4263 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004264 }
Phil Burk00eeb322016-03-31 12:41:00 -07004265 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004266 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004267 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004268 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004269 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004270 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004271 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004272 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004273 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4274 profile->pickAudioProfile(
4275 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004276 config.offload_info.sample_rate = config.sample_rate;
4277 config.offload_info.channel_mask = config.channel_mask;
4278 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004279
4280 status_t status = desc->open(&config, device, address, AUDIO_STREAM_DEFAULT,
4281 AUDIO_OUTPUT_FLAG_NONE, &output);
4282 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004283 output = AUDIO_IO_HANDLE_NONE;
4284 }
Eric Laurentd4692962014-05-05 18:13:44 -07004285 }
4286
Eric Laurentcf2c0212014-07-25 16:20:43 -07004287 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004288 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01004289 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004290 sp<AudioPolicyMix> policyMix;
4291 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004292 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
4293 address.string());
4294 }
François Gaffie036e1e92015-03-19 10:16:24 +01004295 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07004296 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01004297
Eric Laurent87ffa392015-05-22 10:32:38 -07004298 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4299 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004300 // no duplicated output for direct outputs and
4301 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004302 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004303
Eric Laurentd4692962014-05-05 18:13:44 -07004304 //TODO: configure audio effect output stage here
4305
4306 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004307 sp<SwAudioOutputDescriptor> dupOutputDesc =
4308 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4309 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4310 &duplicatedOutput);
4311 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004312 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004313 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004314 } else {
4315 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004316 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004317 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004318 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004319 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004320 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004321 }
Eric Laurente552edb2014-03-10 17:42:56 -07004322 }
4323 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004324 } else {
4325 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004326 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004327 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004328 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004329 profiles.removeAt(profile_index);
4330 profile_index--;
4331 } else {
4332 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004333 // Load digital format info only for digital devices
4334 if (audio_device_is_digital(device)) {
4335 devDesc->importAudioPort(profile);
4336 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004337
François Gaffie53615e22015-03-19 09:24:12 +01004338 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004339 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4340 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004341 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004342 NULL/*patch handle*/, address.string());
4343 }
Eric Laurente552edb2014-03-10 17:42:56 -07004344 ALOGV("checkOutputsForDevice(): adding output %d", output);
4345 }
4346 }
4347
4348 if (profiles.isEmpty()) {
4349 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4350 return BAD_VALUE;
4351 }
Eric Laurentd4692962014-05-05 18:13:44 -07004352 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004353 // check if one opened output is not needed any more after disconnecting one device
4354 for (size_t i = 0; i < mOutputs.size(); i++) {
4355 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004356 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004357 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004358 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004359 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004360 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004361 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004362 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4363 mOutputs.keyAt(i));
4364 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004365 }
Eric Laurente552edb2014-03-10 17:42:56 -07004366 }
4367 }
Eric Laurentd4692962014-05-05 18:13:44 -07004368 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004369 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004370 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4371 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004372 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004373 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004374 "clearing direct output profile %zu on module %s",
4375 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004376 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004377 }
4378 }
4379 }
4380 }
4381 return NO_ERROR;
4382}
4383
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004384status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004385 audio_policy_dev_state_t state,
4386 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004387 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004388{
Paul McLean9080a4c2015-06-18 08:24:02 -07004389 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004390 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004391
4392 if (audio_device_is_digital(device)) {
4393 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004394 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004395 }
4396
Eric Laurentd4692962014-05-05 18:13:44 -07004397 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4398 // first list already open inputs that can be routed to this device
4399 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4400 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004401 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004402 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4403 inputs.add(mInputs.keyAt(input_index));
4404 }
4405 }
4406
4407 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004408 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004409 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004410 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004411 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004412 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004413 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004414
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004415 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004416 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004417 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004418 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004419 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4420 profile_index, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004421 }
Eric Laurentd4692962014-05-05 18:13:44 -07004422 }
4423 }
4424 }
4425
4426 if (profiles.isEmpty() && inputs.isEmpty()) {
4427 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4428 return BAD_VALUE;
4429 }
4430
4431 // open inputs for matching profiles if needed. Direct inputs are also opened to
4432 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4433 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4434
Eric Laurent1c333e22014-05-20 10:48:17 -07004435 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004436
Eric Laurentd4692962014-05-05 18:13:44 -07004437 // nothing to do if one input is already opened for this profile
4438 size_t input_index;
4439 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4440 desc = mInputs.valueAt(input_index);
4441 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004442 if (audio_device_is_digital(device)) {
4443 devDesc->importAudioPort(profile);
4444 }
Eric Laurentd4692962014-05-05 18:13:44 -07004445 break;
4446 }
4447 }
4448 if (input_index != mInputs.size()) {
4449 continue;
4450 }
4451
Eric Laurent3974e3b2017-12-07 17:58:43 -08004452 if (!profile->canOpenNewIo()) {
4453 ALOGW("Max Input number %u already opened for this profile %s",
4454 profile->maxOpenCount, profile->getTagName().c_str());
4455 continue;
4456 }
4457
Eric Laurentfe231122017-11-17 17:48:06 -08004458 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004459 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004460 status_t status = desc->open(nullptr,
4461 device,
4462 address,
4463 AUDIO_SOURCE_MIC,
4464 AUDIO_INPUT_FLAG_NONE,
4465 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004466
Eric Laurentcf2c0212014-07-25 16:20:43 -07004467 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004468 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004469 char *param = audio_device_address_to_parameter(device, address);
4470 mpClientInterface->setParameters(input, String8(param));
4471 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004472 }
Phil Burk00eeb322016-03-31 12:41:00 -07004473 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004474 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004475 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004476 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004477 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004478 }
4479
4480 if (input != 0) {
4481 addInput(input, desc);
4482 }
4483 } // endif input != 0
4484
Eric Laurentcf2c0212014-07-25 16:20:43 -07004485 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004486 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004487 profiles.removeAt(profile_index);
4488 profile_index--;
4489 } else {
4490 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004491 if (audio_device_is_digital(device)) {
4492 devDesc->importAudioPort(profile);
4493 }
Eric Laurentd4692962014-05-05 18:13:44 -07004494 ALOGV("checkInputsForDevice(): adding input %d", input);
4495 }
4496 } // end scan profiles
4497
4498 if (profiles.isEmpty()) {
4499 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4500 return BAD_VALUE;
4501 }
4502 } else {
4503 // Disconnect
4504 // check if one opened input is not needed any more after disconnecting one device
4505 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4506 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004507 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004508 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4509 mInputs.keyAt(input_index));
4510 inputs.add(mInputs.keyAt(input_index));
4511 }
4512 }
4513 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004514 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004515 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004516 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004517 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004518 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004519 if (profile->supportDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004520 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4521 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004522 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004523 }
4524 }
4525 }
4526 } // end disconnect
4527
4528 return NO_ERROR;
4529}
4530
4531
Eric Laurente0720872014-03-11 09:30:41 -07004532void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004533{
4534 ALOGV("closeOutput(%d)", output);
4535
Eric Laurentc75307b2015-03-17 15:29:32 -07004536 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004537 if (outputDesc == NULL) {
4538 ALOGW("closeOutput() unknown output %d", output);
4539 return;
4540 }
François Gaffie036e1e92015-03-19 10:16:24 +01004541 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004542
Eric Laurente552edb2014-03-10 17:42:56 -07004543 // look for duplicated outputs connected to the output being removed.
4544 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004545 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004546 if (dupOutputDesc->isDuplicated() &&
4547 (dupOutputDesc->mOutput1 == outputDesc ||
4548 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004549 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004550 if (dupOutputDesc->mOutput1 == outputDesc) {
4551 outputDesc2 = dupOutputDesc->mOutput2;
4552 } else {
4553 outputDesc2 = dupOutputDesc->mOutput1;
4554 }
4555 // As all active tracks on duplicated output will be deleted,
4556 // and as they were also referenced on the other output, the reference
4557 // count for their stream type must be adjusted accordingly on
4558 // the other output.
Eric Laurent733ce942017-12-07 12:18:25 -08004559 bool wasActive = outputDesc2->isActive();
Eric Laurent3b73df72014-03-11 09:06:29 -07004560 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004561 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07004562 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004563 }
Eric Laurent733ce942017-12-07 12:18:25 -08004564 // stop() will be a no op if the output is still active but is needed in case all
4565 // active streams refcounts where cleared above
4566 if (wasActive) {
4567 outputDesc2->stop();
4568 }
Eric Laurente552edb2014-03-10 17:42:56 -07004569 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4570 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4571
4572 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004573 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004574 }
4575 }
4576
Eric Laurent05b90f82014-08-27 15:32:29 -07004577 nextAudioPortGeneration();
4578
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004579 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004580 if (index >= 0) {
4581 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004582 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004583 mAudioPatches.removeItemsAt(index);
4584 mpClientInterface->onAudioPatchListUpdate();
4585 }
4586
Eric Laurentfe231122017-11-17 17:48:06 -08004587 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004588
François Gaffie53615e22015-03-19 09:24:12 +01004589 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004590 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004591}
4592
4593void AudioPolicyManager::closeInput(audio_io_handle_t input)
4594{
4595 ALOGV("closeInput(%d)", input);
4596
4597 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4598 if (inputDesc == NULL) {
4599 ALOGW("closeInput() unknown input %d", input);
4600 return;
4601 }
4602
Eric Laurent6a94d692014-05-20 11:18:06 -07004603 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004604
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004605 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004606 if (index >= 0) {
4607 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004608 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004609 mAudioPatches.removeItemsAt(index);
4610 mpClientInterface->onAudioPatchListUpdate();
4611 }
4612
Eric Laurentfe231122017-11-17 17:48:06 -08004613 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004614 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004615}
4616
Eric Laurentc75307b2015-03-17 15:29:32 -07004617SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4618 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004619 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004620{
4621 SortedVector<audio_io_handle_t> outputs;
4622
4623 ALOGVV("getOutputsForDevice() device %04x", device);
4624 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004625 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004626 i, openOutputs.valueAt(i)->isDuplicated(),
4627 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004628 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4629 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4630 outputs.add(openOutputs.keyAt(i));
4631 }
4632 }
4633 return outputs;
4634}
4635
Eric Laurente0720872014-03-11 09:30:41 -07004636bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
François Gaffie53615e22015-03-19 09:24:12 +01004637 SortedVector<audio_io_handle_t>& outputs2)
Eric Laurente552edb2014-03-10 17:42:56 -07004638{
4639 if (outputs1.size() != outputs2.size()) {
4640 return false;
4641 }
4642 for (size_t i = 0; i < outputs1.size(); i++) {
4643 if (outputs1[i] != outputs2[i]) {
4644 return false;
4645 }
4646 }
4647 return true;
4648}
4649
Eric Laurente0720872014-03-11 09:30:41 -07004650void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004651{
4652 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4653 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4654 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4655 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4656
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004657 // also take into account external policy-related changes: add all outputs which are
4658 // associated with policies in the "before" and "after" output vectors
4659 ALOGVV("checkOutputForStrategy(): policy related outputs");
4660 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004661 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004662 if (desc != 0 && desc->mPolicyMix != NULL) {
4663 srcOutputs.add(desc->mIoHandle);
4664 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4665 }
4666 }
4667 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004668 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004669 if (desc != 0 && desc->mPolicyMix != NULL) {
4670 dstOutputs.add(desc->mIoHandle);
4671 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4672 }
4673 }
4674
Eric Laurente552edb2014-03-10 17:42:56 -07004675 if (!vectorsEqual(srcOutputs,dstOutputs)) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004676 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4677 // audio from invalidated tracks will be rendered when unmuting
4678 uint32_t maxLatency = 0;
4679 for (audio_io_handle_t srcOut : srcOutputs) {
4680 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4681 if (desc != 0 && maxLatency < desc->latency()) {
4682 maxLatency = desc->latency();
4683 }
4684 }
Eric Laurente552edb2014-03-10 17:42:56 -07004685 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4686 strategy, srcOutputs[0], dstOutputs[0]);
4687 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004688 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004689 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4690 if (desc != 0 && isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004691 setStrategyMute(strategy, true, desc);
Eric Laurentac3a6902018-05-11 16:39:10 -07004692 setStrategyMute(strategy, false, desc, maxLatency * LATENCY_MUTE_FACTOR, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004693 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004694 sp<AudioSourceDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004695 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004696 if (source != 0){
4697 connectAudioSource(source);
4698 }
Eric Laurente552edb2014-03-10 17:42:56 -07004699 }
4700
4701 // Move effects associated to this strategy from previous output to new output
4702 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004703 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004704 }
4705 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004706 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004707 if (getStrategy((audio_stream_type_t)i) == strategy) {
4708 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004709 }
4710 }
4711 }
4712}
4713
Eric Laurente0720872014-03-11 09:30:41 -07004714void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004715{
François Gaffie2110e042015-03-24 08:41:51 +01004716 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004717 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004718 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004719 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004720 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004721 checkOutputForStrategy(STRATEGY_SONIFICATION);
4722 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004723 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004724 checkOutputForStrategy(STRATEGY_MEDIA);
4725 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004726 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004727}
4728
Eric Laurente0720872014-03-11 09:30:41 -07004729void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004730{
François Gaffie53615e22015-03-19 09:24:12 +01004731 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004732 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004733 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004734 return;
4735 }
4736
Eric Laurent3a4311c2014-03-17 12:00:47 -07004737 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004738 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4739 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4740 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004741
4742 // if suspended, restore A2DP output if:
4743 // ((SCO device is NOT connected) ||
4744 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4745 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004746 //
Eric Laurentf732e072016-08-03 19:30:28 -07004747 // if not suspended, suspend A2DP output if:
4748 // (SCO device is connected) &&
4749 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4750 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004751 //
4752 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004753 if (!isScoConnected ||
4754 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4755 AUDIO_POLICY_FORCE_BT_SCO) &&
4756 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4757 AUDIO_POLICY_FORCE_BT_SCO) &&
4758 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004759 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004760
4761 mpClientInterface->restoreOutput(a2dpOutput);
4762 mA2dpSuspended = false;
4763 }
4764 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004765 if (isScoConnected &&
4766 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4767 AUDIO_POLICY_FORCE_BT_SCO) ||
4768 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4769 AUDIO_POLICY_FORCE_BT_SCO) ||
4770 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004771 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004772
4773 mpClientInterface->suspendOutput(a2dpOutput);
4774 mA2dpSuspended = true;
4775 }
4776 }
4777}
4778
Eric Laurentc75307b2015-03-17 15:29:32 -07004779audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4780 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004781{
4782 audio_devices_t device = AUDIO_DEVICE_NONE;
4783
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004784 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004785 if (index >= 0) {
4786 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4787 if (patchDesc->mUid != mUidCached) {
4788 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004789 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004790 return outputDesc->device();
4791 }
4792 }
4793
Eric Laurentf3a5a602018-05-22 18:42:55 -07004794 // Check if an explicit routing request exists for an active stream on this output and
4795 // use it in priority before any other rule
4796 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
4797 if (outputDesc->isStreamActive((audio_stream_type_t)stream)) {
4798 audio_devices_t forcedDevice =
4799 mOutputRoutes.getActiveDeviceForStream(
4800 (audio_stream_type_t)stream, mAvailableOutputDevices);
4801
4802 if (forcedDevice != AUDIO_DEVICE_NONE) {
4803 return forcedDevice;
4804 }
4805 }
4806 }
4807
Eric Laurente552edb2014-03-10 17:42:56 -07004808 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004809 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004810 // use device for strategy enforced audible
4811 // 2: we are in call or the strategy phone is active on the output:
4812 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004813 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004814 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004815 // 4: the strategy for enforced audible is active but not enforced on the output:
4816 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004817 // 5: the strategy accessibility is active on the output:
4818 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004819 // 6: the strategy "respectful" sonification is active on the output:
4820 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004821 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004822 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004823 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004824 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004825 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004826 // use device for strategy t-t-s
Eric Laurent484e9272018-06-07 17:29:23 -07004827
4828 // FIXME: extend use of isStrategyActiveOnSameModule() to all strategies
4829 // with a refined rule considering mutually exclusive devices (using same backend)
4830 // as opposed to all streams on the same audio HAL module.
François Gaffiead3183e2015-03-18 16:55:35 +01004831 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004832 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004833 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4834 } else if (isInCall() ||
Eric Laurent484e9272018-06-07 17:29:23 -07004835 isStrategyActiveOnSameModule(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004836 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004837 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004838 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004839 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
4840 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004841 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4842 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004843 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004844 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004845 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004846 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004847 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004848 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004849 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004850 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004851 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004852 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004853 }
4854
Eric Laurent1c333e22014-05-20 10:48:17 -07004855 ALOGV("getNewOutputDevice() selected device %x", device);
4856 return device;
4857}
4858
Eric Laurentfb66dd92016-01-28 18:32:03 -08004859audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004860{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004861 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004862
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004863 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004864 if (index >= 0) {
4865 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4866 if (patchDesc->mUid != mUidCached) {
4867 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004868 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004869 return inputDesc->mDevice;
4870 }
4871 }
4872
Eric Laurentdc95a252018-04-12 12:46:56 -07004873 // If we are not in call and no client is active on this input, this methods returns
4874 // AUDIO_DEVICE_NONE, causing the patch on the input stream to be released.
Eric Laurentfb66dd92016-01-28 18:32:03 -08004875 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
Eric Laurentdc95a252018-04-12 12:46:56 -07004876 if (source == AUDIO_SOURCE_DEFAULT && isInCall()) {
4877 source = AUDIO_SOURCE_VOICE_COMMUNICATION;
4878 }
4879 if (source != AUDIO_SOURCE_DEFAULT) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08004880 device = getDeviceAndMixForInputSource(source);
4881 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004882
Eric Laurente552edb2014-03-10 17:42:56 -07004883 return device;
4884}
4885
Eric Laurent794fde22016-03-11 09:50:45 -08004886bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4887 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004888 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004889}
4890
Eric Laurente0720872014-03-11 09:30:41 -07004891uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004892 return (uint32_t)getStrategy(stream);
4893}
4894
Eric Laurente0720872014-03-11 09:30:41 -07004895audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004896 // By checking the range of stream before calling getStrategy, we avoid
4897 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4898 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004899 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004900 return AUDIO_DEVICE_NONE;
4901 }
Eric Laurent28d09f02016-03-08 10:43:05 -08004902 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004903 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4904 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004905 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004906 }
Eric Laurent794fde22016-03-11 09:50:45 -08004907 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004908 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004909 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004910 for (audio_io_handle_t output : getOutputsForDevice(curDevices, mOutputs)) {
4911 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08004912 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004913 curDevices |= outputDesc->device();
4914 }
4915 }
4916 devices |= curDevices;
Eric Laurente552edb2014-03-10 17:42:56 -07004917 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004918
4919 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4920 and doesn't really need to.*/
4921 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4922 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4923 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4924 }
Eric Laurente552edb2014-03-10 17:42:56 -07004925 return devices;
4926}
4927
François Gaffie2110e042015-03-24 08:41:51 +01004928routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4929{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004930 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004931 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004932}
4933
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004934uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4935 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004936 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4937 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4938 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004939 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4940 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4941 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004942 // usage to strategy mapping
François Gaffie2110e042015-03-24 08:41:51 +01004943 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004944}
4945
Eric Laurente0720872014-03-11 09:30:41 -07004946void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004947 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004948 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004949 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4950 updateDevicesAndOutputs();
4951 break;
4952 default:
4953 break;
4954 }
4955}
4956
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004957uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004958
4959 // skip beacon mute management if a dedicated TTS output is available
4960 if (mTtsOutputAvailable) {
4961 return 0;
4962 }
4963
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004964 switch(event) {
4965 case STARTING_OUTPUT:
4966 mBeaconMuteRefCount++;
4967 break;
4968 case STOPPING_OUTPUT:
4969 if (mBeaconMuteRefCount > 0) {
4970 mBeaconMuteRefCount--;
4971 }
4972 break;
4973 case STARTING_BEACON:
4974 mBeaconPlayingRefCount++;
4975 break;
4976 case STOPPING_BEACON:
4977 if (mBeaconPlayingRefCount > 0) {
4978 mBeaconPlayingRefCount--;
4979 }
4980 break;
4981 }
4982
4983 if (mBeaconMuteRefCount > 0) {
4984 // any playback causes beacon to be muted
4985 return setBeaconMute(true);
4986 } else {
4987 // no other playback: unmute when beacon starts playing, mute when it stops
4988 return setBeaconMute(mBeaconPlayingRefCount == 0);
4989 }
4990}
4991
4992uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4993 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4994 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4995 // keep track of muted state to avoid repeating mute/unmute operations
4996 if (mBeaconMuted != mute) {
4997 // mute/unmute AUDIO_STREAM_TTS on all outputs
4998 ALOGV("\t muting %d", mute);
4999 uint32_t maxLatency = 0;
5000 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005001 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005002 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07005003 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005004 0 /*delay*/, AUDIO_DEVICE_NONE);
5005 const uint32_t latency = desc->latency() * 2;
5006 if (latency > maxLatency) {
5007 maxLatency = latency;
5008 }
5009 }
5010 mBeaconMuted = mute;
5011 return maxLatency;
5012 }
5013 return 0;
5014}
5015
Eric Laurente0720872014-03-11 09:30:41 -07005016audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01005017 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005018{
Eric Laurentf3a5a602018-05-22 18:42:55 -07005019 // Check if an explicit routing request exists for a stream type corresponding to the
5020 // specified strategy and use it in priority over default routing rules.
5021 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
5022 if (getStrategy((audio_stream_type_t)stream) == strategy) {
5023 audio_devices_t forcedDevice =
5024 mOutputRoutes.getActiveDeviceForStream(
5025 (audio_stream_type_t)stream, mAvailableOutputDevices);
5026 if (forcedDevice != AUDIO_DEVICE_NONE) {
5027 return forcedDevice;
5028 }
Paul McLeanaa981192015-03-21 09:55:15 -07005029 }
5030 }
5031
Eric Laurente552edb2014-03-10 17:42:56 -07005032 if (fromCache) {
5033 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
5034 strategy, mDeviceForStrategy[strategy]);
5035 return mDeviceForStrategy[strategy];
5036 }
François Gaffie2110e042015-03-24 08:41:51 +01005037 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07005038}
5039
Eric Laurente0720872014-03-11 09:30:41 -07005040void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005041{
5042 for (int i = 0; i < NUM_STRATEGIES; i++) {
5043 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
5044 }
5045 mPreviousOutputs = mOutputs;
5046}
5047
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005048uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005049 audio_devices_t prevDevice,
5050 uint32_t delayMs)
5051{
5052 // mute/unmute strategies using an incompatible device combination
5053 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5054 // if unmuting, unmute only after the specified delay
5055 if (outputDesc->isDuplicated()) {
5056 return 0;
5057 }
5058
5059 uint32_t muteWaitMs = 0;
5060 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07005061 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005062
5063 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
5064 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07005065 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07005066 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
5067 bool doMute = false;
5068
5069 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
5070 doMute = true;
5071 outputDesc->mStrategyMutedByDevice[i] = true;
5072 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
5073 doMute = true;
5074 outputDesc->mStrategyMutedByDevice[i] = false;
5075 }
Eric Laurent99401132014-05-07 19:48:15 -07005076 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005077 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005078 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005079 // skip output if it does not share any device with current output
5080 if ((desc->supportedDevices() & outputDesc->supportedDevices())
5081 == AUDIO_DEVICE_NONE) {
5082 continue;
5083 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005084 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07005085 mute ? "muting" : "unmuting", i, curDevice);
5086 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005087 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005088 if (mute) {
5089 // FIXME: should not need to double latency if volume could be applied
5090 // immediately by the audioflinger mixer. We must account for the delay
5091 // between now and the next time the audioflinger thread for this output
5092 // will process a buffer (which corresponds to one buffer size,
5093 // usually 1/2 or 1/4 of the latency).
5094 if (muteWaitMs < desc->latency() * 2) {
5095 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005096 }
5097 }
5098 }
5099 }
5100 }
5101 }
5102
Eric Laurent99401132014-05-07 19:48:15 -07005103 // temporary mute output if device selection changes to avoid volume bursts due to
5104 // different per device volumes
5105 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005106 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5107 // temporary mute duration is conservatively set to 4 times the reported latency
5108 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5109 if (muteWaitMs < tempMuteWaitMs) {
5110 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005111 }
Eric Laurentdc462862016-07-19 12:29:53 -07005112
Eric Laurent99401132014-05-07 19:48:15 -07005113 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005114 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005115 // make sure that we do not start the temporary mute period too early in case of
5116 // delayed device change
5117 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005118 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07005119 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07005120 }
5121 }
5122 }
5123
Eric Laurente552edb2014-03-10 17:42:56 -07005124 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5125 if (muteWaitMs > delayMs) {
5126 muteWaitMs -= delayMs;
5127 usleep(muteWaitMs * 1000);
5128 return muteWaitMs;
5129 }
5130 return 0;
5131}
5132
Eric Laurentc75307b2015-03-17 15:29:32 -07005133uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005134 audio_devices_t device,
5135 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07005136 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005137 audio_patch_handle_t *patchHandle,
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005138 const char *address,
5139 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005140{
Eric Laurentc75307b2015-03-17 15:29:32 -07005141 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005142 AudioParameter param;
5143 uint32_t muteWaitMs;
5144
5145 if (outputDesc->isDuplicated()) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005146 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs,
5147 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
5148 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs,
5149 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005150 return muteWaitMs;
5151 }
5152 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5153 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07005154 if ((device != AUDIO_DEVICE_NONE) &&
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005155 ((device & outputDesc->supportedDevices()) == AUDIO_DEVICE_NONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005156 return 0;
5157 }
5158
5159 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07005160 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07005161
5162 audio_devices_t prevDevice = outputDesc->mDevice;
5163
Paul McLeanaa981192015-03-21 09:55:15 -07005164 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005165
5166 if (device != AUDIO_DEVICE_NONE) {
5167 outputDesc->mDevice = device;
5168 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005169
5170 // if the outputs are not materially active, there is no need to mute.
5171 if (requiresMuteCheck) {
5172 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
5173 } else {
5174 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5175 muteWaitMs = 0;
5176 }
Eric Laurente552edb2014-03-10 17:42:56 -07005177
5178 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005179 // the requested device is AUDIO_DEVICE_NONE
5180 // OR the requested device is the same as current device
5181 // AND force is not specified
5182 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07005183 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07005184 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
5185 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005186 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005187 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005188 return muteWaitMs;
5189 }
5190
5191 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07005192
Eric Laurente552edb2014-03-10 17:42:56 -07005193 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07005194 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005195 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005196 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07005197 DeviceVector deviceList;
5198 if ((address == NULL) || (strlen(address) == 0)) {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005199 deviceList = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurentc40d9692016-04-13 19:14:13 -07005200 } else {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005201 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
5202 device, String8(address));
5203 if (deviceDesc) deviceList.add(deviceDesc);
Eric Laurentc40d9692016-04-13 19:14:13 -07005204 }
5205
Eric Laurent1c333e22014-05-20 10:48:17 -07005206 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005207 PatchBuilder patchBuilder;
5208 patchBuilder.addSource(outputDesc);
Eric Laurent1c333e22014-05-20 10:48:17 -07005209 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005210 patchBuilder.addSink(deviceList.itemAt(i));
Eric Laurent1c333e22014-05-20 10:48:17 -07005211 }
Mikhail Naganovdc769682018-05-04 15:34:08 -07005212 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005213 }
bryant_liuf5e7e792014-08-19 20:07:05 +08005214
5215 // inform all input as well
5216 for (size_t i = 0; i < mInputs.size(); i++) {
5217 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01005218 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08005219 AudioParameter inputCmd = AudioParameter();
5220 ALOGV("%s: inform input %d of device:%d", __func__,
5221 inputDescriptor->mIoHandle, device);
5222 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
5223 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
5224 inputCmd.toString(),
5225 delayMs);
5226 }
5227 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005228 }
Eric Laurente552edb2014-03-10 17:42:56 -07005229
5230 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07005231 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005232
5233 return muteWaitMs;
5234}
5235
Eric Laurentc75307b2015-03-17 15:29:32 -07005236status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005237 int delayMs,
5238 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005239{
Eric Laurent6a94d692014-05-20 11:18:06 -07005240 ssize_t index;
5241 if (patchHandle) {
5242 index = mAudioPatches.indexOfKey(*patchHandle);
5243 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005244 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005245 }
5246 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005247 return INVALID_OPERATION;
5248 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005249 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5250 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005251 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005252 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005253 removeAudioPatch(patchDesc->mHandle);
5254 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005255 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005256 return status;
5257}
5258
5259status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5260 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005261 bool force,
5262 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005263{
5264 status_t status = NO_ERROR;
5265
Eric Laurent1f2f2232014-06-02 12:01:23 -07005266 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005267 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5268 inputDesc->mDevice = device;
5269
Mikhail Naganov708e0382018-05-30 09:53:04 -07005270 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005271 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005272 PatchBuilder patchBuilder;
5273 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005274 // AUDIO_SOURCE_HOTWORD is for internal use only:
5275 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07005276 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5277 auto result = usecase;
5278 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5279 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5280 }
5281 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07005282 //only one input device for now
Mikhail Naganovdc769682018-05-04 15:34:08 -07005283 addSource(deviceList.itemAt(0));
5284 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005285 }
5286 }
5287 return status;
5288}
5289
Eric Laurent6a94d692014-05-20 11:18:06 -07005290status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5291 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005292{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005293 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005294 ssize_t index;
5295 if (patchHandle) {
5296 index = mAudioPatches.indexOfKey(*patchHandle);
5297 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005298 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005299 }
5300 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005301 return INVALID_OPERATION;
5302 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005303 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5304 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005305 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005306 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005307 removeAudioPatch(patchDesc->mHandle);
5308 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005309 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005310 return status;
5311}
5312
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005313sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005314 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005315 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005316 audio_format_t& format,
5317 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005318 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005319{
5320 // Choose an input profile based on the requested capture parameters: select the first available
5321 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005322 //
5323 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5324 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005325
Glenn Kasten730b9262018-03-29 15:01:26 -07005326 sp<IOProfile> firstInexact;
5327 uint32_t updatedSamplingRate = 0;
5328 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5329 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005330 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005331 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005332 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005333 //updatedFormat = format;
Eric Laurent275e8e92014-11-30 15:14:47 -08005334 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005335 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005336 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005337 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005338 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005339 &channelMask /*updatedChannelMask*/,
5340 // FIXME ugly cast
5341 (audio_output_flags_t) flags,
5342 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005343 return profile;
5344 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005345 if (firstInexact == nullptr && profile->isCompatibleProfile(device, address,
5346 samplingRate,
5347 &updatedSamplingRate,
5348 format,
5349 &updatedFormat,
5350 channelMask,
5351 &updatedChannelMask,
5352 // FIXME ugly cast
5353 (audio_output_flags_t) flags,
5354 false /*exactMatchRequiredForInputFlags*/)) {
5355 firstInexact = profile;
5356 }
5357
Eric Laurente552edb2014-03-10 17:42:56 -07005358 }
5359 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005360 if (firstInexact != nullptr) {
5361 samplingRate = updatedSamplingRate;
5362 format = updatedFormat;
5363 channelMask = updatedChannelMask;
5364 return firstInexact;
5365 }
Eric Laurente552edb2014-03-10 17:42:56 -07005366 return NULL;
5367}
5368
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005369
5370audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005371 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005372{
François Gaffie036e1e92015-03-19 10:16:24 +01005373 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5374 audio_devices_t selectedDeviceFromMix =
5375 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005376
François Gaffie036e1e92015-03-19 10:16:24 +01005377 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5378 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005379 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005380 return getDeviceForInputSource(inputSource);
5381}
5382
5383audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5384{
Eric Laurentad2e7b92017-09-14 20:06:42 -07005385 // Routing
5386 // Scan the whole RouteMap to see if we have an explicit route:
5387 // if the input source in the RouteMap is the same as the argument above,
5388 // and activity count is non-zero and the device in the route descriptor is available
5389 // then select this device.
Paul McLean466dc8e2015-04-17 13:15:36 -06005390 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
5391 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
Eric Laurent2157f5b2018-04-25 18:33:02 -07005392 if ((inputSource == route->mSource) && route->isActiveOrChanged() &&
Eric Laurentad2e7b92017-09-14 20:06:42 -07005393 (mAvailableInputDevices.indexOf(route->mDeviceDescriptor) >= 0)) {
Paul McLean466dc8e2015-04-17 13:15:36 -06005394 return route->mDeviceDescriptor->type();
5395 }
5396 }
5397
5398 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005399}
5400
Eric Laurente0720872014-03-11 09:30:41 -07005401float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005402 int index,
5403 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005404{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005405 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005406
5407 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5408 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5409 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5410 // the ringtone volume
5411 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5412 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5413 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5414 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5415 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5416 }
5417
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005418 // in-call: always cap volume by voice volume + some low headroom
5419 if ((stream != AUDIO_STREAM_VOICE_CALL) &&
Eric Laurent7731b5a2018-04-06 15:47:22 -07005420 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005421 switch (stream) {
5422 case AUDIO_STREAM_SYSTEM:
5423 case AUDIO_STREAM_RING:
5424 case AUDIO_STREAM_MUSIC:
5425 case AUDIO_STREAM_ALARM:
5426 case AUDIO_STREAM_NOTIFICATION:
5427 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5428 case AUDIO_STREAM_DTMF:
5429 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005430 int voiceVolumeIndex =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005431 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, device);
Eric Laurent7731b5a2018-04-06 15:47:22 -07005432 const float maxVoiceVolDb =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005433 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, device)
Eric Laurent7731b5a2018-04-06 15:47:22 -07005434 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005435 if (volumeDB > maxVoiceVolDb) {
5436 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5437 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5438 volumeDB = maxVoiceVolDb;
5439 }
5440 } break;
5441 default:
5442 break;
5443 }
5444 }
5445
Eric Laurente552edb2014-03-10 17:42:56 -07005446 // if a headset is connected, apply the following rules to ring tones and notifications
5447 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005448 // - always attenuate notifications volume by 6dB
5449 // - attenuate ring tones volume by 6dB unless music is not playing and
5450 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005451 // - if music is playing, always limit the volume to current music volume,
5452 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005453 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005454 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5455 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5456 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005457 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005458 AUDIO_DEVICE_OUT_USB_HEADSET |
5459 AUDIO_DEVICE_OUT_HEARING_AID)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005460 ((stream_strategy == STRATEGY_SONIFICATION)
5461 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005462 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005463 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005464 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005465 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005466 // when the phone is ringing we must consider that music could have been paused just before
5467 // by the music application and behave as if music was active if the last music track was
5468 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005469 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005470 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005471 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005472 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005473 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005474 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5475 musicDevice),
5476 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005477 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5478 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005479 if (volumeDB > minVolDB) {
5480 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005481 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005482 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005483 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5484 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5485 // on A2DP, also ensure notification volume is not too low compared to media when
5486 // intended to be played
5487 if ((volumeDB > -96.0f) &&
5488 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5489 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5490 stream, device,
5491 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5492 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5493 }
5494 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005495 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5496 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005497 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005498 }
5499 }
5500
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005501 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005502}
5503
Eric Laurent3839bc02018-07-10 18:33:34 -07005504int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
5505 audio_stream_type_t srcStream,
5506 audio_stream_type_t dstStream)
5507{
5508 if (srcStream == dstStream) {
5509 return srcIndex;
5510 }
5511 float minSrc = (float)mVolumeCurves->getVolumeIndexMin(srcStream);
5512 float maxSrc = (float)mVolumeCurves->getVolumeIndexMax(srcStream);
5513 float minDst = (float)mVolumeCurves->getVolumeIndexMin(dstStream);
5514 float maxDst = (float)mVolumeCurves->getVolumeIndexMax(dstStream);
5515
5516 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
5517}
5518
Eric Laurente0720872014-03-11 09:30:41 -07005519status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005520 int index,
5521 const sp<AudioOutputDescriptor>& outputDesc,
5522 audio_devices_t device,
5523 int delayMs,
5524 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005525{
Eric Laurente552edb2014-03-10 17:42:56 -07005526 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005527 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005528 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005529 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005530 return NO_ERROR;
5531 }
François Gaffie2110e042015-03-24 08:41:51 +01005532 audio_policy_forced_cfg_t forceUseForComm =
5533 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005534 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005535 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5536 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005537 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005538 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005539 return INVALID_OPERATION;
5540 }
5541
Eric Laurentc75307b2015-03-17 15:29:32 -07005542 if (device == AUDIO_DEVICE_NONE) {
5543 device = outputDesc->device();
5544 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005545
Eric Laurentffbc80f2015-03-18 18:30:19 -07005546 float volumeDb = computeVolume(stream, index, device);
HW Leeda7581e2018-05-22 18:31:34 +08005547 if (outputDesc->isFixedVolume(device) ||
5548 // Force VoIP volume to max for bluetooth SCO
5549 ((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
5550 (device & AUDIO_DEVICE_OUT_ALL_SCO) != 0)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005551 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005552 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005553
Eric Laurentffbc80f2015-03-18 18:30:19 -07005554 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005555
Eric Laurent3b73df72014-03-11 09:06:29 -07005556 if (stream == AUDIO_STREAM_VOICE_CALL ||
5557 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005558 float voiceVolume;
5559 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005560 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurent3839bc02018-07-10 18:33:34 -07005561 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005562 } else {
5563 voiceVolume = 1.0;
5564 }
5565
Eric Laurent18fba842016-03-31 14:41:26 -07005566 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005567 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5568 mLastVoiceVolume = voiceVolume;
5569 }
5570 }
5571
5572 return NO_ERROR;
5573}
5574
Eric Laurentc75307b2015-03-17 15:29:32 -07005575void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5576 audio_devices_t device,
5577 int delayMs,
5578 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005579{
Eric Laurentc75307b2015-03-17 15:29:32 -07005580 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005581
Eric Laurent794fde22016-03-11 09:50:45 -08005582 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005583 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005584 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005585 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005586 device,
5587 delayMs,
5588 force);
5589 }
5590}
5591
Eric Laurente0720872014-03-11 09:30:41 -07005592void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005593 bool on,
5594 const sp<AudioOutputDescriptor>& outputDesc,
5595 int delayMs,
5596 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005597{
Eric Laurent72249d52015-06-08 11:12:15 -07005598 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5599 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005600 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005601 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005602 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005603 }
5604 }
5605}
5606
Eric Laurente0720872014-03-11 09:30:41 -07005607void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005608 bool on,
5609 const sp<AudioOutputDescriptor>& outputDesc,
5610 int delayMs,
5611 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005612{
Eric Laurente552edb2014-03-10 17:42:56 -07005613 if (device == AUDIO_DEVICE_NONE) {
5614 device = outputDesc->device();
5615 }
5616
Eric Laurentc75307b2015-03-17 15:29:32 -07005617 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5618 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005619
5620 if (on) {
5621 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005622 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005623 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005624 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005625 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005626 }
5627 }
5628 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5629 outputDesc->mMuteCount[stream]++;
5630 } else {
5631 if (outputDesc->mMuteCount[stream] == 0) {
5632 ALOGV("setStreamMute() unmuting non muted stream!");
5633 return;
5634 }
5635 if (--outputDesc->mMuteCount[stream] == 0) {
5636 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005637 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005638 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005639 device,
5640 delayMs);
5641 }
5642 }
5643}
5644
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005645audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5646{
5647 // flags to stream type mapping
5648 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5649 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5650 }
5651 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5652 return AUDIO_STREAM_BLUETOOTH_SCO;
5653 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005654 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5655 return AUDIO_STREAM_TTS;
5656 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005657
5658 // usage to stream type mapping
5659 switch (attr->usage) {
5660 case AUDIO_USAGE_MEDIA:
5661 case AUDIO_USAGE_GAME:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005662 case AUDIO_USAGE_ASSISTANT:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005663 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5664 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005665 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5666 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005667 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5668 return AUDIO_STREAM_SYSTEM;
5669 case AUDIO_USAGE_VOICE_COMMUNICATION:
5670 return AUDIO_STREAM_VOICE_CALL;
5671
5672 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5673 return AUDIO_STREAM_DTMF;
5674
5675 case AUDIO_USAGE_ALARM:
5676 return AUDIO_STREAM_ALARM;
5677 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5678 return AUDIO_STREAM_RING;
5679
5680 case AUDIO_USAGE_NOTIFICATION:
5681 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5682 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5683 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5684 case AUDIO_USAGE_NOTIFICATION_EVENT:
5685 return AUDIO_STREAM_NOTIFICATION;
5686
5687 case AUDIO_USAGE_UNKNOWN:
5688 default:
5689 return AUDIO_STREAM_MUSIC;
5690 }
5691}
Eric Laurente83b55d2014-11-14 10:06:21 -08005692
François Gaffie53615e22015-03-19 09:24:12 +01005693bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5694{
Eric Laurente83b55d2014-11-14 10:06:21 -08005695 // has flags that map to a strategy?
5696 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5697 return true;
5698 }
5699
5700 // has known usage?
5701 switch (paa->usage) {
5702 case AUDIO_USAGE_UNKNOWN:
5703 case AUDIO_USAGE_MEDIA:
5704 case AUDIO_USAGE_VOICE_COMMUNICATION:
5705 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5706 case AUDIO_USAGE_ALARM:
5707 case AUDIO_USAGE_NOTIFICATION:
5708 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5709 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5710 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5711 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5712 case AUDIO_USAGE_NOTIFICATION_EVENT:
5713 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5714 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5715 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5716 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005717 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005718 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005719 break;
5720 default:
5721 return false;
5722 }
5723 return true;
5724}
5725
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005726bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005727 routing_strategy strategy, uint32_t inPastMs,
5728 nsecs_t sysTime) const
5729{
5730 if ((sysTime == 0) && (inPastMs != 0)) {
5731 sysTime = systemTime();
5732 }
Eric Laurent794fde22016-03-11 09:50:45 -08005733 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005734 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5735 (NUM_STRATEGIES == strategy)) &&
5736 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5737 return true;
5738 }
5739 }
5740 return false;
5741}
5742
Eric Laurent484e9272018-06-07 17:29:23 -07005743bool AudioPolicyManager::isStrategyActiveOnSameModule(const sp<AudioOutputDescriptor>& outputDesc,
5744 routing_strategy strategy, uint32_t inPastMs,
5745 nsecs_t sysTime) const
5746{
5747 for (size_t i = 0; i < mOutputs.size(); i++) {
5748 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5749 if (outputDesc->sharesHwModuleWith(desc)
5750 && isStrategyActive(desc, strategy, inPastMs, sysTime)) {
5751 return true;
5752 }
5753 }
5754 return false;
5755}
5756
François Gaffie2110e042015-03-24 08:41:51 +01005757audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5758{
5759 return mEngine->getForceUse(usage);
5760}
5761
5762bool AudioPolicyManager::isInCall()
5763{
5764 return isStateInCall(mEngine->getPhoneState());
5765}
5766
5767bool AudioPolicyManager::isStateInCall(int state)
5768{
5769 return is_state_in_call(state);
5770}
5771
Eric Laurentd60560a2015-04-10 11:31:20 -07005772void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5773{
5774 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5775 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
5776 if (sourceDesc->mDevice->equals(deviceDesc)) {
5777 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle());
5778 stopAudioSource(sourceDesc->getHandle());
5779 }
5780 }
5781
5782 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5783 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5784 bool release = false;
5785 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5786 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5787 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5788 source->ext.device.type == deviceDesc->type()) {
5789 release = true;
5790 }
5791 }
5792 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5793 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5794 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5795 sink->ext.device.type == deviceDesc->type()) {
5796 release = true;
5797 }
5798 }
5799 if (release) {
5800 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5801 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5802 }
5803 }
5804}
5805
Phil Burk09bc4612016-02-24 15:58:15 -08005806// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005807void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5808 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005809 // TODO Set this based on Config properties.
5810 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005811
5812 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5813 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005814 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005815
jiabin81772902018-04-02 17:52:27 -07005816 // If MANUAL, keep the supported surround sound formats as current enabled ones.
5817 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
5818 formats.clear();
5819 for (auto it = mSurroundFormats.begin(); it != mSurroundFormats.end(); it++) {
5820 formats.add(*it);
Phil Burk09bc4612016-02-24 15:58:15 -08005821 }
jiabin81772902018-04-02 17:52:27 -07005822 // Always enable IEC61937 when in MANUAL mode.
5823 formats.add(AUDIO_FORMAT_IEC61937);
5824 } else { // NEVER, AUTO or ALWAYS
5825 // Analyze original support for various formats.
5826 bool supportsAC3 = false;
5827 bool supportsOtherSurround = false;
5828 bool supportsIEC61937 = false;
5829 mSurroundFormats.clear();
5830 for (ssize_t formatIndex = 0; formatIndex < (ssize_t)formats.size(); formatIndex++) {
5831 audio_format_t format = formats[formatIndex];
5832 switch (format) {
5833 case AUDIO_FORMAT_AC3:
5834 supportsAC3 = true;
5835 break;
5836 case AUDIO_FORMAT_E_AC3:
5837 case AUDIO_FORMAT_DTS:
5838 case AUDIO_FORMAT_DTS_HD:
5839 // If ALWAYS, remove all other surround formats here
5840 // since we will add them later.
5841 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5842 formats.removeAt(formatIndex);
5843 formatIndex--;
5844 }
5845 supportsOtherSurround = true;
5846 break;
5847 case AUDIO_FORMAT_IEC61937:
5848 supportsIEC61937 = true;
5849 break;
5850 default:
5851 break;
5852 }
5853 }
Phil Burk09bc4612016-02-24 15:58:15 -08005854
jiabin81772902018-04-02 17:52:27 -07005855 // Modify formats based on surround preferences.
5856 // If NEVER, remove support for surround formats.
5857 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5858 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5859 // Remove surround sound related formats.
5860 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5861 audio_format_t format = formats[formatIndex];
5862 switch(format) {
5863 case AUDIO_FORMAT_AC3:
5864 case AUDIO_FORMAT_E_AC3:
5865 case AUDIO_FORMAT_DTS:
5866 case AUDIO_FORMAT_DTS_HD:
5867 case AUDIO_FORMAT_IEC61937:
5868 formats.removeAt(formatIndex);
5869 break;
5870 default:
5871 formatIndex++; // keep it
5872 break;
5873 }
5874 }
5875 supportsAC3 = false;
5876 supportsOtherSurround = false;
5877 supportsIEC61937 = false;
5878 }
5879 } else { // AUTO or ALWAYS
5880 // Most TVs support AC3 even if they do not report it in the EDID.
5881 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
5882 && !supportsAC3) {
5883 formats.add(AUDIO_FORMAT_AC3);
5884 supportsAC3 = true;
5885 }
5886
5887 // If ALWAYS, add support for raw surround formats if all are missing.
5888 // This assumes that if any of these formats are reported by the HAL
5889 // then the report is valid and should not be modified.
5890 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5891 formats.add(AUDIO_FORMAT_E_AC3);
5892 formats.add(AUDIO_FORMAT_DTS);
5893 formats.add(AUDIO_FORMAT_DTS_HD);
5894 supportsOtherSurround = true;
5895 }
5896
5897 // Add support for IEC61937 if any raw surround supported.
5898 // The HAL could do this but add it here, just in case.
5899 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
5900 formats.add(AUDIO_FORMAT_IEC61937);
5901 supportsIEC61937 = true;
5902 }
5903
5904 // Add reported surround sound formats to enabled surround formats.
5905 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
Phil Burk07ac1142016-03-25 13:39:29 -07005906 audio_format_t format = formats[formatIndex];
5907 switch(format) {
5908 case AUDIO_FORMAT_AC3:
5909 case AUDIO_FORMAT_E_AC3:
5910 case AUDIO_FORMAT_DTS:
5911 case AUDIO_FORMAT_DTS_HD:
jiabin81772902018-04-02 17:52:27 -07005912 case AUDIO_FORMAT_AAC_LC:
5913 case AUDIO_FORMAT_DOLBY_TRUEHD:
5914 case AUDIO_FORMAT_E_AC3_JOC:
5915 mSurroundFormats.insert(format);
Phil Burk07ac1142016-03-25 13:39:29 -07005916 default:
Phil Burk07ac1142016-03-25 13:39:29 -07005917 break;
5918 }
Phil Burk09bc4612016-02-24 15:58:15 -08005919 }
Phil Burk07ac1142016-03-25 13:39:29 -07005920 }
Phil Burk09bc4612016-02-24 15:58:15 -08005921 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005922}
5923
5924// Modify the list of channel masks supported.
5925void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
5926 ChannelsVector &channelMasks = *channelMasksPtr;
5927 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5928 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5929
5930 // If NEVER, then remove support for channelMasks > stereo.
5931 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5932 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5933 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5934 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5935 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5936 channelMasks.removeAt(maskIndex);
5937 } else {
5938 maskIndex++;
5939 }
5940 }
jiabin81772902018-04-02 17:52:27 -07005941 // If ALWAYS or MANUAL, then make sure we at least support 5.1
5942 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
5943 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005944 bool supports5dot1 = false;
5945 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005946 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005947 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5948 supports5dot1 = true;
5949 break;
5950 }
5951 }
5952 // If not then add 5.1 support.
5953 if (!supports5dot1) {
5954 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
5955 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
5956 }
Phil Burk09bc4612016-02-24 15:58:15 -08005957 }
5958}
5959
Phil Burk00eeb322016-03-31 12:41:00 -07005960void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
5961 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005962 AudioProfileVector &profiles)
5963{
5964 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07005965
François Gaffie112b0af2015-11-19 16:13:25 +01005966 // Format MUST be checked first to update the list of AudioProfile
5967 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005968 reply = mpClientInterface->getParameters(
5969 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07005970 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005971 AudioParameter repliedParameters(reply);
5972 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005973 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005974 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5975 return;
5976 }
Phil Burk09bc4612016-02-24 15:58:15 -08005977 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07005978 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005979 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005980 }
Phil Burk09bc4612016-02-24 15:58:15 -08005981 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005982 }
François Gaffie112b0af2015-11-19 16:13:25 +01005983
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005984 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08005985 ChannelsVector channelMasks;
5986 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005987 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07005988 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01005989
5990 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005991 reply = mpClientInterface->getParameters(
5992 ioHandle,
5993 requestedParameters.toString() + ";" +
5994 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01005995 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005996 AudioParameter repliedParameters(reply);
5997 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005998 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005999 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01006000 }
6001 }
6002 if (profiles.hasDynamicChannelsFor(format)) {
6003 reply = mpClientInterface->getParameters(ioHandle,
6004 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07006005 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01006006 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006007 AudioParameter repliedParameters(reply);
6008 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006009 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006010 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07006011 if (device == AUDIO_DEVICE_OUT_HDMI) {
6012 filterSurroundChannelMasks(&channelMasks);
6013 }
François Gaffie112b0af2015-11-19 16:13:25 +01006014 }
6015 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08006016 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006017 }
6018}
Eric Laurentd60560a2015-04-10 11:31:20 -07006019
Mikhail Naganovdc769682018-05-04 15:34:08 -07006020status_t AudioPolicyManager::installPatch(const char *caller,
6021 audio_patch_handle_t *patchHandle,
6022 AudioIODescriptorInterface *ioDescriptor,
6023 const struct audio_patch *patch,
6024 int delayMs)
6025{
6026 ssize_t index = mAudioPatches.indexOfKey(
6027 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6028 *patchHandle : ioDescriptor->getPatchHandle());
6029 sp<AudioPatch> patchDesc;
6030 status_t status = installPatch(
6031 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6032 if (status == NO_ERROR) {
6033 ioDescriptor->setPatchHandle(patchDesc->mHandle);
6034 }
6035 return status;
6036}
6037
6038status_t AudioPolicyManager::installPatch(const char *caller,
6039 ssize_t index,
6040 audio_patch_handle_t *patchHandle,
6041 const struct audio_patch *patch,
6042 int delayMs,
6043 uid_t uid,
6044 sp<AudioPatch> *patchDescPtr)
6045{
6046 sp<AudioPatch> patchDesc;
6047 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6048 if (index >= 0) {
6049 patchDesc = mAudioPatches.valueAt(index);
6050 afPatchHandle = patchDesc->mAfPatchHandle;
6051 }
6052
6053 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6054 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6055 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6056 if (status == NO_ERROR) {
6057 if (index < 0) {
6058 patchDesc = new AudioPatch(patch, uid);
6059 addAudioPatch(patchDesc->mHandle, patchDesc);
6060 } else {
6061 patchDesc->mPatch = *patch;
6062 }
6063 patchDesc->mAfPatchHandle = afPatchHandle;
6064 if (patchHandle) {
6065 *patchHandle = patchDesc->mHandle;
6066 }
6067 nextAudioPortGeneration();
6068 mpClientInterface->onAudioPatchListUpdate();
6069 }
6070 if (patchDescPtr) *patchDescPtr = patchDesc;
6071 return status;
6072}
6073
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006074} // namespace android