blob: 958ac3014c1e92948e3d92844c4fddc75f54a1f5 [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 Laurente552edb2014-03-10 17:42:56 -0700554 // if leaving call state, handle special case of active streams
555 // pertaining to sonification strategy see handleIncallSonification()
Eric Laurent63dea1d2015-07-02 17:10:28 -0700556 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700557 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800558 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700559 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700560 }
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800561
Eric Laurent63dea1d2015-07-02 17:10:28 -0700562 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800563 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700564 }
565
François Gaffie2110e042015-03-24 08:41:51 +0100566 /**
567 * Switching to or from incall state or switching between telephony and VoIP lead to force
568 * routing command.
569 */
570 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
571 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700572
573 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700574 checkA2dpSuspend();
575 checkOutputForAllStrategies();
576 updateDevicesAndOutputs();
577
Eric Laurente552edb2014-03-10 17:42:56 -0700578 int delayMs = 0;
579 if (isStateInCall(state)) {
580 nsecs_t sysTime = systemTime();
581 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700582 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700583 // mute media and sonification strategies and delay device switch by the largest
584 // latency of any output where either strategy is active.
585 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100586 if ((isStrategyActive(desc, STRATEGY_MEDIA,
587 SONIFICATION_HEADSET_MUSIC_DELAY,
588 sysTime) ||
589 isStrategyActive(desc, STRATEGY_SONIFICATION,
590 SONIFICATION_HEADSET_MUSIC_DELAY,
591 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700592 (delayMs < (int)desc->latency()*2)) {
593 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700594 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700595 setStrategyMute(STRATEGY_MEDIA, true, desc);
596 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700597 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700598 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
599 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700600 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
601 }
602 }
603
Eric Laurent87ffa392015-05-22 10:32:38 -0700604 if (hasPrimaryOutput()) {
605 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
606 // the device returned is not necessarily reachable via this output
607 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
608 // force routing command to audio hardware when ending call
609 // even if no device change is needed
610 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
611 rxDevice = mPrimaryOutput->device();
612 }
Eric Laurente552edb2014-03-10 17:42:56 -0700613
Eric Laurent87ffa392015-05-22 10:32:38 -0700614 if (state == AUDIO_MODE_IN_CALL) {
615 updateCallRouting(rxDevice, delayMs);
616 } else if (oldState == AUDIO_MODE_IN_CALL) {
617 if (mCallRxPatch != 0) {
618 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
619 mCallRxPatch.clear();
620 }
621 if (mCallTxPatch != 0) {
622 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
623 mCallTxPatch.clear();
624 }
625 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
626 } else {
627 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700628 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700629 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700630
631 // reevaluate routing on all outputs in case tracks have been started during the call
632 for (size_t i = 0; i < mOutputs.size(); i++) {
633 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
634 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
635 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
Yung Ti Suf60c8242018-05-10 18:07:26 +0800636 setOutputDevice(desc, newDevice, (newDevice != AUDIO_DEVICE_NONE), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700637 }
638 }
639
Eric Laurente552edb2014-03-10 17:42:56 -0700640 // if entering in call state, handle special case of active streams
641 // pertaining to sonification strategy see handleIncallSonification()
642 if (isStateInCall(state)) {
643 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800644 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700645 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700646 }
Eric Laurent63dea1d2015-07-02 17:10:28 -0700647
648 // force reevaluating accessibility routing when call starts
649 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700650 }
651
652 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700653 if (state == AUDIO_MODE_RINGTONE &&
654 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700655 mLimitRingtoneVolume = true;
656 } else {
657 mLimitRingtoneVolume = false;
658 }
659}
660
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700661audio_mode_t AudioPolicyManager::getPhoneState() {
662 return mEngine->getPhoneState();
663}
664
Eric Laurente0720872014-03-11 09:30:41 -0700665void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700666 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700667{
François Gaffie2110e042015-03-24 08:41:51 +0100668 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700669 if (config == mEngine->getForceUse(usage)) {
670 return;
671 }
Eric Laurente552edb2014-03-10 17:42:56 -0700672
François Gaffie2110e042015-03-24 08:41:51 +0100673 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
674 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
675 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700676 }
François Gaffie2110e042015-03-24 08:41:51 +0100677 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
678 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
679 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700680
681 // check for device and output changes triggered by new force usage
682 checkA2dpSuspend();
683 checkOutputForAllStrategies();
684 updateDevicesAndOutputs();
Phil Burk09bc4612016-02-24 15:58:15 -0800685
Eric Laurentdc462862016-07-19 12:29:53 -0700686 //FIXME: workaround for truncated touch sounds
687 // to be removed when the problem is handled by system UI
688 uint32_t delayMs = 0;
689 uint32_t waitMs = 0;
690 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
691 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
692 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700693 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700694 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
Eric Laurentdc462862016-07-19 12:29:53 -0700695 waitMs = updateCallRouting(newDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700696 }
Eric Laurente552edb2014-03-10 17:42:56 -0700697 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700698 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
699 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
700 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700701 waitMs = setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE),
702 delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700703 }
Eric Laurente552edb2014-03-10 17:42:56 -0700704 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700705 applyStreamVolumes(outputDesc, newDevice, waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700706 }
707 }
708
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800709 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800710 audio_devices_t newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700711 // Force new input selection if the new device can not be reached via current input
Eric Laurentfb66dd92016-01-28 18:32:03 -0800712 if (activeDesc->mProfile->getSupportedDevices().types() &
713 (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
714 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700715 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800716 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700717 }
Eric Laurente552edb2014-03-10 17:42:56 -0700718 }
Eric Laurente552edb2014-03-10 17:42:56 -0700719}
720
Eric Laurente0720872014-03-11 09:30:41 -0700721void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700722{
723 ALOGV("setSystemProperty() property %s, value %s", property, value);
724}
725
726// Find a direct output profile compatible with the parameters passed, even if the input flags do
727// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800728sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700729 audio_devices_t device,
730 uint32_t samplingRate,
731 audio_format_t format,
732 audio_channel_mask_t channelMask,
733 audio_output_flags_t flags)
734{
Eric Laurent861a6282015-05-18 15:40:16 -0700735 // only retain flags that will drive the direct output profile selection
736 // if explicitly requested
737 static const uint32_t kRelevantFlags =
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700738 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
739 AUDIO_OUTPUT_FLAG_VOIP_RX);
Eric Laurent861a6282015-05-18 15:40:16 -0700740 flags =
741 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
742
743 sp<IOProfile> profile;
744
Mikhail Naganovd4120142017-12-06 15:49:22 -0800745 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800746 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent861a6282015-05-18 15:40:16 -0700747 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700748 samplingRate, NULL /*updatedSamplingRate*/,
749 format, NULL /*updatedFormat*/,
750 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700751 flags)) {
752 continue;
753 }
754 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100755 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700756 continue;
757 }
758 // if several profiles are compatible, give priority to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100759 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700760 continue;
761 }
762 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100763 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700764 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700765 }
Eric Laurente552edb2014-03-10 17:42:56 -0700766 }
767 }
Eric Laurent861a6282015-05-18 15:40:16 -0700768 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700769}
770
Eric Laurentf4e63452017-11-06 19:31:46 +0000771audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700772{
Eric Laurent3b73df72014-03-11 09:06:29 -0700773 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700774 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800775
776 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
777 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
778 // format, flags, etc. This may result in some discrepancy for functions that utilize
779 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
780 // and AudioSystem::getOutputSamplingRate().
781
Eric Laurentf4e63452017-11-06 19:31:46 +0000782 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
783 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
Eric Laurente552edb2014-03-10 17:42:56 -0700784
Eric Laurentf4e63452017-11-06 19:31:46 +0000785 ALOGV("getOutput() stream %d selected device %08x, output %d", stream, device, output);
786 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700787}
788
Eric Laurente83b55d2014-11-14 10:06:21 -0800789status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
790 audio_io_handle_t *output,
791 audio_session_t session,
792 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700793 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800794 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200795 audio_output_flags_t *flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700796 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800797 audio_port_handle_t *portId)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700798{
Eric Laurente83b55d2014-11-14 10:06:21 -0800799 audio_attributes_t attributes;
800 if (attr != NULL) {
801 if (!isValidAttributes(attr)) {
802 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
803 attr->usage, attr->content_type, attr->flags,
804 attr->tags);
805 return BAD_VALUE;
806 }
807 attributes = *attr;
808 } else {
809 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
810 ALOGE("getOutputForAttr(): invalid stream type");
811 return BAD_VALUE;
812 }
813 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700814 }
Eric Laurent20b9ef02016-12-05 11:03:16 -0800815
816 // TODO: check for existing client for this port ID
817 if (*portId == AUDIO_PORT_HANDLE_NONE) {
818 *portId = AudioPort::getNextUniqueId();
819 }
820
Eric Laurentc75307b2015-03-17 15:29:32 -0700821 sp<SwAudioOutputDescriptor> desc;
Jean-Michel Trivie8deced2016-02-11 12:50:39 -0800822 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
François Gaffie036e1e92015-03-19 10:16:24 +0100823 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
Eric Laurent20b9ef02016-12-05 11:03:16 -0800824 if (!audio_has_proportional_frames(config->format)) {
François Gaffie036e1e92015-03-19 10:16:24 +0100825 return BAD_VALUE;
Eric Laurent275e8e92014-11-30 15:14:47 -0800826 }
François Gaffie036e1e92015-03-19 10:16:24 +0100827 *stream = streamTypefromAttributesInt(&attributes);
828 *output = desc->mIoHandle;
829 ALOGV("getOutputForAttr() returns output %d", *output);
830 return NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -0800831 }
832 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
833 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
834 return BAD_VALUE;
835 }
836
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700837 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
838 " session %d selectedDeviceId %d",
839 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700840 session, *selectedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700841
842 *stream = streamTypefromAttributesInt(&attributes);
843
844 // Explicit routing?
845 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -0700846 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800847 deviceDesc = mAvailableOutputDevices.getDeviceFromId(*selectedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700848 }
849 mOutputRoutes.addRoute(session, *stream, SessionRoute::SOURCE_TYPE_NA, deviceDesc, uid);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700850
Eric Laurente83b55d2014-11-14 10:06:21 -0800851 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700852 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700853
Eric Laurente83b55d2014-11-14 10:06:21 -0800854 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200855 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -0700856 }
857
Glenn Kasten49f36ba2017-12-06 13:02:02 -0800858 ALOGV("getOutputForAttr() device 0x%x, sampling rate %d, format %#x, channel mask %#x, "
859 "flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +0200860 device, config->sample_rate, config->format, config->channel_mask, *flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700861
Andy Hungc88b0642018-04-27 15:42:35 -0700862 *output = getOutputForDevice(device, session, *stream, config, flags);
Eric Laurente83b55d2014-11-14 10:06:21 -0800863 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700864 mOutputRoutes.removeRoute(session);
Eric Laurente83b55d2014-11-14 10:06:21 -0800865 return INVALID_OPERATION;
866 }
Paul McLeanaa981192015-03-21 09:55:15 -0700867
Mikhail Naganov708e0382018-05-30 09:53:04 -0700868 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -0700869 *selectedDeviceId = outputDevices.size() > 0 ? outputDevices.itemAt(0)->getId()
870 : AUDIO_PORT_HANDLE_NONE;
871
872 ALOGV(" getOutputForAttr() returns output %d selectedDeviceId %d", *output, *selectedDeviceId);
873
Eric Laurente83b55d2014-11-14 10:06:21 -0800874 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700875}
876
877audio_io_handle_t AudioPolicyManager::getOutputForDevice(
878 audio_devices_t device,
Kevin Rocard169753c2017-03-06 14:18:23 -0800879 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700880 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -0800881 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200882 audio_output_flags_t *flags)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700883{
Andy Hungc88b0642018-04-27 15:42:35 -0700884 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700885 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700886
Eric Laurente552edb2014-03-10 17:42:56 -0700887 // open a direct output if required by specified parameters
888 //force direct flag if offload flag is set: offloading implies a direct output stream
889 // and all common behaviors are driven by checking only the direct flag
890 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +0200891 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
892 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700893 }
Nadav Bar766fb022018-01-07 12:18:03 +0200894 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
895 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -0700896 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800897 // only allow deep buffering for music stream type
898 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +0200899 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700900 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +0200901 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700902 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
903 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +0200904 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800905 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700906 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +0200907 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700908 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Eric Laurentfe231122017-11-17 17:48:06 -0800909 audio_is_linear_pcm(config->format)) {
Nadav Bar766fb022018-01-07 12:18:03 +0200910 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700911 AUDIO_OUTPUT_FLAG_DIRECT);
912 ALOGV("Set VoIP and Direct output flags for PCM format");
Nadav Bar766fb022018-01-07 12:18:03 +0200913 } else if (device == AUDIO_DEVICE_OUT_TELEPHONY_TX &&
914 stream == AUDIO_STREAM_MUSIC &&
915 audio_is_linear_pcm(config->format) &&
916 isInCall()) {
917 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700918 }
Eric Laurente552edb2014-03-10 17:42:56 -0700919
Nadav Bar766fb022018-01-07 12:18:03 +0200920
Eric Laurentb732cf52014-09-24 19:08:21 -0700921 sp<IOProfile> profile;
922
923 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700924 // and not explicitly requested
Nadav Bar766fb022018-01-07 12:18:03 +0200925 if (((*flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Eric Laurentfe231122017-11-17 17:48:06 -0800926 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
927 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
Eric Laurentb732cf52014-09-24 19:08:21 -0700928 goto non_direct_output;
929 }
930
Andy Hung2ddee192015-12-18 17:34:44 -0800931 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
932 // This prevents creating an offloaded track and tearing it down immediately after start
933 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700934 // FIXME: We should check the audio session here but we do not have it in this context.
935 // This may prevent offloading in rare situations where effects are left active by apps
936 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700937
Nadav Bar766fb022018-01-07 12:18:03 +0200938 if (((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800939 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700940 profile = getProfileForDirectOutput(device,
Eric Laurentfe231122017-11-17 17:48:06 -0800941 config->sample_rate,
942 config->format,
943 config->channel_mask,
Nadav Bar766fb022018-01-07 12:18:03 +0200944 (audio_output_flags_t)*flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700945 }
946
Eric Laurent1c333e22014-05-20 10:48:17 -0700947 if (profile != 0) {
Andy Hungc88b0642018-04-27 15:42:35 -0700948 // exclusive outputs for MMAP and Offload are enforced by different session ids.
949 for (size_t i = 0; i < mOutputs.size(); i++) {
950 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
951 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
952 // reuse direct output if currently open by the same client
953 // and configured with same parameters
954 if ((config->sample_rate == desc->mSamplingRate) &&
Andy Hung5659ed52018-04-30 10:31:26 -0700955 (config->format == desc->mFormat) &&
Andy Hungc88b0642018-04-27 15:42:35 -0700956 (config->channel_mask == desc->mChannelMask) &&
957 (session == desc->mDirectClientSession)) {
958 desc->mDirectOpenCount++;
959 ALOGI("getOutputForDevice() reusing direct output %d for session %d",
960 mOutputs.keyAt(i), session);
961 return mOutputs.keyAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700962 }
963 }
964 }
Eric Laurent3974e3b2017-12-07 17:58:43 -0800965
966 if (!profile->canOpenNewIo()) {
967 goto non_direct_output;
Eric Laurente552edb2014-03-10 17:42:56 -0700968 }
Eric Laurent861a6282015-05-18 15:40:16 -0700969
Eric Laurent3974e3b2017-12-07 17:58:43 -0800970 sp<SwAudioOutputDescriptor> outputDesc =
971 new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurent53b810e2017-12-10 17:25:10 -0800972
Mikhail Naganov708e0382018-05-30 09:53:04 -0700973 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -0800974 String8 address = outputDevices.size() > 0 ? outputDevices.itemAt(0)->mAddress
975 : String8("");
976
Nadav Bar766fb022018-01-07 12:18:03 +0200977 status = outputDesc->open(config, device, address, stream, *flags, &output);
Eric Laurente552edb2014-03-10 17:42:56 -0700978
979 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -0700980 if (status != NO_ERROR ||
Eric Laurentfe231122017-11-17 17:48:06 -0800981 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
Andy Hung5659ed52018-04-30 10:31:26 -0700982 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->mFormat) ||
Eric Laurentfe231122017-11-17 17:48:06 -0800983 (config->channel_mask != 0 && config->channel_mask != outputDesc->mChannelMask)) {
984 ALOGV("getOutputForDevice() failed opening direct output: output %d sample rate %d %d,"
985 "format %d %d, channel mask %04x %04x", output, config->sample_rate,
986 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
987 config->channel_mask, outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700988 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -0800989 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -0700990 }
Eric Laurenta82797f2015-01-30 11:49:43 -0800991 // fall back to mixer output if possible when the direct output could not be open
Eric Laurentfe231122017-11-17 17:48:06 -0800992 if (audio_is_linear_pcm(config->format) &&
993 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -0800994 goto non_direct_output;
995 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700996 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -0700997 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700998 outputDesc->mRefCount[stream] = 0;
999 outputDesc->mStopTime[stream] = 0;
1000 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -08001001 outputDesc->mDirectClientSession = session;
1002
Eric Laurente552edb2014-03-10 17:42:56 -07001003 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001004 mPreviousOutputs = mOutputs;
Eric Laurentf4e63452017-11-06 19:31:46 +00001005 ALOGV("getOutputForDevice() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001006 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001007 return output;
1008 }
1009
Eric Laurentb732cf52014-09-24 19:08:21 -07001010non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001011
1012 // A request for HW A/V sync cannot fallback to a mixed output because time
1013 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001014 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001015 return AUDIO_IO_HANDLE_NONE;
1016 }
1017
Eric Laurente552edb2014-03-10 17:42:56 -07001018 // ignoring channel mask due to downmix capability in mixer
1019
1020 // open a non direct output
1021
1022 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001023 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001024 // get which output is suitable for the specified stream. The actual
1025 // routing change will happen when startOutput() will be called
1026 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1027
Eric Laurent8838a382014-09-08 16:44:28 -07001028 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001029 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1030 output = selectOutput(outputs, *flags, config->format);
Eric Laurente552edb2014-03-10 17:42:56 -07001031 }
Eric Laurentf4e63452017-11-06 19:31:46 +00001032 ALOGW_IF((output == 0), "getOutputForDevice() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001033 "sampling rate %d, format %#x, channels %#x, flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +02001034 stream, config->sample_rate, config->format, config->channel_mask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001035
Eric Laurente552edb2014-03-10 17:42:56 -07001036 return output;
1037}
1038
Eric Laurente0720872014-03-11 09:30:41 -07001039audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001040 audio_output_flags_t flags,
1041 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001042{
1043 // select one output among several that provide a path to a particular device or set of
1044 // devices (the list was previously build by getOutputsForDevice()).
1045 // The priority is as follows:
1046 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001047 // 2: the output with the bit depth the closest to the requested one
1048 // 3: the primary output
1049 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001050
1051 if (outputs.size() == 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001052 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001053 }
1054 if (outputs.size() == 1) {
1055 return outputs[0];
1056 }
1057
1058 int maxCommonFlags = 0;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001059 audio_io_handle_t outputForFlags = AUDIO_IO_HANDLE_NONE;
1060 audio_io_handle_t outputForPrimary = AUDIO_IO_HANDLE_NONE;
1061 audio_io_handle_t outputForFormat = AUDIO_IO_HANDLE_NONE;
Eric Laurente6930022016-02-11 10:20:40 -08001062 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1063 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001064
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001065 for (audio_io_handle_t output : outputs) {
1066 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001067 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001068 // if a valid format is specified, skip output if not compatible
1069 if (format != AUDIO_FORMAT_INVALID) {
1070 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Andy Hung5659ed52018-04-30 10:31:26 -07001071 if (format != outputDesc->mFormat) {
Eric Laurent8838a382014-09-08 16:44:28 -07001072 continue;
1073 }
1074 } else if (!audio_is_linear_pcm(format)) {
1075 continue;
1076 }
Eric Laurente6930022016-02-11 10:20:40 -08001077 if (AudioPort::isBetterFormatMatch(
1078 outputDesc->mFormat, bestFormat, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001079 outputForFormat = output;
Eric Laurente6930022016-02-11 10:20:40 -08001080 bestFormat = outputDesc->mFormat;
1081 }
Eric Laurent8838a382014-09-08 16:44:28 -07001082 }
1083
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001084 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001085 if (commonFlags >= maxCommonFlags) {
1086 if (commonFlags == maxCommonFlags) {
Andy Hungc9901522017-11-10 20:07:54 -08001087 if (format != AUDIO_FORMAT_INVALID
1088 && AudioPort::isBetterFormatMatch(
1089 outputDesc->mFormat, bestFormatForFlags, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001090 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001091 bestFormatForFlags = outputDesc->mFormat;
1092 }
1093 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001094 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001095 maxCommonFlags = commonFlags;
1096 bestFormatForFlags = outputDesc->mFormat;
1097 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001098 ALOGV("selectOutput() commonFlags for output %d, %04x", output, commonFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001099 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001100 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001101 outputForPrimary = output;
Eric Laurente552edb2014-03-10 17:42:56 -07001102 }
1103 }
1104 }
1105
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001106 if (outputForFlags != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001107 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001108 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001109 if (outputForFormat != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001110 return outputForFormat;
1111 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001112 if (outputForPrimary != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001113 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001114 }
1115
1116 return outputs[0];
1117}
1118
Eric Laurente0720872014-03-11 09:30:41 -07001119status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001120 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001121 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001122{
Paul McLeanaa981192015-03-21 09:55:15 -07001123 ALOGV("startOutput() output %d, stream %d, session %d",
1124 output, stream, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001125 ssize_t index = mOutputs.indexOfKey(output);
1126 if (index < 0) {
1127 ALOGW("startOutput() unknown output %d", output);
1128 return BAD_VALUE;
1129 }
1130
Eric Laurentc75307b2015-03-17 15:29:32 -07001131 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1132
Eric Laurent733ce942017-12-07 12:18:25 -08001133 status_t status = outputDesc->start();
1134 if (status != NO_ERROR) {
1135 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001136 }
1137
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001138 // Routing?
1139 mOutputRoutes.incRouteActivity(session);
1140
Eric Laurentc75307b2015-03-17 15:29:32 -07001141 audio_devices_t newDevice;
Eric Laurentc40d9692016-04-13 19:14:13 -07001142 AudioMix *policyMix = NULL;
1143 const char *address = NULL;
Eric Laurentc75307b2015-03-17 15:29:32 -07001144 if (outputDesc->mPolicyMix != NULL) {
Eric Laurentc40d9692016-04-13 19:14:13 -07001145 policyMix = outputDesc->mPolicyMix;
1146 address = policyMix->mDeviceAddress.string();
1147 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1148 newDevice = policyMix->mDeviceType;
1149 } else {
1150 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1151 }
Eric Laurent2157f5b2018-04-25 18:33:02 -07001152 } else if (mOutputRoutes.getAndClearRouteChanged(session)) {
Eric Laurent493404d2015-04-21 15:07:36 -07001153 newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurentf3a5a602018-05-22 18:42:55 -07001154 if (newDevice != outputDesc->device()) {
1155 checkStrategyRoute(getStrategy(stream), output);
1156 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001157 } else {
1158 newDevice = AUDIO_DEVICE_NONE;
1159 }
1160
1161 uint32_t delayMs = 0;
1162
Eric Laurent733ce942017-12-07 12:18:25 -08001163 status = startSource(outputDesc, stream, newDevice, address, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001164
1165 if (status != NO_ERROR) {
1166 mOutputRoutes.decRouteActivity(session);
Eric Laurent733ce942017-12-07 12:18:25 -08001167 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001168 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001169 }
1170 // Automatically enable the remote submix input when output is started on a re routing mix
1171 // of type MIX_TYPE_RECORDERS
Eric Laurentc40d9692016-04-13 19:14:13 -07001172 if (audio_is_remote_submix_device(newDevice) && policyMix != NULL &&
1173 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001174 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1175 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Eric Laurentc40d9692016-04-13 19:14:13 -07001176 address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001177 "remote-submix");
1178 }
1179
1180 if (delayMs != 0) {
1181 usleep(delayMs * 1000);
1182 }
1183
1184 return status;
1185}
1186
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001187status_t AudioPolicyManager::startSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurentc75307b2015-03-17 15:29:32 -07001188 audio_stream_type_t stream,
1189 audio_devices_t device,
Eric Laurentc40d9692016-04-13 19:14:13 -07001190 const char *address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001191 uint32_t *delayMs)
1192{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001193 // cannot start playback of STREAM_TTS if any other output is being used
1194 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001195
1196 *delayMs = 0;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001197 if (stream == AUDIO_STREAM_TTS) {
1198 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001199 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001200 return INVALID_OPERATION;
1201 } else {
1202 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1203 }
1204 } else {
1205 // some playback other than beacon starts
1206 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1207 }
1208
Eric Laurent77305a62016-07-25 16:39:22 -07001209 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001210 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001211 bool force = !outputDesc->isActive() &&
1212 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001213
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001214 // requiresMuteCheck is false when we can bypass mute strategy.
1215 // It covers a common case when there is no materially active audio
1216 // and muting would result in unnecessary delay and dropped audio.
1217 const uint32_t outputLatencyMs = outputDesc->latency();
1218 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1219
Eric Laurente552edb2014-03-10 17:42:56 -07001220 // increment usage count for this stream on the requested output:
1221 // NOTE that the usage count is the same for duplicated output and hardware output which is
1222 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1223 outputDesc->changeRefCount(stream, 1);
1224
Eric Laurent36829f92017-04-07 19:04:42 -07001225 if (stream == AUDIO_STREAM_MUSIC) {
1226 selectOutputForMusicEffects();
1227 }
1228
Eric Laurent493404d2015-04-21 15:07:36 -07001229 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001230 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001231 if (device == AUDIO_DEVICE_NONE) {
1232 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001233 }
Eric Laurent36829f92017-04-07 19:04:42 -07001234
Eric Laurente552edb2014-03-10 17:42:56 -07001235 routing_strategy strategy = getStrategy(stream);
1236 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001237 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1238 (beaconMuteLatency > 0);
1239 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001240 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001241 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001242 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001243 // An output has a shared device if
1244 // - managed by the same hw module
1245 // - supports the currently selected device
1246 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
1247 && (desc->supportedDevices() & device) != AUDIO_DEVICE_NONE;
1248
Eric Laurent77305a62016-07-25 16:39:22 -07001249 // force a device change if any other output is:
1250 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001251 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001252 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001253 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001254 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001255 // change the device currently selected by the other output.
1256 if (sharedDevice &&
Eric Laurent77305a62016-07-25 16:39:22 -07001257 desc->device() != device &&
Eric Laurent77305a62016-07-25 16:39:22 -07001258 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001259 force = true;
1260 }
1261 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001262 // a notification so that audio focus effect can propagate, or that a mute/unmute
1263 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001264 const uint32_t latencyMs = desc->latency();
1265 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1266
1267 if (shouldWait && isActive && (waitMs < latencyMs)) {
1268 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001269 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001270
1271 // Require mute check if another output is on a shared device
1272 // and currently active to have proper drain and avoid pops.
1273 // Note restoring AudioTracks onto this output needs to invoke
1274 // a volume ramp if there is no mute.
1275 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001276 }
1277 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001278
1279 const uint32_t muteWaitMs =
1280 setOutputDevice(outputDesc, device, force, 0, NULL, address, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001281
1282 // handle special case for sonification while in call
1283 if (isInCall()) {
1284 handleIncallSonification(stream, true, false);
1285 }
1286
1287 // apply volume rules for current stream and device if necessary
1288 checkAndSetVolume(stream,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001289 mVolumeCurves->getVolumeIndex(stream, outputDesc->device()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001290 outputDesc,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001291 outputDesc->device());
Eric Laurente552edb2014-03-10 17:42:56 -07001292
1293 // update the outputs if starting an output with a stream that can affect notification
1294 // routing
1295 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001296
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001297 // force reevaluating accessibility routing when ringtone or alarm starts
1298 if (strategy == STRATEGY_SONIFICATION) {
1299 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1300 }
Eric Laurentdc462862016-07-19 12:29:53 -07001301
1302 if (waitMs > muteWaitMs) {
1303 *delayMs = waitMs - muteWaitMs;
1304 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001305
1306 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1307 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1308 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1309 // change occurs after the MixerThread starts and causes a stream volume
1310 // glitch.
1311 //
1312 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001313 }
Eric Laurentdc462862016-07-19 12:29:53 -07001314
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001315 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1316 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1317 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1318 }
1319
Tomoharu Kasaharaa81f0982018-01-18 20:55:02 +09001320 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1321 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1322 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1323 }
1324
Eric Laurente552edb2014-03-10 17:42:56 -07001325 return NO_ERROR;
1326}
1327
1328
Eric Laurente0720872014-03-11 09:30:41 -07001329status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001330 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001331 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001332{
1333 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1334 ssize_t index = mOutputs.indexOfKey(output);
1335 if (index < 0) {
1336 ALOGW("stopOutput() unknown output %d", output);
1337 return BAD_VALUE;
1338 }
1339
Eric Laurentc75307b2015-03-17 15:29:32 -07001340 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001341
Eric Laurentc75307b2015-03-17 15:29:32 -07001342 if (outputDesc->mRefCount[stream] == 1) {
1343 // Automatically disable the remote submix input when output is stopped on a
1344 // re routing mix of type MIX_TYPE_RECORDERS
1345 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1346 outputDesc->mPolicyMix != NULL &&
1347 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1348 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1349 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001350 outputDesc->mPolicyMix->mDeviceAddress,
Eric Laurentc75307b2015-03-17 15:29:32 -07001351 "remote-submix");
1352 }
1353 }
1354
1355 // Routing?
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001356 bool forceDeviceUpdate = false;
Eric Laurentc75307b2015-03-17 15:29:32 -07001357 if (outputDesc->mRefCount[stream] > 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001358 int activityCount = mOutputRoutes.decRouteActivity(session);
1359 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1360
1361 if (forceDeviceUpdate) {
1362 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1363 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001364 }
1365
Eric Laurent3974e3b2017-12-07 17:58:43 -08001366 status_t status = stopSource(outputDesc, stream, forceDeviceUpdate);
1367
Eric Laurent733ce942017-12-07 12:18:25 -08001368 if (status == NO_ERROR ) {
1369 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001370 }
1371 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001372}
1373
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001374status_t AudioPolicyManager::stopSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001375 audio_stream_type_t stream,
1376 bool forceDeviceUpdate)
Eric Laurentc75307b2015-03-17 15:29:32 -07001377{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001378 // always handle stream stop, check which stream type is stopping
1379 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1380
Eric Laurente552edb2014-03-10 17:42:56 -07001381 // handle special case for sonification while in call
1382 if (isInCall()) {
1383 handleIncallSonification(stream, false, false);
1384 }
1385
1386 if (outputDesc->mRefCount[stream] > 0) {
1387 // decrement usage count of this stream on the output
1388 outputDesc->changeRefCount(stream, -1);
Paul McLeanaa981192015-03-21 09:55:15 -07001389
Eric Laurente552edb2014-03-10 17:42:56 -07001390 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001391 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001392 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001393 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001394 // delay the device switch by twice the latency because stopOutput() is executed when
1395 // the track stop() command is received and at that time the audio track buffer can
1396 // still contain data that needs to be drained. The latency only covers the audio HAL
1397 // and kernel buffers. Also the latency does not always include additional delay in the
1398 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001399 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001400
1401 // force restoring the device selection on other active outputs if it differs from the
1402 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001403 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001404 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001405 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001406 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001407 desc->isActive() &&
1408 outputDesc->sharesHwModuleWith(desc) &&
1409 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001410 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1411 bool force = desc->device() != newDevice2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001412
Eric Laurentc75307b2015-03-17 15:29:32 -07001413 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001414 newDevice2,
1415 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001416 delayMs);
1417 // re-apply device specific volume if not done by setOutputDevice()
1418 if (!force) {
1419 applyStreamVolumes(desc, newDevice2, delayMs);
1420 }
Eric Laurente552edb2014-03-10 17:42:56 -07001421 }
1422 }
1423 // update the outputs if stopping one with a stream that can affect notification routing
1424 handleNotificationRoutingForStream(stream);
1425 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001426
1427 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1428 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1429 setStrategyMute(STRATEGY_SONIFICATION, false, outputDesc);
1430 }
1431
Eric Laurent36829f92017-04-07 19:04:42 -07001432 if (stream == AUDIO_STREAM_MUSIC) {
1433 selectOutputForMusicEffects();
1434 }
Eric Laurente552edb2014-03-10 17:42:56 -07001435 return NO_ERROR;
1436 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001437 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001438 return INVALID_OPERATION;
1439 }
1440}
1441
Eric Laurente83b55d2014-11-14 10:06:21 -08001442void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001443 audio_stream_type_t stream __unused,
1444 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001445{
1446 ALOGV("releaseOutput() %d", output);
1447 ssize_t index = mOutputs.indexOfKey(output);
1448 if (index < 0) {
1449 ALOGW("releaseOutput() releasing unknown output %d", output);
1450 return;
1451 }
1452
Paul McLeanaa981192015-03-21 09:55:15 -07001453 // Routing
1454 mOutputRoutes.removeRoute(session);
1455
Eric Laurentc75307b2015-03-17 15:29:32 -07001456 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001457 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001458 if (desc->mDirectOpenCount <= 0) {
1459 ALOGW("releaseOutput() invalid open count %d for output %d",
1460 desc->mDirectOpenCount, output);
1461 return;
1462 }
1463 if (--desc->mDirectOpenCount == 0) {
1464 closeOutput(output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001465 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001466 }
1467 }
1468}
1469
1470
Eric Laurentcaf7f482014-11-25 17:50:47 -08001471status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1472 audio_io_handle_t *input,
1473 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001474 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001475 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001476 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001477 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001478 input_type_t *inputType,
1479 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001480{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001481 ALOGV("getInputForAttr() source %d, sampling rate %d, format %#x, channel mask %#x,"
Eric Laurentcaf7f482014-11-25 17:50:47 -08001482 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001483 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001484
Eric Laurentad2e7b92017-09-14 20:06:42 -07001485 status_t status = NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -08001486 // handle legacy remote submix case where the address was not always specified
1487 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001488 audio_source_t halInputSource;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001489 audio_source_t inputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001490 AudioMix *policyMix = NULL;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001491 DeviceVector inputDevices;
Eric Laurent20b9ef02016-12-05 11:03:16 -08001492
Eric Laurentfe231122017-11-17 17:48:06 -08001493 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1494 inputSource = AUDIO_SOURCE_MIC;
1495 }
1496
Paul McLean466dc8e2015-04-17 13:15:36 -06001497 // Explicit routing?
1498 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -07001499 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
jiabinc0c831a2018-01-29 17:55:15 -08001500 deviceDesc = mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001501 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001502 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
Paul McLean466dc8e2015-04-17 13:15:36 -06001503
Eric Laurentad2e7b92017-09-14 20:06:42 -07001504 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1505 // possible
1506 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1507 *input != AUDIO_IO_HANDLE_NONE) {
1508 ssize_t index = mInputs.indexOfKey(*input);
1509 if (index < 0) {
1510 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1511 status = BAD_VALUE;
1512 goto error;
1513 }
1514 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1515 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1516 if (audioSession == 0) {
1517 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1518 status = BAD_VALUE;
1519 goto error;
1520 }
1521 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1522 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001523 // corresponds to a new client and is only permitted from the same UID.
1524 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurentad2e7b92017-09-14 20:06:42 -07001525 if (audioSession->openCount() == 1) {
1526 audioSession->setUid(uid);
1527 } else if (audioSession->uid() != uid) {
Eric Laurent331679c2018-04-16 17:03:16 -07001528 if (!audioSession->isSilenced()) {
1529 ALOGW("getInputForAttr() bad uid %d for session %d uid %d",
1530 uid, session, audioSession->uid());
1531 status = INVALID_OPERATION;
1532 goto error;
1533 }
1534 audioSession->setUid(uid);
1535 audioSession->setSilenced(false);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001536 }
1537 audioSession->changeOpenCount(1);
1538 *inputType = API_INPUT_LEGACY;
1539 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1540 *portId = AudioPort::getNextUniqueId();
1541 }
Mikhail Naganov708e0382018-05-30 09:53:04 -07001542 inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(inputDesc->mDevice);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001543 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1544 : AUDIO_PORT_HANDLE_NONE;
1545 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
1546
1547 return NO_ERROR;
1548 }
1549
1550 *input = AUDIO_IO_HANDLE_NONE;
1551 *inputType = API_INPUT_INVALID;
1552
Eric Laurentad2e7b92017-09-14 20:06:42 -07001553 halInputSource = inputSource;
1554
1555 // TODO: check for existing client for this port ID
1556 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1557 *portId = AudioPort::getNextUniqueId();
1558 }
1559
1560 audio_devices_t device;
1561
Eric Laurentc447ded2015-01-06 08:47:05 -08001562 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001563 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001564 status = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
1565 if (status != NO_ERROR) {
1566 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001567 }
1568 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001569 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1570 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001571 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001572 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001573 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001574 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001575 status = BAD_VALUE;
1576 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001577 }
Eric Laurentc722f302014-12-10 11:21:49 -08001578 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001579 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001580 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1581 // there is an external policy, but this input is attached to a mix of recorders,
1582 // meaning it receives audio injected into the framework, so the recorder doesn't
1583 // know about it and is therefore considered "legacy"
1584 *inputType = API_INPUT_LEGACY;
1585 } else {
1586 // recording a mix of players defined by an external policy, we're rerouting for
1587 // an external policy
1588 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1589 }
Eric Laurentc722f302014-12-10 11:21:49 -08001590 } else if (audio_is_remote_submix_device(device)) {
1591 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001592 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001593 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1594 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001595 } else {
1596 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001597 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001598
Eric Laurent599c7582015-12-07 18:05:55 -08001599 }
1600
1601 *input = getInputForDevice(device, address, session, uid, inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001602 config, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001603 policyMix);
1604 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001605 status = INVALID_OPERATION;
1606 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001607 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001608
Mikhail Naganov708e0382018-05-30 09:53:04 -07001609 inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -07001610 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1611 : AUDIO_PORT_HANDLE_NONE;
1612
1613 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d",
1614 *input, *inputType, *selectedDeviceId);
1615
Eric Laurent599c7582015-12-07 18:05:55 -08001616 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001617
1618error:
1619 mInputRoutes.removeRoute(session);
1620 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001621}
1622
1623
1624audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1625 String8 address,
1626 audio_session_t session,
1627 uid_t uid,
1628 audio_source_t inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001629 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08001630 audio_input_flags_t flags,
1631 AudioMix *policyMix)
1632{
1633 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1634 audio_source_t halInputSource = inputSource;
1635 bool isSoundTrigger = false;
1636
1637 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1638 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1639 if (index >= 0) {
1640 input = mSoundTriggerSessions.valueFor(session);
1641 isSoundTrigger = true;
1642 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1643 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1644 } else {
1645 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001646 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001647 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08001648 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001649 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001650 }
1651
Andy Hungf129b032015-04-07 13:45:50 -07001652 // find a compatible input profile (not necessarily identical in parameters)
1653 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08001654 // sampling rate and flags may be updated by getInputProfile
1655 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
1656 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07001657 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08001658 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07001659 audio_input_flags_t profileFlags = flags;
1660 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07001661 profileFormat = config->format; // reset each time through loop, in case it is updated
Eric Laurent275e8e92014-11-30 15:14:47 -08001662 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001663 profileSamplingRate, profileFormat, profileChannelMask,
1664 profileFlags);
1665 if (profile != 0) {
1666 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001667 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1668 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001669 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1670 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1671 } else { // fail
Glenn Kastenfaa10a62017-05-25 15:52:05 -07001672 ALOGW("getInputForDevice() could not find profile for device 0x%X, "
Eric Laurentfe231122017-11-17 17:48:06 -08001673 "sampling rate %u, format %#x, channel mask 0x%X, flags %#x",
1674 device, config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001675 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001676 }
Eric Laurente552edb2014-03-10 17:42:56 -07001677 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001678 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08001679 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08001680 if (samplingRate == 0) {
1681 samplingRate = profileSamplingRate;
1682 }
Eric Laurente552edb2014-03-10 17:42:56 -07001683
Eric Laurent322b4d22015-04-03 15:57:54 -07001684 if (profile->getModuleHandle() == 0) {
1685 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001686 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001687 }
1688
Eric Laurent599c7582015-12-07 18:05:55 -08001689 sp<AudioSession> audioSession = new AudioSession(session,
Eric Laurentfe231122017-11-17 17:48:06 -08001690 inputSource,
1691 config->format,
1692 samplingRate,
1693 config->channel_mask,
1694 flags,
1695 uid,
1696 isSoundTrigger,
1697 policyMix, mpClientInterface);
Eric Laurent599c7582015-12-07 18:05:55 -08001698
Eric Laurent74708e72017-04-07 17:13:42 -07001699// FIXME: disable concurrent capture until UI is ready
1700#if 0
Eric Laurent599c7582015-12-07 18:05:55 -08001701 // reuse an open input if possible
Eric Laurent555530a2017-02-07 18:17:24 -08001702 sp<AudioInputDescriptor> reusedInputDesc;
Eric Laurent599c7582015-12-07 18:05:55 -08001703 for (size_t i = 0; i < mInputs.size(); i++) {
1704 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001705 // reuse input if:
1706 // - it shares the same profile
1707 // AND
1708 // - it is not a reroute submix input
1709 // AND
1710 // - it is: not used for sound trigger
1711 // OR
1712 // used for sound trigger and all clients use the same session ID
1713 //
1714 if ((profile == desc->mProfile) &&
1715 (isSoundTrigger == desc->isSoundTrigger()) &&
1716 !is_virtual_input_device(device)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001717
1718 sp<AudioSession> as = desc->getAudioSession(session);
1719 if (as != 0) {
1720 // do not allow unmatching properties on same session
1721 if (as->matches(audioSession)) {
1722 as->changeOpenCount(1);
1723 } else {
1724 ALOGW("getInputForDevice() record with different attributes"
1725 " exists for session %d", session);
Eric Laurent555530a2017-02-07 18:17:24 -08001726 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001727 }
Eric Laurentfb66dd92016-01-28 18:32:03 -08001728 } else if (isSoundTrigger) {
Eric Laurent555530a2017-02-07 18:17:24 -08001729 continue;
Eric Laurentfb66dd92016-01-28 18:32:03 -08001730 }
Eric Laurentbb948092017-01-23 18:33:30 -08001731
Eric Laurent555530a2017-02-07 18:17:24 -08001732 // Reuse the already opened input stream on this profile if:
1733 // - the new capture source is background OR
1734 // - the path requested configurations match OR
1735 // - the new source priority is less than the highest source priority on this input
1736 // If the input stream cannot be reused, close it before opening a new stream
1737 // on the same profile for the new client so that the requested path configuration
1738 // can be selected.
1739 if (!isConcurrentSource(inputSource) &&
Eric Laurentbb948092017-01-23 18:33:30 -08001740 ((desc->mSamplingRate != samplingRate ||
Eric Laurentfe231122017-11-17 17:48:06 -08001741 desc->mChannelMask != config->channel_mask ||
1742 !audio_formats_match(desc->mFormat, config->format)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001743 (source_priority(desc->getHighestPrioritySource(false /*activeOnly*/)) <
Eric Laurentbb948092017-01-23 18:33:30 -08001744 source_priority(inputSource)))) {
Eric Laurent555530a2017-02-07 18:17:24 -08001745 reusedInputDesc = desc;
1746 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001747 } else {
1748 desc->addAudioSession(session, audioSession);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001749 ALOGV("%s: reusing input %d", __FUNCTION__, mInputs.keyAt(i));
1750 return mInputs.keyAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08001751 }
Eric Laurent599c7582015-12-07 18:05:55 -08001752 }
1753 }
Eric Laurent599c7582015-12-07 18:05:55 -08001754
Eric Laurent555530a2017-02-07 18:17:24 -08001755 if (reusedInputDesc != 0) {
1756 AudioSessionCollection sessions = reusedInputDesc->getAudioSessions(false /*activeOnly*/);
1757 for (size_t j = 0; j < sessions.size(); j++) {
1758 audio_session_t currentSession = sessions.keyAt(j);
1759 stopInput(reusedInputDesc->mIoHandle, currentSession);
1760 releaseInput(reusedInputDesc->mIoHandle, currentSession);
1761 }
1762 }
Eric Laurent74708e72017-04-07 17:13:42 -07001763#endif
Eric Laurent555530a2017-02-07 18:17:24 -08001764
Eric Laurent3974e3b2017-12-07 17:58:43 -08001765 if (!profile->canOpenNewIo()) {
1766 return AUDIO_IO_HANDLE_NONE;
1767 }
1768
Eric Laurentfe231122017-11-17 17:48:06 -08001769 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001770
Eric Laurentfe231122017-11-17 17:48:06 -08001771 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
1772 lConfig.sample_rate = profileSamplingRate;
1773 lConfig.channel_mask = profileChannelMask;
1774 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07001775
Eric Laurent53b810e2017-12-10 17:25:10 -08001776 if (address == "") {
Mikhail Naganov708e0382018-05-30 09:53:04 -07001777 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -08001778 // the inputs vector must be of size >= 1, but we don't want to crash here
1779 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress : String8("");
1780 }
1781
Eric Laurentfe231122017-11-17 17:48:06 -08001782 status_t status = inputDesc->open(&lConfig, device, address,
1783 halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001784
1785 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001786 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08001787 (profileSamplingRate != lConfig.sample_rate) ||
1788 !audio_formats_match(profileFormat, lConfig.format) ||
1789 (profileChannelMask != lConfig.channel_mask)) {
1790 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001791 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08001792 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001793 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001794 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07001795 }
Eric Laurent599c7582015-12-07 18:05:55 -08001796 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001797 }
1798
Eric Laurentc722f302014-12-10 11:21:49 -08001799 inputDesc->mPolicyMix = policyMix;
Eric Laurent599c7582015-12-07 18:05:55 -08001800 inputDesc->addAudioSession(session, audioSession);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001801
Eric Laurent599c7582015-12-07 18:05:55 -08001802 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001803 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001804
Eric Laurent599c7582015-12-07 18:05:55 -08001805 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001806}
1807
Eric Laurentbb948092017-01-23 18:33:30 -08001808//static
1809bool AudioPolicyManager::isConcurrentSource(audio_source_t source)
1810{
1811 return (source == AUDIO_SOURCE_HOTWORD) ||
1812 (source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
1813 (source == AUDIO_SOURCE_FM_TUNER);
1814}
1815
Eric Laurentfb66dd92016-01-28 18:32:03 -08001816bool AudioPolicyManager::isConcurentCaptureAllowed(const sp<AudioInputDescriptor>& inputDesc,
1817 const sp<AudioSession>& audioSession)
1818{
1819 // Do not allow capture if an active voice call is using a software patch and
1820 // the call TX source device is on the same HW module.
1821 // FIXME: would be better to refine to only inputs whose profile connects to the
1822 // call TX device but this information is not in the audio patch
1823 if (mCallTxPatch != 0 &&
1824 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1825 return false;
1826 }
1827
1828 // starting concurrent capture is enabled if:
1829 // 1) capturing for re-routing
1830 // 2) capturing for HOTWORD source
1831 // 3) capturing for FM TUNER source
1832 // 3) All other active captures are either for re-routing or HOTWORD
1833
1834 if (is_virtual_input_device(inputDesc->mDevice) ||
Eric Laurentbb948092017-01-23 18:33:30 -08001835 isConcurrentSource(audioSession->inputSource())) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001836 return true;
1837 }
1838
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001839 for (const auto& activeInput : mInputs.getActiveInputs()) {
Eric Laurentbb948092017-01-23 18:33:30 -08001840 if (!isConcurrentSource(activeInput->inputSource(true)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001841 !is_virtual_input_device(activeInput->mDevice)) {
1842 return false;
1843 }
1844 }
1845
1846 return true;
1847}
1848
Chris Thornton2b864642017-06-27 21:26:07 -07001849// FIXME: remove when concurrent capture is ready. This is a hack to work around bug b/63083537.
1850bool AudioPolicyManager::soundTriggerSupportsConcurrentCapture() {
1851 if (!mHasComputedSoundTriggerSupportsConcurrentCapture) {
1852 bool soundTriggerSupportsConcurrentCapture = false;
1853 unsigned int numModules = 0;
1854 struct sound_trigger_module_descriptor* nModules = NULL;
1855
1856 status_t status = SoundTrigger::listModules(nModules, &numModules);
1857 if (status == NO_ERROR && numModules != 0) {
1858 nModules = (struct sound_trigger_module_descriptor*) calloc(
1859 numModules, sizeof(struct sound_trigger_module_descriptor));
1860 if (nModules == NULL) {
1861 // We failed to malloc the buffer, so just say no for now, and hope that we have more
1862 // ram the next time this function is called.
1863 ALOGE("Failed to allocate buffer for module descriptors");
1864 return false;
1865 }
1866
1867 status = SoundTrigger::listModules(nModules, &numModules);
1868 if (status == NO_ERROR) {
1869 soundTriggerSupportsConcurrentCapture = true;
1870 for (size_t i = 0; i < numModules; ++i) {
1871 soundTriggerSupportsConcurrentCapture &=
1872 nModules[i].properties.concurrent_capture;
1873 }
1874 }
1875 free(nModules);
1876 }
1877 mSoundTriggerSupportsConcurrentCapture = soundTriggerSupportsConcurrentCapture;
1878 mHasComputedSoundTriggerSupportsConcurrentCapture = true;
1879 }
1880 return mSoundTriggerSupportsConcurrentCapture;
1881}
1882
Eric Laurentfb66dd92016-01-28 18:32:03 -08001883
Eric Laurent4dc68062014-07-28 17:26:49 -07001884status_t AudioPolicyManager::startInput(audio_io_handle_t input,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001885 audio_session_t session,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001886 bool silenced,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001887 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07001888{
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001889
1890 ALOGV("AudioPolicyManager::startInput(input:%d, session:%d, silenced:%d, concurrency:%d)",
1891 input, session, silenced, *concurrency);
1892
Eric Laurentfb66dd92016-01-28 18:32:03 -08001893 *concurrency = API_INPUT_CONCURRENCY_NONE;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001894
Eric Laurente552edb2014-03-10 17:42:56 -07001895 ssize_t index = mInputs.indexOfKey(input);
1896 if (index < 0) {
1897 ALOGW("startInput() unknown input %d", input);
1898 return BAD_VALUE;
1899 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001900 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001901
Eric Laurent599c7582015-12-07 18:05:55 -08001902 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1903 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07001904 ALOGW("startInput() unknown session %d on input %d", session, input);
1905 return BAD_VALUE;
1906 }
1907
Eric Laurent74708e72017-04-07 17:13:42 -07001908// FIXME: disable concurrent capture until UI is ready
1909#if 0
Eric Laurentfb66dd92016-01-28 18:32:03 -08001910 if (!isConcurentCaptureAllowed(inputDesc, audioSession)) {
1911 ALOGW("startInput(%d) failed: other input already started", input);
1912 return INVALID_OPERATION;
1913 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001914
Eric Laurentfb66dd92016-01-28 18:32:03 -08001915 if (isInCall()) {
1916 *concurrency |= API_INPUT_CONCURRENCY_CALL;
1917 }
Eric Laurentf7c50102016-09-30 15:19:43 -07001918 if (mInputs.activeInputsCountOnDevices() != 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001919 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurente552edb2014-03-10 17:42:56 -07001920 }
Eric Laurent74708e72017-04-07 17:13:42 -07001921#else
1922 if (!is_virtual_input_device(inputDesc->mDevice)) {
1923 if (mCallTxPatch != 0 &&
1924 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1925 ALOGW("startInput(%d) failed: call in progress", input);
Ray Essick84e84a52018-05-03 18:45:07 -07001926 *concurrency |= API_INPUT_CONCURRENCY_CALL;
Eric Laurent74708e72017-04-07 17:13:42 -07001927 return INVALID_OPERATION;
1928 }
1929
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001930 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07001931
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001932 // If a UID is idle and records silence and another not silenced recording starts
1933 // from another UID (idle or active) we stop the current idle UID recording in
1934 // favor of the new one - "There can be only one" TM
1935 if (!silenced) {
1936 for (const auto& activeDesc : activeInputs) {
1937 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
1938 activeDesc->getId() == inputDesc->getId()) {
1939 continue;
1940 }
1941
1942 AudioSessionCollection activeSessions = activeDesc->getAudioSessions(
1943 true /*activeOnly*/);
1944 sp<AudioSession> activeSession = activeSessions.valueAt(0);
1945 if (activeSession->isSilenced()) {
1946 audio_io_handle_t activeInput = activeDesc->mIoHandle;
1947 audio_session_t activeSessionId = activeSession->session();
1948 stopInput(activeInput, activeSessionId);
1949 releaseInput(activeInput, activeSessionId);
1950 ALOGV("startInput(%d) stopping silenced input %d", input, activeInput);
1951 activeInputs = mInputs.getActiveInputs();
1952 }
1953 }
1954 }
1955
1956 for (const auto& activeDesc : activeInputs) {
Eric Laurentcb4dae22017-07-01 19:39:32 -07001957 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
1958 activeDesc->getId() == inputDesc->getId()) {
1959 continue;
1960 }
1961
Eric Laurent74708e72017-04-07 17:13:42 -07001962 audio_source_t activeSource = activeDesc->inputSource(true);
1963 if (audioSession->inputSource() == AUDIO_SOURCE_HOTWORD) {
1964 if (activeSource == AUDIO_SOURCE_HOTWORD) {
1965 if (activeDesc->hasPreemptedSession(session)) {
1966 ALOGW("startInput(%d) failed for HOTWORD: "
1967 "other input %d already started for HOTWORD",
1968 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07001969 *concurrency |= API_INPUT_CONCURRENCY_HOTWORD;
Eric Laurent74708e72017-04-07 17:13:42 -07001970 return INVALID_OPERATION;
1971 }
1972 } else {
1973 ALOGV("startInput(%d) failed for HOTWORD: other input %d already started",
1974 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07001975 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07001976 return INVALID_OPERATION;
1977 }
1978 } else {
1979 if (activeSource != AUDIO_SOURCE_HOTWORD) {
1980 ALOGW("startInput(%d) failed: other input %d already started",
1981 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07001982 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07001983 return INVALID_OPERATION;
1984 }
1985 }
1986 }
1987
Chris Thornton2b864642017-06-27 21:26:07 -07001988 // We only need to check if the sound trigger session supports concurrent capture if the
1989 // input is also a sound trigger input. Otherwise, we should preempt any hotword stream
1990 // that's running.
1991 const bool allowConcurrentWithSoundTrigger =
1992 inputDesc->isSoundTrigger() ? soundTriggerSupportsConcurrentCapture() : false;
1993
Eric Laurent74708e72017-04-07 17:13:42 -07001994 // if capture is allowed, preempt currently active HOTWORD captures
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001995 for (const auto& activeDesc : activeInputs) {
Chris Thornton2b864642017-06-27 21:26:07 -07001996 if (allowConcurrentWithSoundTrigger && activeDesc->isSoundTrigger()) {
1997 continue;
1998 }
1999
Eric Laurent74708e72017-04-07 17:13:42 -07002000 audio_source_t activeSource = activeDesc->inputSource(true);
2001 if (activeSource == AUDIO_SOURCE_HOTWORD) {
2002 AudioSessionCollection activeSessions =
2003 activeDesc->getAudioSessions(true /*activeOnly*/);
2004 audio_session_t activeSession = activeSessions.keyAt(0);
2005 audio_io_handle_t activeHandle = activeDesc->mIoHandle;
2006 SortedVector<audio_session_t> sessions = activeDesc->getPreemptedSessions();
Ray Essick84e84a52018-05-03 18:45:07 -07002007 *concurrency |= API_INPUT_CONCURRENCY_PREEMPT;
Eric Laurent74708e72017-04-07 17:13:42 -07002008 sessions.add(activeSession);
2009 inputDesc->setPreemptedSessions(sessions);
2010 stopInput(activeHandle, activeSession);
2011 releaseInput(activeHandle, activeSession);
2012 ALOGV("startInput(%d) for HOTWORD preempting HOTWORD input %d",
2013 input, activeDesc->mIoHandle);
2014 }
2015 }
2016 }
2017#endif
Eric Laurente552edb2014-03-10 17:42:56 -07002018
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002019 // Make sure we start with the correct silence state
2020 audioSession->setSilenced(silenced);
2021
Eric Laurent313d1e72016-01-29 09:56:57 -08002022 // increment activity count before calling getNewInputDevice() below as only active sessions
2023 // are considered for device selection
2024 audioSession->changeActiveCount(1);
2025
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002026 // Routing?
2027 mInputRoutes.incRouteActivity(session);
2028
Eric Laurent2157f5b2018-04-25 18:33:02 -07002029 if (audioSession->activeCount() == 1 || mInputRoutes.getAndClearRouteChanged(session)) {
Eric Laurent271a93e2016-09-29 14:47:06 -07002030 // indicate active capture to sound trigger service if starting capture from a mic on
2031 // primary HW module
Eric Laurentf7c50102016-09-30 15:19:43 -07002032 audio_devices_t device = getNewInputDevice(inputDesc);
Eric Laurent271a93e2016-09-29 14:47:06 -07002033 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002034
Eric Laurent733ce942017-12-07 12:18:25 -08002035 status_t status = inputDesc->start();
2036 if (status != NO_ERROR) {
2037 mInputRoutes.decRouteActivity(session);
2038 audioSession->changeActiveCount(-1);
2039 return status;
2040 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002041
Eric Laurent733ce942017-12-07 12:18:25 -08002042 if (inputDesc->getAudioSessionCount(true/*activeOnly*/) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002043 // if input maps to a dynamic policy with an activity listener, notify of state change
2044 if ((inputDesc->mPolicyMix != NULL)
2045 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2046 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2047 MIX_STATE_MIXING);
Eric Laurentc722f302014-12-10 11:21:49 -08002048 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002049
Eric Laurentf7c50102016-09-30 15:19:43 -07002050 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2051 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Eric Laurent05b345e2016-11-18 12:36:27 -08002052 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002053 SoundTrigger::setCaptureState(true);
2054 }
2055
2056 // automatically enable the remote submix output when input is started if not
2057 // used by a policy mix of type MIX_TYPE_RECORDERS
2058 // For remote submix (a virtual device), we open only one input per capture request.
2059 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2060 String8 address = String8("");
2061 if (inputDesc->mPolicyMix == NULL) {
2062 address = String8("0");
2063 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2064 address = inputDesc->mPolicyMix->mDeviceAddress;
2065 }
2066 if (address != "") {
2067 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2068 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2069 address, "remote-submix");
2070 }
Eric Laurentc722f302014-12-10 11:21:49 -08002071 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002072 }
Eric Laurente552edb2014-03-10 17:42:56 -07002073 }
2074
Eric Laurent599c7582015-12-07 18:05:55 -08002075 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
Eric Laurente552edb2014-03-10 17:42:56 -07002076
Eric Laurente552edb2014-03-10 17:42:56 -07002077 return NO_ERROR;
2078}
2079
Eric Laurent4dc68062014-07-28 17:26:49 -07002080status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
2081 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07002082{
2083 ALOGV("stopInput() input %d", input);
2084 ssize_t index = mInputs.indexOfKey(input);
2085 if (index < 0) {
2086 ALOGW("stopInput() unknown input %d", input);
2087 return BAD_VALUE;
2088 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002089 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07002090
Eric Laurent599c7582015-12-07 18:05:55 -08002091 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07002092 if (index < 0) {
2093 ALOGW("stopInput() unknown session %d on input %d", session, input);
2094 return BAD_VALUE;
2095 }
2096
Eric Laurent599c7582015-12-07 18:05:55 -08002097 if (audioSession->activeCount() == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002098 ALOGW("stopInput() input %d already stopped", input);
2099 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002100 }
2101
Eric Laurent599c7582015-12-07 18:05:55 -08002102 audioSession->changeActiveCount(-1);
Paul McLean466dc8e2015-04-17 13:15:36 -06002103
2104 // Routing?
2105 mInputRoutes.decRouteActivity(session);
2106
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002107 if (audioSession->activeCount() == 0) {
Eric Laurent733ce942017-12-07 12:18:25 -08002108 inputDesc->stop();
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002109 if (inputDesc->isActive()) {
2110 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2111 } else {
2112 // if input maps to a dynamic policy with an activity listener, notify of state change
2113 if ((inputDesc->mPolicyMix != NULL)
2114 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2115 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2116 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002117 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002118
2119 // automatically disable the remote submix output when input is stopped if not
2120 // used by a policy mix of type MIX_TYPE_RECORDERS
2121 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2122 String8 address = String8("");
2123 if (inputDesc->mPolicyMix == NULL) {
2124 address = String8("0");
2125 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2126 address = inputDesc->mPolicyMix->mDeviceAddress;
2127 }
2128 if (address != "") {
2129 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2130 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2131 address, "remote-submix");
2132 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002133 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002134
Eric Laurentf7c50102016-09-30 15:19:43 -07002135 audio_devices_t device = inputDesc->mDevice;
Eric Laurentfb66dd92016-01-28 18:32:03 -08002136 resetInputDevice(input);
Eric Laurent84332aa2016-01-28 22:19:18 +00002137
Eric Laurentf7c50102016-09-30 15:19:43 -07002138 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2139 // primary HW module
2140 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2141 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2142 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08002143 SoundTrigger::setCaptureState(false);
2144 }
2145 inputDesc->clearPreemptedSessions();
Eric Laurent84332aa2016-01-28 22:19:18 +00002146 }
Eric Laurente552edb2014-03-10 17:42:56 -07002147 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002148 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002149}
2150
Eric Laurent4dc68062014-07-28 17:26:49 -07002151void AudioPolicyManager::releaseInput(audio_io_handle_t input,
2152 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07002153{
2154 ALOGV("releaseInput() %d", input);
2155 ssize_t index = mInputs.indexOfKey(input);
2156 if (index < 0) {
2157 ALOGW("releaseInput() releasing unknown input %d", input);
2158 return;
2159 }
Paul McLean466dc8e2015-04-17 13:15:36 -06002160
2161 // Routing
2162 mInputRoutes.removeRoute(session);
2163
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002164 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
2165 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07002166
Eric Laurent599c7582015-12-07 18:05:55 -08002167 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
vivek mehta587b8df2017-01-31 14:58:44 -08002168 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07002169 ALOGW("releaseInput() unknown session %d on input %d", session, input);
2170 return;
2171 }
Eric Laurent599c7582015-12-07 18:05:55 -08002172
2173 if (audioSession->openCount() == 0) {
2174 ALOGW("releaseInput() invalid open count %d on session %d",
2175 audioSession->openCount(), session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002176 return;
2177 }
Eric Laurent599c7582015-12-07 18:05:55 -08002178
2179 if (audioSession->changeOpenCount(-1) == 0) {
2180 inputDesc->removeAudioSession(session);
2181 }
2182
Jean-Michel Trivi65bfe912015-12-04 15:56:47 -08002183 if (inputDesc->getOpenRefCount() > 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002184 ALOGV("releaseInput() exit > 0");
2185 return;
2186 }
2187
Eric Laurent05b90f82014-08-27 15:32:29 -07002188 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002189 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002190 ALOGV("releaseInput() exit");
2191}
2192
Eric Laurentd4692962014-05-05 18:13:44 -07002193void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002194 bool patchRemoved = false;
2195
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002196 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002197 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002198 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002199 if (patch_index >= 0) {
2200 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002201 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002202 mAudioPatches.removeItemsAt(patch_index);
2203 patchRemoved = true;
2204 }
Eric Laurentfe231122017-11-17 17:48:06 -08002205 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002206 }
jiabin829a00b2018-04-04 16:28:32 -07002207 mInputRoutes.clear();
Eric Laurentd4692962014-05-05 18:13:44 -07002208 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002209 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002210 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002211
2212 if (patchRemoved) {
2213 mpClientInterface->onAudioPatchListUpdate();
2214 }
Eric Laurentd4692962014-05-05 18:13:44 -07002215}
2216
Eric Laurente0720872014-03-11 09:30:41 -07002217void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002218 int indexMin,
2219 int indexMax)
2220{
2221 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002222 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002223
2224 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002225 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2226 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002227 continue;
2228 }
2229 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002230 }
Eric Laurente552edb2014-03-10 17:42:56 -07002231}
2232
Eric Laurente0720872014-03-11 09:30:41 -07002233status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002234 int index,
2235 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002236{
2237
Nadav Bar7c605f62017-12-25 00:01:52 +02002238 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2239 // app that has MODIFY_PHONE_STATE permission.
2240 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
2241 !(stream == AUDIO_STREAM_VOICE_CALL && index == 0)) ||
François Gaffied1ab2bd2015-12-02 18:20:06 +01002242 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002243 return BAD_VALUE;
2244 }
2245 if (!audio_is_output_device(device)) {
2246 return BAD_VALUE;
2247 }
2248
2249 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002250 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002251
Eric Laurent1fd372e2016-04-06 14:23:53 -07002252 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002253 stream, device, index);
2254
Eric Laurent28d09f02016-03-08 10:43:05 -08002255 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002256 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2257 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002258 continue;
2259 }
2260 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2261 }
Eric Laurente552edb2014-03-10 17:42:56 -07002262
Eric Laurent1fd372e2016-04-06 14:23:53 -07002263 // update volume on all outputs and streams matching the following:
2264 // - The requested stream (or a stream matching for volume control) is active on the output
2265 // - The device (or devices) selected by the strategy corresponding to this stream includes
2266 // the requested device
2267 // - For non default requested device, currently selected device on the output is either the
2268 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002269 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2270 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002271 status_t status = NO_ERROR;
2272 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002273 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2274 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08002275 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2276 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002277 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002278 }
Eric Laurentd3926fe2016-04-15 18:10:07 -07002279 if (!(desc->isStreamActive((audio_stream_type_t)curStream) ||
2280 (isInCall() && (curStream == AUDIO_STREAM_VOICE_CALL)))) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002281 continue;
2282 }
Eric Laurent794fde22016-03-11 09:50:45 -08002283 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002284 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2285 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002286 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2287 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002288 continue;
2289 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002290 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002291 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002292 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07002293 applyVolume = (curDevice & curStreamDevice) != 0;
2294 } else {
2295 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002296 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002297 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002298
Eric Laurente76f29c2016-09-14 17:17:53 -07002299 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002300 //FIXME: workaround for truncated touch sounds
2301 // delayed volume change for system stream to be removed when the problem is
2302 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002303 status_t volStatus =
Eric Laurentdc462862016-07-19 12:29:53 -07002304 checkAndSetVolume((audio_stream_type_t)curStream, index, desc, curDevice,
2305 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002306 if (volStatus != NO_ERROR) {
2307 status = volStatus;
2308 }
2309 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002310 }
Eric Laurente552edb2014-03-10 17:42:56 -07002311 }
2312 return status;
2313}
2314
Eric Laurente0720872014-03-11 09:30:41 -07002315status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002316 int *index,
2317 audio_devices_t device)
2318{
2319 if (index == NULL) {
2320 return BAD_VALUE;
2321 }
2322 if (!audio_is_output_device(device)) {
2323 return BAD_VALUE;
2324 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002325 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002326 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002327 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002328 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2329 }
François Gaffiedfd74092015-03-19 12:10:59 +01002330 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002331
François Gaffied1ab2bd2015-12-02 18:20:06 +01002332 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002333 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2334 return NO_ERROR;
2335}
2336
Eric Laurent36829f92017-04-07 19:04:42 -07002337audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002338{
2339 // select one output among several suitable for global effects.
2340 // The priority is as follows:
2341 // 1: An offloaded output. If the effect ends up not being offloadable,
2342 // AudioFlinger will invalidate the track and the offloaded output
2343 // will be closed causing the effect to be moved to a PCM output.
2344 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002345 // 3: The primary output
2346 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002347
Eric Laurent3b73df72014-03-11 09:06:29 -07002348 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002349 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent36829f92017-04-07 19:04:42 -07002350 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002351
Eric Laurent36829f92017-04-07 19:04:42 -07002352 if (outputs.size() == 0) {
2353 return AUDIO_IO_HANDLE_NONE;
2354 }
Eric Laurente552edb2014-03-10 17:42:56 -07002355
Eric Laurent36829f92017-04-07 19:04:42 -07002356 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2357 bool activeOnly = true;
2358
2359 while (output == AUDIO_IO_HANDLE_NONE) {
2360 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2361 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2362 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2363
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002364 for (audio_io_handle_t output : outputs) {
2365 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002366 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2367 continue;
2368 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002369 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2370 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002371 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002372 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002373 }
2374 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002375 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002376 }
2377 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002378 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002379 }
2380 }
2381 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2382 output = outputOffloaded;
2383 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2384 output = outputDeepBuffer;
2385 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2386 output = outputPrimary;
2387 } else {
2388 output = outputs[0];
2389 }
2390 activeOnly = false;
2391 }
2392
2393 if (output != mMusicEffectOutput) {
2394 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2395 mMusicEffectOutput = output;
2396 }
2397
2398 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002399 return output;
2400}
2401
Eric Laurent36829f92017-04-07 19:04:42 -07002402audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2403{
2404 return selectOutputForMusicEffects();
2405}
2406
Eric Laurente0720872014-03-11 09:30:41 -07002407status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002408 audio_io_handle_t io,
2409 uint32_t strategy,
2410 int session,
2411 int id)
2412{
2413 ssize_t index = mOutputs.indexOfKey(io);
2414 if (index < 0) {
2415 index = mInputs.indexOfKey(io);
2416 if (index < 0) {
2417 ALOGW("registerEffect() unknown io %d", io);
2418 return INVALID_OPERATION;
2419 }
2420 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002421 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002422}
2423
Eric Laurentc75307b2015-03-17 15:29:32 -07002424bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2425{
Eric Laurent28d09f02016-03-08 10:43:05 -08002426 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002427 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2428 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002429 continue;
2430 }
2431 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2432 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002433 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002434}
2435
2436bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2437{
2438 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2439}
2440
Eric Laurente0720872014-03-11 09:30:41 -07002441bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002442{
2443 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002444 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002445 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002446 return true;
2447 }
2448 }
2449 return false;
2450}
2451
Eric Laurent275e8e92014-11-30 15:14:47 -08002452// Register a list of custom mixes with their attributes and format.
2453// When a mix is registered, corresponding input and output profiles are
2454// added to the remote submix hw module. The profile contains only the
2455// parameters (sampling rate, format...) specified by the mix.
2456// The corresponding input remote submix device is also connected.
2457//
2458// When a remote submix device is connected, the address is checked to select the
2459// appropriate profile and the corresponding input or output stream is opened.
2460//
2461// When capture starts, getInputForAttr() will:
2462// - 1 look for a mix matching the address passed in attribtutes tags if any
2463// - 2 if none found, getDeviceForInputSource() will:
2464// - 2.1 look for a mix matching the attributes source
2465// - 2.2 if none found, default to device selection by policy rules
2466// At this time, the corresponding output remote submix device is also connected
2467// and active playback use cases can be transferred to this mix if needed when reconnecting
2468// after AudioTracks are invalidated
2469//
2470// When playback starts, getOutputForAttr() will:
2471// - 1 look for a mix matching the address passed in attribtutes tags if any
2472// - 2 if none found, look for a mix matching the attributes usage
2473// - 3 if none found, default to device and output selection by policy rules.
2474
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002475status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002476{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002477 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2478 status_t res = NO_ERROR;
2479
2480 sp<HwModule> rSubmixModule;
2481 // examine each mix's route type
2482 for (size_t i = 0; i < mixes.size(); i++) {
2483 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
2484 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
2485 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002486 break;
2487 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002488 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002489 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002490 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002491 rSubmixModule = mHwModules.getModuleFromName(
2492 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2493 if (rSubmixModule == 0) {
2494 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2495 i);
2496 res = INVALID_OPERATION;
2497 break;
2498 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002499 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002500
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002501 String8 address = mixes[i].mDeviceAddress;
François Gaffie036e1e92015-03-19 10:16:24 +01002502
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002503 if (mPolicyMixes.registerMix(address, mixes[i], 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002504 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002505 res = INVALID_OPERATION;
2506 break;
2507 }
2508 audio_config_t outputConfig = mixes[i].mFormat;
2509 audio_config_t inputConfig = mixes[i].mFormat;
2510 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2511 // stereo and let audio flinger do the channel conversion if needed.
2512 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2513 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2514 rSubmixModule->addOutputProfile(address, &outputConfig,
2515 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2516 rSubmixModule->addInputProfile(address, &inputConfig,
2517 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002518
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002519 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
2520 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2521 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2522 address.string(), "remote-submix");
2523 } else {
2524 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2525 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2526 address.string(), "remote-submix");
2527 }
2528 } else if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002529 String8 address = mixes[i].mDeviceAddress;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002530 audio_devices_t device = mixes[i].mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002531 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2532 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002533
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002534 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002535 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2536 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2537 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2538 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2539 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2540 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002541 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2542 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002543 if (mPolicyMixes.registerMix(address, mixes[i], desc) != NO_ERROR) {
2544 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002545 } else {
2546 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002547 }
2548 break;
2549 }
2550 }
2551
2552 if (res != NO_ERROR) {
2553 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002554 i, device, address.string());
2555 res = INVALID_OPERATION;
2556 break;
2557 } else if (!foundOutput) {
2558 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2559 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002560 res = INVALID_OPERATION;
2561 break;
2562 }
Eric Laurentc722f302014-12-10 11:21:49 -08002563 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002564 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002565 if (res != NO_ERROR) {
2566 unregisterPolicyMixes(mixes);
2567 }
2568 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002569}
2570
2571status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2572{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002573 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002574 status_t res = NO_ERROR;
2575 sp<HwModule> rSubmixModule;
2576 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002577 for (const auto& mix : mixes) {
2578 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002579
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002580 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002581 rSubmixModule = mHwModules.getModuleFromName(
2582 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2583 if (rSubmixModule == 0) {
2584 res = INVALID_OPERATION;
2585 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002586 }
2587 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002588
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002589 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002590
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002591 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2592 res = INVALID_OPERATION;
2593 continue;
2594 }
2595
2596 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2597 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2598 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2599 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2600 address.string(), "remote-submix");
2601 }
2602 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2603 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2604 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2605 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2606 address.string(), "remote-submix");
2607 }
2608 rSubmixModule->removeOutputProfile(address);
2609 rSubmixModule->removeInputProfile(address);
2610
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002611 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2612 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002613 res = INVALID_OPERATION;
2614 continue;
2615 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002616 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002617 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002618 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002619}
2620
Eric Laurente552edb2014-03-10 17:42:56 -07002621
Eric Laurente0720872014-03-11 09:30:41 -07002622status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002623{
Eric Laurente552edb2014-03-10 17:42:56 -07002624 String8 result;
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002625 result.appendFormat("\nAudioPolicyManager Dump: %p\n", this);
2626 result.appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07002627 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002628 std::string stateLiteral;
2629 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002630 result.appendFormat(" Phone state: %s\n", stateLiteral.c_str());
2631 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
2632 "communications", "media", "record", "dock", "system",
2633 "HDMI system audio", "encoded surround output", "vibrate ringing" };
2634 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
2635 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
2636 result.appendFormat(" Force use for %s: %d\n",
2637 forceUses[i], mEngine->getForceUse(i));
2638 }
2639 result.appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
2640 result.appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
2641 result.appendFormat(" Config source: %s\n", getConfig().getSource().c_str());
François Gaffie2110e042015-03-24 08:41:51 +01002642 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002643
François Gaffie112b0af2015-11-19 16:13:25 +01002644 mAvailableOutputDevices.dump(fd, String8("Available output"));
2645 mAvailableInputDevices.dump(fd, String8("Available input"));
Mikhail Naganovd4120142017-12-06 15:49:22 -08002646 mHwModulesAll.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002647 mOutputs.dump(fd);
2648 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002649 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002650 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002651 mAudioPatches.dump(fd);
Mikhail Naganov44344b02016-12-13 11:21:02 -08002652 mPolicyMixes.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002653
2654 return NO_ERROR;
2655}
2656
2657// This function checks for the parameters which can be offloaded.
2658// This can be enhanced depending on the capability of the DSP and policy
2659// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002660bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002661{
2662 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002663 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002664 offloadInfo.sample_rate, offloadInfo.channel_mask,
2665 offloadInfo.format,
2666 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2667 offloadInfo.has_video);
2668
Andy Hung2ddee192015-12-18 17:34:44 -08002669 if (mMasterMono) {
2670 return false; // no offloading if mono is set.
2671 }
2672
Eric Laurente552edb2014-03-10 17:42:56 -07002673 // Check if offload has been disabled
2674 char propValue[PROPERTY_VALUE_MAX];
2675 if (property_get("audio.offload.disable", propValue, "0")) {
2676 if (atoi(propValue) != 0) {
2677 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2678 return false;
2679 }
2680 }
2681
2682 // Check if stream type is music, then only allow offload as of now.
2683 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2684 {
2685 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2686 return false;
2687 }
2688
2689 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002690 const bool allowOffloadWithVideo =
2691 property_get_bool("audio.offload.video", false /* default_value */);
2692 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002693 ALOGV("isOffloadSupported: has_video == true, returning false");
2694 return false;
2695 }
2696
2697 //If duration is less than minimum value defined in property, return false
2698 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2699 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2700 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2701 return false;
2702 }
2703 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2704 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2705 return false;
2706 }
2707
2708 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2709 // creating an offloaded track and tearing it down immediately after start when audioflinger
2710 // detects there is an active non offloadable effect.
2711 // FIXME: We should check the audio session here but we do not have it in this context.
2712 // This may prevent offloading in rare situations where effects are left active by apps
2713 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002714 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002715 return false;
2716 }
2717
2718 // See if there is a profile to support this.
2719 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002720 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002721 offloadInfo.sample_rate,
2722 offloadInfo.format,
2723 offloadInfo.channel_mask,
2724 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002725 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2726 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002727}
2728
Eric Laurent6a94d692014-05-20 11:18:06 -07002729status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2730 audio_port_type_t type,
2731 unsigned int *num_ports,
2732 struct audio_port *ports,
2733 unsigned int *generation)
2734{
2735 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2736 generation == NULL) {
2737 return BAD_VALUE;
2738 }
2739 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2740 if (ports == NULL) {
2741 *num_ports = 0;
2742 }
2743
2744 size_t portsWritten = 0;
2745 size_t portsMax = *num_ports;
2746 *num_ports = 0;
2747 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002748 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2749 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002750 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002751 for (const auto& dev : mAvailableOutputDevices) {
2752 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002753 continue;
2754 }
2755 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002756 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002757 }
2758 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002759 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002760 }
2761 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002762 for (const auto& dev : mAvailableInputDevices) {
2763 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002764 continue;
2765 }
2766 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002767 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002768 }
2769 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002770 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002771 }
2772 }
2773 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2774 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2775 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2776 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2777 }
2778 *num_ports += mInputs.size();
2779 }
2780 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002781 size_t numOutputs = 0;
2782 for (size_t i = 0; i < mOutputs.size(); i++) {
2783 if (!mOutputs[i]->isDuplicated()) {
2784 numOutputs++;
2785 if (portsWritten < portsMax) {
2786 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2787 }
2788 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002789 }
Eric Laurent84c70242014-06-23 08:46:27 -07002790 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002791 }
2792 }
2793 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002794 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002795 return NO_ERROR;
2796}
2797
Eric Laurent99fcae42018-05-17 16:59:18 -07002798status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07002799{
Eric Laurent99fcae42018-05-17 16:59:18 -07002800 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
2801 return BAD_VALUE;
2802 }
2803 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
2804 if (dev != 0) {
2805 dev->toAudioPort(port);
2806 return NO_ERROR;
2807 }
2808 dev = mAvailableInputDevices.getDeviceFromId(port->id);
2809 if (dev != 0) {
2810 dev->toAudioPort(port);
2811 return NO_ERROR;
2812 }
2813 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
2814 if (out != 0) {
2815 out->toAudioPort(port);
2816 return NO_ERROR;
2817 }
2818 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
2819 if (in != 0) {
2820 in->toAudioPort(port);
2821 return NO_ERROR;
2822 }
2823 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002824}
2825
Eric Laurent6a94d692014-05-20 11:18:06 -07002826status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2827 audio_patch_handle_t *handle,
2828 uid_t uid)
2829{
2830 ALOGV("createAudioPatch()");
2831
2832 if (handle == NULL || patch == NULL) {
2833 return BAD_VALUE;
2834 }
2835 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2836
Eric Laurent874c42872014-08-08 15:13:39 -07002837 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2838 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2839 return BAD_VALUE;
2840 }
2841 // only one source per audio patch supported for now
2842 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002843 return INVALID_OPERATION;
2844 }
Eric Laurent874c42872014-08-08 15:13:39 -07002845
2846 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002847 return INVALID_OPERATION;
2848 }
Eric Laurent874c42872014-08-08 15:13:39 -07002849 for (size_t i = 0; i < patch->num_sinks; i++) {
2850 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2851 return INVALID_OPERATION;
2852 }
2853 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002854
2855 sp<AudioPatch> patchDesc;
2856 ssize_t index = mAudioPatches.indexOfKey(*handle);
2857
Eric Laurent6a94d692014-05-20 11:18:06 -07002858 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2859 patch->sources[0].role,
2860 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002861#if LOG_NDEBUG == 0
2862 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002863 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002864 patch->sinks[i].role,
2865 patch->sinks[i].type);
2866 }
2867#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002868
2869 if (index >= 0) {
2870 patchDesc = mAudioPatches.valueAt(index);
2871 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2872 mUidCached, patchDesc->mUid, uid);
2873 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2874 return INVALID_OPERATION;
2875 }
2876 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002877 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002878 }
2879
2880 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002881 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002882 if (outputDesc == NULL) {
2883 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2884 return BAD_VALUE;
2885 }
Eric Laurent84c70242014-06-23 08:46:27 -07002886 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2887 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002888 if (patchDesc != 0) {
2889 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2890 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2891 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2892 return BAD_VALUE;
2893 }
2894 }
Eric Laurent874c42872014-08-08 15:13:39 -07002895 DeviceVector devices;
2896 for (size_t i = 0; i < patch->num_sinks; i++) {
2897 // Only support mix to devices connection
2898 // TODO add support for mix to mix connection
2899 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2900 ALOGV("createAudioPatch() source mix but sink is not a device");
2901 return INVALID_OPERATION;
2902 }
2903 sp<DeviceDescriptor> devDesc =
2904 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2905 if (devDesc == 0) {
2906 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2907 return BAD_VALUE;
2908 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002909
François Gaffie53615e22015-03-19 09:24:12 +01002910 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002911 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002912 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002913 NULL, // updatedSamplingRate
2914 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002915 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002916 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002917 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002918 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002919 ALOGV("createAudioPatch() profile not supported for device %08x",
2920 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002921 return INVALID_OPERATION;
2922 }
2923 devices.add(devDesc);
2924 }
2925 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002926 return INVALID_OPERATION;
2927 }
Eric Laurent874c42872014-08-08 15:13:39 -07002928
Eric Laurent6a94d692014-05-20 11:18:06 -07002929 // TODO: reconfigure output format and channels here
2930 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002931 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002932 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002933 index = mAudioPatches.indexOfKey(*handle);
2934 if (index >= 0) {
2935 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2936 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2937 }
2938 patchDesc = mAudioPatches.valueAt(index);
2939 patchDesc->mUid = uid;
2940 ALOGV("createAudioPatch() success");
2941 } else {
2942 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2943 return INVALID_OPERATION;
2944 }
2945 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2946 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2947 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002948 // only one sink supported when connecting an input device to a mix
2949 if (patch->num_sinks > 1) {
2950 return INVALID_OPERATION;
2951 }
François Gaffie53615e22015-03-19 09:24:12 +01002952 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002953 if (inputDesc == NULL) {
2954 return BAD_VALUE;
2955 }
2956 if (patchDesc != 0) {
2957 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2958 return BAD_VALUE;
2959 }
2960 }
2961 sp<DeviceDescriptor> devDesc =
2962 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2963 if (devDesc == 0) {
2964 return BAD_VALUE;
2965 }
2966
François Gaffie53615e22015-03-19 09:24:12 +01002967 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002968 devDesc->mAddress,
2969 patch->sinks[0].sample_rate,
2970 NULL, /*updatedSampleRate*/
2971 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002972 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002973 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002974 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002975 // FIXME for the parameter type,
2976 // and the NONE
2977 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002978 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002979 return INVALID_OPERATION;
2980 }
2981 // TODO: reconfigure output format and channels here
2982 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01002983 devDesc->type(), inputDesc->mIoHandle);
2984 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002985 index = mAudioPatches.indexOfKey(*handle);
2986 if (index >= 0) {
2987 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2988 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2989 }
2990 patchDesc = mAudioPatches.valueAt(index);
2991 patchDesc->mUid = uid;
2992 ALOGV("createAudioPatch() success");
2993 } else {
2994 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2995 return INVALID_OPERATION;
2996 }
2997 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2998 // device to device connection
2999 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003000 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003001 return BAD_VALUE;
3002 }
3003 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003004 sp<DeviceDescriptor> srcDeviceDesc =
3005 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07003006 if (srcDeviceDesc == 0) {
3007 return BAD_VALUE;
3008 }
Eric Laurent874c42872014-08-08 15:13:39 -07003009
Eric Laurent6a94d692014-05-20 11:18:06 -07003010 //update source and sink with our own data as the data passed in the patch may
3011 // be incomplete.
3012 struct audio_patch newPatch = *patch;
3013 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003014
Eric Laurent874c42872014-08-08 15:13:39 -07003015 for (size_t i = 0; i < patch->num_sinks; i++) {
3016 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3017 ALOGV("createAudioPatch() source device but one sink is not a device");
3018 return INVALID_OPERATION;
3019 }
3020
3021 sp<DeviceDescriptor> sinkDeviceDesc =
3022 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3023 if (sinkDeviceDesc == 0) {
3024 return BAD_VALUE;
3025 }
3026 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
3027
Eric Laurent3bcf8592015-04-03 12:13:24 -07003028 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003029 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003030 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08003031 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003032 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003033 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003034 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003035 return INVALID_OPERATION;
3036 }
Eric Laurent874c42872014-08-08 15:13:39 -07003037 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01003038 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003039 // if the sink device is reachable via an opened output stream, request to go via
3040 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07003041 audio_io_handle_t output = selectOutput(outputs,
3042 AUDIO_OUTPUT_FLAG_NONE,
3043 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07003044 if (output != AUDIO_IO_HANDLE_NONE) {
3045 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3046 if (outputDesc->isDuplicated()) {
3047 return INVALID_OPERATION;
3048 }
3049 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003050 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003051 newPatch.num_sources = 2;
3052 }
Eric Laurent83b88082014-06-20 18:31:16 -07003053 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003054 }
3055 // TODO: check from routing capabilities in config file and other conflicting patches
3056
Mikhail Naganovdc769682018-05-04 15:34:08 -07003057 status_t status = installPatch(__func__, index, handle, &newPatch, 0, uid, &patchDesc);
3058 if (status != NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003059 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3060 status);
3061 return INVALID_OPERATION;
3062 }
3063 } else {
3064 return BAD_VALUE;
3065 }
3066 } else {
3067 return BAD_VALUE;
3068 }
3069 return NO_ERROR;
3070}
3071
3072status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3073 uid_t uid)
3074{
3075 ALOGV("releaseAudioPatch() patch %d", handle);
3076
3077 ssize_t index = mAudioPatches.indexOfKey(handle);
3078
3079 if (index < 0) {
3080 return BAD_VALUE;
3081 }
3082 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3083 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3084 mUidCached, patchDesc->mUid, uid);
3085 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3086 return INVALID_OPERATION;
3087 }
3088
3089 struct audio_patch *patch = &patchDesc->mPatch;
3090 patchDesc->mUid = mUidCached;
3091 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003092 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003093 if (outputDesc == NULL) {
3094 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3095 return BAD_VALUE;
3096 }
3097
Eric Laurentc75307b2015-03-17 15:29:32 -07003098 setOutputDevice(outputDesc,
3099 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07003100 true,
3101 0,
3102 NULL);
3103 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3104 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003105 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003106 if (inputDesc == NULL) {
3107 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3108 return BAD_VALUE;
3109 }
3110 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003111 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003112 true,
3113 NULL);
3114 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003115 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3116 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3117 status, patchDesc->mAfPatchHandle);
3118 removeAudioPatch(patchDesc->mHandle);
3119 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003120 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003121 } else {
3122 return BAD_VALUE;
3123 }
3124 } else {
3125 return BAD_VALUE;
3126 }
3127 return NO_ERROR;
3128}
3129
3130status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3131 struct audio_patch *patches,
3132 unsigned int *generation)
3133{
François Gaffie53615e22015-03-19 09:24:12 +01003134 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003135 return BAD_VALUE;
3136 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003137 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003138 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003139}
3140
Eric Laurente1715a42014-05-20 11:30:42 -07003141status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003142{
Eric Laurente1715a42014-05-20 11:30:42 -07003143 ALOGV("setAudioPortConfig()");
3144
3145 if (config == NULL) {
3146 return BAD_VALUE;
3147 }
3148 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3149 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003150 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3151 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003152 }
3153
Eric Laurenta121f902014-06-03 13:32:54 -07003154 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003155 if (config->type == AUDIO_PORT_TYPE_MIX) {
3156 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003157 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003158 if (outputDesc == NULL) {
3159 return BAD_VALUE;
3160 }
Eric Laurent84c70242014-06-23 08:46:27 -07003161 ALOG_ASSERT(!outputDesc->isDuplicated(),
3162 "setAudioPortConfig() called on duplicated output %d",
3163 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003164 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003165 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003166 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003167 if (inputDesc == NULL) {
3168 return BAD_VALUE;
3169 }
Eric Laurenta121f902014-06-03 13:32:54 -07003170 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003171 } else {
3172 return BAD_VALUE;
3173 }
3174 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3175 sp<DeviceDescriptor> deviceDesc;
3176 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3177 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3178 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3179 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3180 } else {
3181 return BAD_VALUE;
3182 }
3183 if (deviceDesc == NULL) {
3184 return BAD_VALUE;
3185 }
Eric Laurenta121f902014-06-03 13:32:54 -07003186 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003187 } else {
3188 return BAD_VALUE;
3189 }
3190
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003191 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003192 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3193 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003194 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003195 audioPortConfig->toAudioPortConfig(&newConfig, config);
3196 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003197 }
Eric Laurenta121f902014-06-03 13:32:54 -07003198 if (status != NO_ERROR) {
3199 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003200 }
Eric Laurente1715a42014-05-20 11:30:42 -07003201
3202 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003203}
3204
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003205void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3206{
Eric Laurentd60560a2015-04-10 11:31:20 -07003207 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003208 clearAudioPatches(uid);
3209 clearSessionRoutes(uid);
3210}
3211
Eric Laurent6a94d692014-05-20 11:18:06 -07003212void AudioPolicyManager::clearAudioPatches(uid_t uid)
3213{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003214 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003215 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3216 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003217 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003218 }
3219 }
3220}
3221
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003222void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3223 audio_io_handle_t ouptutToSkip)
3224{
3225 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3226 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3227 for (size_t j = 0; j < mOutputs.size(); j++) {
3228 if (mOutputs.keyAt(j) == ouptutToSkip) {
3229 continue;
3230 }
3231 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3232 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3233 continue;
3234 }
3235 // If the default device for this strategy is on another output mix,
3236 // invalidate all tracks in this strategy to force re connection.
3237 // Otherwise select new device on the output mix.
3238 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003239 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003240 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3241 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3242 }
3243 }
3244 } else {
3245 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3246 setOutputDevice(outputDesc, newDevice, false);
3247 }
3248 }
3249}
3250
3251void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3252{
3253 // remove output routes associated with this uid
3254 SortedVector<routing_strategy> affectedStrategies;
3255 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
3256 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
3257 if (route->mUid == uid) {
3258 mOutputRoutes.removeItemsAt(i);
3259 if (route->mDeviceDescriptor != 0) {
3260 affectedStrategies.add(getStrategy(route->mStreamType));
3261 }
3262 }
3263 }
3264 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003265 for (const auto& strategy : affectedStrategies) {
3266 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003267 }
3268
3269 // remove input routes associated with this uid
3270 SortedVector<audio_source_t> affectedSources;
3271 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
3272 sp<SessionRoute> route = mInputRoutes.valueAt(i);
3273 if (route->mUid == uid) {
3274 mInputRoutes.removeItemsAt(i);
3275 if (route->mDeviceDescriptor != 0) {
3276 affectedSources.add(route->mSource);
3277 }
3278 }
3279 }
3280 // reroute inputs if necessary
3281 SortedVector<audio_io_handle_t> inputsToClose;
3282 for (size_t i = 0; i < mInputs.size(); i++) {
3283 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003284 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003285 inputsToClose.add(inputDesc->mIoHandle);
3286 }
3287 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003288 for (const auto& input : inputsToClose) {
3289 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003290 }
3291}
3292
Eric Laurentd60560a2015-04-10 11:31:20 -07003293void AudioPolicyManager::clearAudioSources(uid_t uid)
3294{
3295 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
3296 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3297 if (sourceDesc->mUid == uid) {
3298 stopAudioSource(mAudioSources.keyAt(i));
3299 }
3300 }
3301}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003302
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003303status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3304 audio_io_handle_t *ioHandle,
3305 audio_devices_t *device)
3306{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003307 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3308 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003309 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003310
François Gaffiedf372692015-03-19 10:43:27 +01003311 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003312}
3313
Eric Laurentd60560a2015-04-10 11:31:20 -07003314status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
3315 const audio_attributes_t *attributes,
Glenn Kasten559d4392016-03-29 13:42:57 -07003316 audio_patch_handle_t *handle,
Eric Laurentd60560a2015-04-10 11:31:20 -07003317 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003318{
Eric Laurentd60560a2015-04-10 11:31:20 -07003319 ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle);
3320 if (source == NULL || attributes == NULL || handle == NULL) {
3321 return BAD_VALUE;
3322 }
3323
Glenn Kasten559d4392016-03-29 13:42:57 -07003324 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003325
3326 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3327 source->type != AUDIO_PORT_TYPE_DEVICE) {
3328 ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type);
3329 return INVALID_OPERATION;
3330 }
3331
3332 sp<DeviceDescriptor> srcDeviceDesc =
3333 mAvailableInputDevices.getDevice(source->ext.device.type,
3334 String8(source->ext.device.address));
3335 if (srcDeviceDesc == 0) {
3336 ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
3337 return BAD_VALUE;
3338 }
3339 sp<AudioSourceDescriptor> sourceDesc =
3340 new AudioSourceDescriptor(srcDeviceDesc, attributes, uid);
3341
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003342 struct audio_patch dummyPatch = {};
Eric Laurentd60560a2015-04-10 11:31:20 -07003343 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
3344 sourceDesc->mPatchDesc = patchDesc;
3345
3346 status_t status = connectAudioSource(sourceDesc);
3347 if (status == NO_ERROR) {
3348 mAudioSources.add(sourceDesc->getHandle(), sourceDesc);
3349 *handle = sourceDesc->getHandle();
3350 }
3351 return status;
3352}
3353
3354status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3355{
3356 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3357
3358 // make sure we only have one patch per source.
3359 disconnectAudioSource(sourceDesc);
3360
3361 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
Eric Laurent28d09f02016-03-08 10:43:05 -08003362 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003363 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice;
3364
3365 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3366 sp<DeviceDescriptor> sinkDeviceDesc =
3367 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3368
3369 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003370
3371 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3372 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003373 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003374 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3375 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3376 // create patch between src device and output device
3377 // create Hwoutput and add to mHwOutputs
3378 } else {
3379 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3380 audio_io_handle_t output =
3381 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3382 if (output == AUDIO_IO_HANDLE_NONE) {
3383 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3384 return INVALID_OPERATION;
3385 }
3386 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3387 if (outputDesc->isDuplicated()) {
3388 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3389 return INVALID_OPERATION;
3390 }
Eric Laurent733ce942017-12-07 12:18:25 -08003391 status_t status = outputDesc->start();
3392 if (status != NO_ERROR) {
3393 return status;
3394 }
3395
Eric Laurentd60560a2015-04-10 11:31:20 -07003396 // create a special patch with no sink and two sources:
3397 // - the second source indicates to PatchPanel through which output mix this patch should
3398 // be connected as well as the stream type for volume control
3399 // - the sink is defined by whatever output device is currently selected for the output
3400 // though which this patch is routed.
Mikhail Naganovdc769682018-05-04 15:34:08 -07003401 PatchBuilder patchBuilder;
3402 patchBuilder.addSource(srcDeviceDesc).addSource(outputDesc, { .stream = stream });
3403 status = mpClientInterface->createAudioPatch(patchBuilder.patch(),
Eric Laurentd60560a2015-04-10 11:31:20 -07003404 &afPatchHandle,
3405 0);
3406 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3407 status, afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07003408 sourceDesc->mPatchDesc->mPatch = *patchBuilder.patch();
Eric Laurentd60560a2015-04-10 11:31:20 -07003409 if (status != NO_ERROR) {
3410 ALOGW("%s patch panel could not connect device patch, error %d",
3411 __FUNCTION__, status);
3412 return INVALID_OPERATION;
3413 }
3414 uint32_t delayMs = 0;
Eric Laurentc40d9692016-04-13 19:14:13 -07003415 status = startSource(outputDesc, stream, sinkDevice, NULL, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003416
3417 if (status != NO_ERROR) {
3418 mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0);
3419 return status;
3420 }
3421 sourceDesc->mSwOutput = outputDesc;
3422 if (delayMs != 0) {
3423 usleep(delayMs * 1000);
3424 }
3425 }
3426
3427 sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle;
3428 addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc);
3429
3430 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003431}
3432
Glenn Kasten559d4392016-03-29 13:42:57 -07003433status_t AudioPolicyManager::stopAudioSource(audio_patch_handle_t handle __unused)
Eric Laurent554a2772015-04-10 11:29:24 -07003434{
Eric Laurentd60560a2015-04-10 11:31:20 -07003435 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle);
3436 ALOGV("%s handle %d", __FUNCTION__, handle);
3437 if (sourceDesc == 0) {
3438 ALOGW("%s unknown source for handle %d", __FUNCTION__, handle);
3439 return BAD_VALUE;
3440 }
3441 status_t status = disconnectAudioSource(sourceDesc);
3442
3443 mAudioSources.removeItem(handle);
3444 return status;
3445}
3446
Andy Hung2ddee192015-12-18 17:34:44 -08003447status_t AudioPolicyManager::setMasterMono(bool mono)
3448{
3449 if (mMasterMono == mono) {
3450 return NO_ERROR;
3451 }
3452 mMasterMono = mono;
3453 // if enabling mono we close all offloaded devices, which will invalidate the
3454 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3455 // for recreating the new AudioTrack as non-offloaded PCM.
3456 //
3457 // If disabling mono, we leave all tracks as is: we don't know which clients
3458 // and tracks are able to be recreated as offloaded. The next "song" should
3459 // play back offloaded.
3460 if (mMasterMono) {
3461 Vector<audio_io_handle_t> offloaded;
3462 for (size_t i = 0; i < mOutputs.size(); ++i) {
3463 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3464 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3465 offloaded.push(desc->mIoHandle);
3466 }
3467 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003468 for (const auto& handle : offloaded) {
3469 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003470 }
3471 }
3472 // update master mono for all remaining outputs
3473 for (size_t i = 0; i < mOutputs.size(); ++i) {
3474 updateMono(mOutputs.keyAt(i));
3475 }
3476 return NO_ERROR;
3477}
3478
3479status_t AudioPolicyManager::getMasterMono(bool *mono)
3480{
3481 *mono = mMasterMono;
3482 return NO_ERROR;
3483}
3484
Eric Laurentac9cef52017-06-09 15:46:26 -07003485float AudioPolicyManager::getStreamVolumeDB(
3486 audio_stream_type_t stream, int index, audio_devices_t device)
3487{
3488 return computeVolume(stream, index, device);
3489}
3490
jiabin81772902018-04-02 17:52:27 -07003491status_t AudioPolicyManager::getSupportedFormats(audio_io_handle_t ioHandle,
3492 FormatVector& formats) {
3493 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
3494 return BAD_VALUE;
3495 }
3496 String8 reply;
3497 reply = mpClientInterface->getParameters(
3498 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
3499 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
3500 AudioParameter repliedParameters(reply);
3501 if (repliedParameters.get(
3502 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
3503 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
3504 return BAD_VALUE;
3505 }
3506 for (auto format : formatsFromString(reply.string())) {
3507 // Only AUDIO_FORMAT_AAC_LC will be used in Settings UI for all AAC formats.
3508 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3509 if (format == AAC_FORMATS[i]) {
3510 format = AUDIO_FORMAT_AAC_LC;
3511 break;
3512 }
3513 }
3514 bool exist = false;
3515 for (size_t i = 0; i < formats.size(); i++) {
3516 if (format == formats[i]) {
3517 exist = true;
3518 break;
3519 }
3520 }
3521 bool isSurroundFormat = false;
3522 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3523 if (SURROUND_FORMATS[i] == format) {
3524 isSurroundFormat = true;
3525 break;
3526 }
3527 }
3528 if (!exist && isSurroundFormat) {
3529 formats.add(format);
3530 }
3531 }
3532 return NO_ERROR;
3533}
3534
3535status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3536 audio_format_t *surroundFormats,
3537 bool *surroundFormatsEnabled,
3538 bool reported)
3539{
3540 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3541 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3542 return BAD_VALUE;
3543 }
3544 ALOGV("getSurroundFormats() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
3545 *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
3546
3547 // Only return value if there is HDMI output.
3548 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3549 return INVALID_OPERATION;
3550 }
3551
3552 size_t formatsWritten = 0;
3553 size_t formatsMax = *numSurroundFormats;
3554 *numSurroundFormats = 0;
3555 FormatVector formats;
3556 if (reported) {
3557 // Only get surround formats which are reported by device.
3558 // First list already open outputs that can be routed to this device
3559 audio_devices_t device = AUDIO_DEVICE_OUT_HDMI;
3560 SortedVector<audio_io_handle_t> outputs;
3561 bool reportedFormatFound = false;
3562 status_t status;
3563 sp<SwAudioOutputDescriptor> desc;
3564 for (size_t i = 0; i < mOutputs.size(); i++) {
3565 desc = mOutputs.valueAt(i);
3566 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
3567 outputs.add(mOutputs.keyAt(i));
3568 }
3569 }
3570 // Open an output to query dynamic parameters.
Mikhail Naganov708e0382018-05-30 09:53:04 -07003571 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003572 AUDIO_DEVICE_OUT_HDMI);
3573 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3574 String8 address = hdmiOutputDevices[i]->mAddress;
3575 for (const auto& hwModule : mHwModules) {
3576 for (size_t i = 0; i < hwModule->getOutputProfiles().size(); i++) {
3577 sp<IOProfile> profile = hwModule->getOutputProfiles()[i];
3578 if (profile->supportDevice(AUDIO_DEVICE_OUT_HDMI) &&
3579 profile->supportDeviceAddress(address)) {
3580 size_t j;
3581 for (j = 0; j < outputs.size(); j++) {
3582 desc = mOutputs.valueFor(outputs.itemAt(j));
3583 if (!desc->isDuplicated() && desc->mProfile == profile) {
3584 break;
3585 }
3586 }
3587 if (j != outputs.size()) {
3588 status = getSupportedFormats(outputs.itemAt(j), formats);
3589 reportedFormatFound |= (status == NO_ERROR);
3590 continue;
3591 }
3592
3593 if (!profile->canOpenNewIo()) {
3594 ALOGW("Max Output number %u already opened for this profile %s",
3595 profile->maxOpenCount, profile->getTagName().c_str());
3596 continue;
3597 }
3598
3599 ALOGV("opening output for device %08x with params %s profile %p name %s",
3600 device, address.string(), profile.get(), profile->getName().string());
3601 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
3602 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3603 status_t status = desc->open(nullptr, device, address,
3604 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE,
3605 &output);
3606
3607 if (status == NO_ERROR) {
3608 status = getSupportedFormats(output, formats);
3609 reportedFormatFound |= (status == NO_ERROR);
3610 desc->close();
3611 output = AUDIO_IO_HANDLE_NONE;
3612 }
3613 }
3614 }
3615 }
3616 }
3617
3618 if (!reportedFormatFound) {
3619 return UNKNOWN_ERROR;
3620 }
3621 } else {
3622 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3623 formats.add(SURROUND_FORMATS[i]);
3624 }
3625 }
3626 for (size_t i = 0; i < formats.size(); i++) {
3627 if (formatsWritten < formatsMax) {
3628 surroundFormats[formatsWritten] = formats[i];
3629 bool formatEnabled = false;
3630 if (formats[i] == AUDIO_FORMAT_AAC_LC) {
3631 for (size_t j = 0; j < ARRAY_SIZE(AAC_FORMATS); j++) {
3632 formatEnabled =
3633 mSurroundFormats.find(AAC_FORMATS[i]) != mSurroundFormats.end();
3634 break;
3635 }
3636 } else {
3637 formatEnabled = mSurroundFormats.find(formats[i]) != mSurroundFormats.end();
3638 }
3639 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3640 }
3641 (*numSurroundFormats)++;
3642 }
3643 return NO_ERROR;
3644}
3645
3646status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3647{
3648 // Check if audio format is a surround formats.
3649 bool isSurroundFormat = false;
3650 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3651 if (audioFormat == SURROUND_FORMATS[i]) {
3652 isSurroundFormat = true;
3653 break;
3654 }
3655 }
3656 if (!isSurroundFormat) {
3657 return BAD_VALUE;
3658 }
3659
3660 // Should only be called when MANUAL.
3661 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3662 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
3663 if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3664 return INVALID_OPERATION;
3665 }
3666
3667 if ((mSurroundFormats.find(audioFormat) != mSurroundFormats.end() && enabled)
3668 || (mSurroundFormats.find(audioFormat) == mSurroundFormats.end() && !enabled)) {
3669 return NO_ERROR;
3670 }
3671
3672 // The operation is valid only when there is HDMI output available.
3673 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3674 return INVALID_OPERATION;
3675 }
3676
3677 if (enabled) {
3678 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3679 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3680 mSurroundFormats.insert(AAC_FORMATS[i]);
3681 }
3682 } else {
3683 mSurroundFormats.insert(audioFormat);
3684 }
3685 } else {
3686 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3687 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3688 mSurroundFormats.erase(AAC_FORMATS[i]);
3689 }
3690 } else {
3691 mSurroundFormats.erase(audioFormat);
3692 }
3693 }
3694
3695 sp<SwAudioOutputDescriptor> outputDesc;
3696 bool profileUpdated = false;
Mikhail Naganov708e0382018-05-30 09:53:04 -07003697 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003698 AUDIO_DEVICE_OUT_HDMI);
3699 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3700 // Simulate reconnection to update enabled surround sound formats.
3701 String8 address = hdmiOutputDevices[i]->mAddress;
3702 String8 name = hdmiOutputDevices[i]->getName();
3703 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3704 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3705 address.c_str(),
3706 name.c_str());
3707 if (status != NO_ERROR) {
3708 continue;
3709 }
3710 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3711 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3712 address.c_str(),
3713 name.c_str());
3714 profileUpdated |= (status == NO_ERROR);
3715 }
Mikhail Naganov708e0382018-05-30 09:53:04 -07003716 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003717 AUDIO_DEVICE_IN_HDMI);
3718 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3719 // Simulate reconnection to update enabled surround sound formats.
3720 String8 address = hdmiInputDevices[i]->mAddress;
3721 String8 name = hdmiInputDevices[i]->getName();
3722 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3723 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3724 address.c_str(),
3725 name.c_str());
3726 if (status != NO_ERROR) {
3727 continue;
3728 }
3729 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3730 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3731 address.c_str(),
3732 name.c_str());
3733 profileUpdated |= (status == NO_ERROR);
3734 }
3735
3736 // Undo the surround formats change due to no audio profiles updated.
3737 if (!profileUpdated) {
3738 if (enabled) {
3739 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3740 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3741 mSurroundFormats.erase(AAC_FORMATS[i]);
3742 }
3743 } else {
3744 mSurroundFormats.erase(audioFormat);
3745 }
3746 } else {
3747 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3748 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3749 mSurroundFormats.insert(AAC_FORMATS[i]);
3750 }
3751 } else {
3752 mSurroundFormats.insert(audioFormat);
3753 }
3754 }
3755 }
3756
3757 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3758}
3759
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003760void AudioPolicyManager::setRecordSilenced(uid_t uid, bool silenced)
3761{
3762 ALOGV("AudioPolicyManager:setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
3763
3764 Vector<sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
3765 for (size_t i = 0; i < activeInputs.size(); i++) {
3766 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
3767 AudioSessionCollection activeSessions = activeDesc->getAudioSessions(true);
3768 for (size_t j = 0; j < activeSessions.size(); j++) {
3769 sp<AudioSession> activeSession = activeSessions.valueAt(j);
3770 if (activeSession->uid() == uid) {
3771 activeSession->setSilenced(silenced);
3772 }
3773 }
3774 }
3775}
3776
Eric Laurentd60560a2015-04-10 11:31:20 -07003777status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3778{
3779 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3780
3781 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle);
3782 if (patchDesc == 0) {
3783 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
3784 sourceDesc->mPatchDesc->mHandle);
3785 return BAD_VALUE;
3786 }
3787 removeAudioPatch(sourceDesc->mPatchDesc->mHandle);
3788
Eric Laurent28d09f02016-03-08 10:43:05 -08003789 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003790 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote();
3791 if (swOutputDesc != 0) {
Eric Laurent733ce942017-12-07 12:18:25 -08003792 status_t status = stopSource(swOutputDesc, stream, false);
3793 if (status == NO_ERROR) {
3794 swOutputDesc->stop();
3795 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003796 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3797 } else {
3798 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote();
3799 if (hwOutputDesc != 0) {
3800 // release patch between src device and output device
3801 // close Hwoutput and remove from mHwOutputs
3802 } else {
3803 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3804 }
3805 }
3806 return NO_ERROR;
3807}
3808
3809sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
3810 audio_io_handle_t output, routing_strategy strategy)
3811{
3812 sp<AudioSourceDescriptor> source;
3813 for (size_t i = 0; i < mAudioSources.size(); i++) {
3814 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3815 routing_strategy sourceStrategy =
3816 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
3817 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote();
3818 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3819 source = sourceDesc;
3820 break;
3821 }
3822 }
3823 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003824}
3825
Eric Laurente552edb2014-03-10 17:42:56 -07003826// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003827// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003828// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003829uint32_t AudioPolicyManager::nextAudioPortGeneration()
3830{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003831 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003832}
3833
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003834#ifdef USE_XML_AUDIO_POLICY_CONF
3835// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3836static const char *kConfigLocationList[] =
3837 {"/odm/etc", "/vendor/etc", "/system/etc"};
3838static const int kConfigLocationListSize =
3839 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3840
3841static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3842 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07003843 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003844 status_t ret;
3845
Petri Gyntherf497f292018-04-17 18:46:10 -07003846 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
3847 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
3848 // A2DP offload supported but disabled: try to use special XML file
3849 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
3850 }
3851 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3852
3853 for (const char* fileName : fileNames) {
3854 for (int i = 0; i < kConfigLocationListSize; i++) {
3855 PolicySerializer serializer;
3856 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
3857 "%s/%s", kConfigLocationList[i], fileName);
3858 ret = serializer.deserialize(audioPolicyXmlConfigFile, config);
3859 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003860 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07003861 return ret;
3862 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003863 }
3864 }
3865 return ret;
3866}
3867#endif
3868
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003869AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
3870 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07003871 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07003872 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003873 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07003874 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003875 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003876#ifdef USE_XML_AUDIO_POLICY_CONF
3877 mVolumeCurves(new VolumeCurvesCollection()),
3878 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08003879 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003880#else
3881 mVolumeCurves(new StreamDescriptorCollection()),
3882 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
3883 mDefaultOutputDevice),
3884#endif
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003885 mAudioPortGeneration(1),
3886 mBeaconMuteRefCount(0),
3887 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003888 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003889 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003890 mMasterMono(false),
Chris Thornton2b864642017-06-27 21:26:07 -07003891 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE),
3892 mHasComputedSoundTriggerSupportsConcurrentCapture(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003893{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003894}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003895
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003896AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
3897 : AudioPolicyManager(clientInterface, false /*forTesting*/)
3898{
3899 loadConfig();
3900 initialize();
3901}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003902
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003903void AudioPolicyManager::loadConfig() {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003904#ifdef USE_XML_AUDIO_POLICY_CONF
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003905 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003906#else
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003907 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, getConfig()) != NO_ERROR)
3908 && (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, getConfig()) != NO_ERROR)) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003909#endif
3910 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003911 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01003912 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003913}
3914
3915status_t AudioPolicyManager::initialize() {
3916 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01003917
3918 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003919 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3920 if (!engineInstance) {
3921 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003922 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003923 }
3924 // Retrieve the Policy Manager Interface
3925 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3926 if (mEngine == NULL) {
3927 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003928 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003929 }
3930 mEngine->setObserver(this);
3931 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003932 if (status != NO_ERROR) {
3933 LOG_FATAL("Policy engine not initialized(err=%d)", status);
3934 return status;
3935 }
François Gaffie2110e042015-03-24 08:41:51 +01003936
Eric Laurent3a4311c2014-03-17 12:00:47 -07003937 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003938 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003939 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3940 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Mikhail Naganovd4120142017-12-06 15:49:22 -08003941 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003942 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08003943 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
3944 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003945 continue;
3946 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08003947 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07003948 // open all output streams needed to access attached devices
3949 // except for direct output streams that are only opened when they are actually
3950 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003951 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003952 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003953 if (!outProfile->canOpenNewIo()) {
3954 ALOGE("Invalid Output profile max open count %u for profile %s",
3955 outProfile->maxOpenCount, outProfile->getTagName().c_str());
3956 continue;
3957 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003958 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003959 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003960 continue;
3961 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003962 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003963 mTtsOutputAvailable = true;
3964 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003965
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003966 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003967 continue;
3968 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003969 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003970 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3971 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003972 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003973 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003974 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003975 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003976 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003977 if ((profileType & outputDeviceTypes) == 0) {
3978 continue;
3979 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003980 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3981 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003982 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov708e0382018-05-30 09:53:04 -07003983 const DeviceVector &devicesForType = supportedDevices.getDevicesFromTypeMask(
3984 profileType);
Eric Laurentc40d9692016-04-13 19:14:13 -07003985 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3986 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003987 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08003988 status_t status = outputDesc->open(nullptr, profileType, address,
3989 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07003990
3991 if (status != NO_ERROR) {
3992 ALOGW("Cannot open output stream for device %08x on hw module %s",
3993 outputDesc->mDevice,
Mikhail Naganovd4120142017-12-06 15:49:22 -08003994 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003995 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003996 for (const auto& dev : supportedDevices) {
3997 ssize_t index = mAvailableOutputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07003998 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003999 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004000 mAvailableOutputDevices[index]->attach(hwModule);
Eric Laurentd78f1532014-09-16 16:38:20 -07004001 }
4002 }
4003 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004004 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004005 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07004006 }
4007 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07004008 setOutputDevice(outputDesc,
Eric Laurentfe231122017-11-17 17:48:06 -08004009 profileType,
Eric Laurentc40d9692016-04-13 19:14:13 -07004010 true,
4011 0,
4012 NULL,
Eric Laurentfe231122017-11-17 17:48:06 -08004013 address);
Eric Laurentd78f1532014-09-16 16:38:20 -07004014 }
Eric Laurente552edb2014-03-10 17:42:56 -07004015 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004016 // open input streams needed to access attached devices to validate
4017 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004018 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004019 if (!inProfile->canOpenNewIo()) {
4020 ALOGE("Invalid Input profile max open count %u for profile %s",
4021 inProfile->maxOpenCount, inProfile->getTagName().c_str());
4022 continue;
4023 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004024 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004025 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004026 continue;
4027 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004028 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07004029 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004030 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
4031
Eric Laurentd78f1532014-09-16 16:38:20 -07004032 if ((profileType & inputDeviceTypes) == 0) {
4033 continue;
4034 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08004035 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08004036 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004037
Mikhail Naganov708e0382018-05-30 09:53:04 -07004038 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(profileType);
Eric Laurent53b810e2017-12-10 17:25:10 -08004039 // the inputs vector must be of size >= 1, but we don't want to crash here
4040 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
4041 : String8("");
4042 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
4043 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
4044
Eric Laurentd78f1532014-09-16 16:38:20 -07004045 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004046 status_t status = inputDesc->open(nullptr,
4047 profileType,
Eric Laurent53b810e2017-12-10 17:25:10 -08004048 address,
Eric Laurentfe231122017-11-17 17:48:06 -08004049 AUDIO_SOURCE_MIC,
4050 AUDIO_INPUT_FLAG_NONE,
4051 &input);
Eric Laurentd78f1532014-09-16 16:38:20 -07004052
4053 if (status == NO_ERROR) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004054 for (const auto& dev : inProfile->getSupportedDevices()) {
4055 ssize_t index = mAvailableInputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07004056 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07004057 if (index >= 0) {
4058 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
4059 if (!devDesc->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004060 devDesc->attach(hwModule);
Eric Laurent83efe1c2017-07-09 16:51:08 -07004061 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07004062 }
Eric Laurentd78f1532014-09-16 16:38:20 -07004063 }
4064 }
Eric Laurentfe231122017-11-17 17:48:06 -08004065 inputDesc->close();
Eric Laurentd78f1532014-09-16 16:38:20 -07004066 } else {
4067 ALOGW("Cannot open input stream for device %08x on hw module %s",
Eric Laurentfe231122017-11-17 17:48:06 -08004068 profileType,
Mikhail Naganovd4120142017-12-06 15:49:22 -08004069 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07004070 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004071 }
4072 }
4073 // make sure all attached devices have been allocated a unique ID
4074 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004075 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004076 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004077 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
4078 continue;
4079 }
François Gaffie2110e042015-03-24 08:41:51 +01004080 // The device is now validated and can be appended to the available devices of the engine
4081 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
4082 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004083 i++;
4084 }
4085 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004086 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01004087 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004088 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
4089 continue;
4090 }
François Gaffie2110e042015-03-24 08:41:51 +01004091 // The device is now validated and can be appended to the available devices of the engine
4092 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
4093 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004094 i++;
4095 }
4096 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004097 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01004098 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004099 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004100 }
jiabin9ff780e2018-03-19 18:19:52 -07004101 // If microphones address is empty, set it according to device type
4102 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
4103 if (mAvailableInputDevices[i]->mAddress.isEmpty()) {
4104 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
4105 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
4106 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
4107 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BACK_MICROPHONE_ADDRESS);
4108 }
4109 }
4110 }
Eric Laurente552edb2014-03-10 17:42:56 -07004111
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004112 if (mPrimaryOutput == 0) {
4113 ALOGE("Failed to open primary output");
4114 status = NO_INIT;
4115 }
Eric Laurente552edb2014-03-10 17:42:56 -07004116
4117 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004118 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004119}
4120
Eric Laurente0720872014-03-11 09:30:41 -07004121AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004122{
Eric Laurente552edb2014-03-10 17:42:56 -07004123 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004124 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004125 }
4126 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004127 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004128 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004129 mAvailableOutputDevices.clear();
4130 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004131 mOutputs.clear();
4132 mInputs.clear();
4133 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004134 mHwModulesAll.clear();
jiabin81772902018-04-02 17:52:27 -07004135 mSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004136}
4137
Eric Laurente0720872014-03-11 09:30:41 -07004138status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004139{
Eric Laurent87ffa392015-05-22 10:32:38 -07004140 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004141}
4142
Eric Laurente552edb2014-03-10 17:42:56 -07004143// ---
4144
Eric Laurent98e38192018-02-15 18:31:53 -08004145void AudioPolicyManager::addOutput(audio_io_handle_t output,
4146 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004147{
Eric Laurent1c333e22014-05-20 10:48:17 -07004148 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08004149 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004150 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004151 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004152 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004153}
4154
François Gaffie53615e22015-03-19 09:24:12 +01004155void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4156{
4157 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004158 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004159}
4160
Eric Laurent98e38192018-02-15 18:31:53 -08004161void AudioPolicyManager::addInput(audio_io_handle_t input,
4162 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004163{
Eric Laurent1c333e22014-05-20 10:48:17 -07004164 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004165 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004166}
Eric Laurente552edb2014-03-10 17:42:56 -07004167
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004168void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08004169 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004170 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004171 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08004172 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004173 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08004174 if (devDesc != 0) {
4175 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
4176 desc->mIoHandle, address.string());
4177 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004178 }
4179}
4180
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004181status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004182 audio_policy_dev_state_t state,
4183 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004184 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07004185{
François Gaffie53615e22015-03-19 09:24:12 +01004186 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07004187 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004188
4189 if (audio_device_is_digital(device)) {
4190 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004191 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004192 }
Eric Laurente552edb2014-03-10 17:42:56 -07004193
Eric Laurent3b73df72014-03-11 09:06:29 -07004194 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004195 // first list already open outputs that can be routed to this device
4196 for (size_t i = 0; i < mOutputs.size(); i++) {
4197 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07004198 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004199 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004200 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
4201 outputs.add(mOutputs.keyAt(i));
4202 } else {
4203 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08004204 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004205 }
Eric Laurente552edb2014-03-10 17:42:56 -07004206 }
4207 }
4208 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004209 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004210 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004211 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4212 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004213 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004214 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004215 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004216 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004217 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4218 j, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004219 }
Eric Laurente552edb2014-03-10 17:42:56 -07004220 }
4221 }
4222 }
4223
Eric Laurent7b279bb2015-12-14 10:18:23 -08004224 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004225
Eric Laurente552edb2014-03-10 17:42:56 -07004226 if (profiles.isEmpty() && outputs.isEmpty()) {
4227 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4228 return BAD_VALUE;
4229 }
4230
4231 // open outputs for matching profiles if needed. Direct outputs are also opened to
4232 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4233 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004234 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004235
4236 // nothing to do if one output is already opened for this profile
4237 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004238 for (j = 0; j < outputs.size(); j++) {
4239 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004240 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004241 // matching profile: save the sample rates, format and channel masks supported
4242 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07004243 if (audio_device_is_digital(device)) {
4244 devDesc->importAudioPort(profile);
4245 }
Eric Laurente552edb2014-03-10 17:42:56 -07004246 break;
4247 }
4248 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004249 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004250 continue;
4251 }
4252
Eric Laurent3974e3b2017-12-07 17:58:43 -08004253 if (!profile->canOpenNewIo()) {
4254 ALOGW("Max Output number %u already opened for this profile %s",
4255 profile->maxOpenCount, profile->getTagName().c_str());
4256 continue;
4257 }
4258
Eric Laurent83efe1c2017-07-09 16:51:08 -07004259 ALOGV("opening output for device %08x with params %s profile %p name %s",
4260 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004261 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004262 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004263 status_t status = desc->open(nullptr, device, address,
4264 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004265
Eric Laurentfe231122017-11-17 17:48:06 -08004266 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004267 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004268 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004269 char *param = audio_device_address_to_parameter(device, address);
4270 mpClientInterface->setParameters(output, String8(param));
4271 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004272 }
Phil Burk00eeb322016-03-31 12:41:00 -07004273 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004274 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004275 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004276 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004277 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004278 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004279 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004280 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004281 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4282 profile->pickAudioProfile(
4283 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004284 config.offload_info.sample_rate = config.sample_rate;
4285 config.offload_info.channel_mask = config.channel_mask;
4286 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004287
4288 status_t status = desc->open(&config, device, address, AUDIO_STREAM_DEFAULT,
4289 AUDIO_OUTPUT_FLAG_NONE, &output);
4290 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004291 output = AUDIO_IO_HANDLE_NONE;
4292 }
Eric Laurentd4692962014-05-05 18:13:44 -07004293 }
4294
Eric Laurentcf2c0212014-07-25 16:20:43 -07004295 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004296 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01004297 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004298 sp<AudioPolicyMix> policyMix;
4299 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004300 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
4301 address.string());
4302 }
François Gaffie036e1e92015-03-19 10:16:24 +01004303 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07004304 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01004305
Eric Laurent87ffa392015-05-22 10:32:38 -07004306 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4307 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004308 // no duplicated output for direct outputs and
4309 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004310 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004311
Eric Laurentd4692962014-05-05 18:13:44 -07004312 //TODO: configure audio effect output stage here
4313
4314 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004315 sp<SwAudioOutputDescriptor> dupOutputDesc =
4316 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4317 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4318 &duplicatedOutput);
4319 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004320 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004321 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004322 } else {
4323 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004324 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004325 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004326 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004327 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004328 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004329 }
Eric Laurente552edb2014-03-10 17:42:56 -07004330 }
4331 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004332 } else {
4333 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004334 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004335 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004336 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004337 profiles.removeAt(profile_index);
4338 profile_index--;
4339 } else {
4340 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004341 // Load digital format info only for digital devices
4342 if (audio_device_is_digital(device)) {
4343 devDesc->importAudioPort(profile);
4344 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004345
François Gaffie53615e22015-03-19 09:24:12 +01004346 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004347 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4348 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004349 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004350 NULL/*patch handle*/, address.string());
4351 }
Eric Laurente552edb2014-03-10 17:42:56 -07004352 ALOGV("checkOutputsForDevice(): adding output %d", output);
4353 }
4354 }
4355
4356 if (profiles.isEmpty()) {
4357 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4358 return BAD_VALUE;
4359 }
Eric Laurentd4692962014-05-05 18:13:44 -07004360 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004361 // check if one opened output is not needed any more after disconnecting one device
4362 for (size_t i = 0; i < mOutputs.size(); i++) {
4363 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004364 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004365 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004366 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004367 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004368 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004369 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004370 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4371 mOutputs.keyAt(i));
4372 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004373 }
Eric Laurente552edb2014-03-10 17:42:56 -07004374 }
4375 }
Eric Laurentd4692962014-05-05 18:13:44 -07004376 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004377 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004378 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4379 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004380 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004381 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004382 "clearing direct output profile %zu on module %s",
4383 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004384 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004385 }
4386 }
4387 }
4388 }
4389 return NO_ERROR;
4390}
4391
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004392status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004393 audio_policy_dev_state_t state,
4394 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004395 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004396{
Paul McLean9080a4c2015-06-18 08:24:02 -07004397 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004398 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004399
4400 if (audio_device_is_digital(device)) {
4401 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004402 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004403 }
4404
Eric Laurentd4692962014-05-05 18:13:44 -07004405 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4406 // first list already open inputs that can be routed to this device
4407 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4408 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004409 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004410 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4411 inputs.add(mInputs.keyAt(input_index));
4412 }
4413 }
4414
4415 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004416 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004417 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004418 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004419 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004420 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004421 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004422
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004423 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004424 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004425 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004426 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004427 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4428 profile_index, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004429 }
Eric Laurentd4692962014-05-05 18:13:44 -07004430 }
4431 }
4432 }
4433
4434 if (profiles.isEmpty() && inputs.isEmpty()) {
4435 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4436 return BAD_VALUE;
4437 }
4438
4439 // open inputs for matching profiles if needed. Direct inputs are also opened to
4440 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4441 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4442
Eric Laurent1c333e22014-05-20 10:48:17 -07004443 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004444
Eric Laurentd4692962014-05-05 18:13:44 -07004445 // nothing to do if one input is already opened for this profile
4446 size_t input_index;
4447 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4448 desc = mInputs.valueAt(input_index);
4449 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004450 if (audio_device_is_digital(device)) {
4451 devDesc->importAudioPort(profile);
4452 }
Eric Laurentd4692962014-05-05 18:13:44 -07004453 break;
4454 }
4455 }
4456 if (input_index != mInputs.size()) {
4457 continue;
4458 }
4459
Eric Laurent3974e3b2017-12-07 17:58:43 -08004460 if (!profile->canOpenNewIo()) {
4461 ALOGW("Max Input number %u already opened for this profile %s",
4462 profile->maxOpenCount, profile->getTagName().c_str());
4463 continue;
4464 }
4465
Eric Laurentfe231122017-11-17 17:48:06 -08004466 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004467 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004468 status_t status = desc->open(nullptr,
4469 device,
4470 address,
4471 AUDIO_SOURCE_MIC,
4472 AUDIO_INPUT_FLAG_NONE,
4473 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004474
Eric Laurentcf2c0212014-07-25 16:20:43 -07004475 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004476 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004477 char *param = audio_device_address_to_parameter(device, address);
4478 mpClientInterface->setParameters(input, String8(param));
4479 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004480 }
Phil Burk00eeb322016-03-31 12:41:00 -07004481 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004482 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004483 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004484 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004485 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004486 }
4487
4488 if (input != 0) {
4489 addInput(input, desc);
4490 }
4491 } // endif input != 0
4492
Eric Laurentcf2c0212014-07-25 16:20:43 -07004493 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004494 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004495 profiles.removeAt(profile_index);
4496 profile_index--;
4497 } else {
4498 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004499 if (audio_device_is_digital(device)) {
4500 devDesc->importAudioPort(profile);
4501 }
Eric Laurentd4692962014-05-05 18:13:44 -07004502 ALOGV("checkInputsForDevice(): adding input %d", input);
4503 }
4504 } // end scan profiles
4505
4506 if (profiles.isEmpty()) {
4507 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4508 return BAD_VALUE;
4509 }
4510 } else {
4511 // Disconnect
4512 // check if one opened input is not needed any more after disconnecting one device
4513 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4514 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004515 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004516 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4517 mInputs.keyAt(input_index));
4518 inputs.add(mInputs.keyAt(input_index));
4519 }
4520 }
4521 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004522 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004523 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004524 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004525 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004526 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004527 if (profile->supportDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004528 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4529 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004530 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004531 }
4532 }
4533 }
4534 } // end disconnect
4535
4536 return NO_ERROR;
4537}
4538
4539
Eric Laurente0720872014-03-11 09:30:41 -07004540void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004541{
4542 ALOGV("closeOutput(%d)", output);
4543
Eric Laurentc75307b2015-03-17 15:29:32 -07004544 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004545 if (outputDesc == NULL) {
4546 ALOGW("closeOutput() unknown output %d", output);
4547 return;
4548 }
François Gaffie036e1e92015-03-19 10:16:24 +01004549 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004550
Eric Laurente552edb2014-03-10 17:42:56 -07004551 // look for duplicated outputs connected to the output being removed.
4552 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004553 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004554 if (dupOutputDesc->isDuplicated() &&
4555 (dupOutputDesc->mOutput1 == outputDesc ||
4556 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004557 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004558 if (dupOutputDesc->mOutput1 == outputDesc) {
4559 outputDesc2 = dupOutputDesc->mOutput2;
4560 } else {
4561 outputDesc2 = dupOutputDesc->mOutput1;
4562 }
4563 // As all active tracks on duplicated output will be deleted,
4564 // and as they were also referenced on the other output, the reference
4565 // count for their stream type must be adjusted accordingly on
4566 // the other output.
Eric Laurent733ce942017-12-07 12:18:25 -08004567 bool wasActive = outputDesc2->isActive();
Eric Laurent3b73df72014-03-11 09:06:29 -07004568 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004569 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07004570 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004571 }
Eric Laurent733ce942017-12-07 12:18:25 -08004572 // stop() will be a no op if the output is still active but is needed in case all
4573 // active streams refcounts where cleared above
4574 if (wasActive) {
4575 outputDesc2->stop();
4576 }
Eric Laurente552edb2014-03-10 17:42:56 -07004577 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4578 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4579
4580 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004581 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004582 }
4583 }
4584
Eric Laurent05b90f82014-08-27 15:32:29 -07004585 nextAudioPortGeneration();
4586
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004587 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004588 if (index >= 0) {
4589 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004590 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004591 mAudioPatches.removeItemsAt(index);
4592 mpClientInterface->onAudioPatchListUpdate();
4593 }
4594
Eric Laurentfe231122017-11-17 17:48:06 -08004595 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004596
François Gaffie53615e22015-03-19 09:24:12 +01004597 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004598 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004599}
4600
4601void AudioPolicyManager::closeInput(audio_io_handle_t input)
4602{
4603 ALOGV("closeInput(%d)", input);
4604
4605 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4606 if (inputDesc == NULL) {
4607 ALOGW("closeInput() unknown input %d", input);
4608 return;
4609 }
4610
Eric Laurent6a94d692014-05-20 11:18:06 -07004611 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004612
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004613 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004614 if (index >= 0) {
4615 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004616 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004617 mAudioPatches.removeItemsAt(index);
4618 mpClientInterface->onAudioPatchListUpdate();
4619 }
4620
Eric Laurentfe231122017-11-17 17:48:06 -08004621 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004622 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004623}
4624
Eric Laurentc75307b2015-03-17 15:29:32 -07004625SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4626 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004627 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004628{
4629 SortedVector<audio_io_handle_t> outputs;
4630
4631 ALOGVV("getOutputsForDevice() device %04x", device);
4632 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004633 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004634 i, openOutputs.valueAt(i)->isDuplicated(),
4635 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004636 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4637 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4638 outputs.add(openOutputs.keyAt(i));
4639 }
4640 }
4641 return outputs;
4642}
4643
Eric Laurente0720872014-03-11 09:30:41 -07004644bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
François Gaffie53615e22015-03-19 09:24:12 +01004645 SortedVector<audio_io_handle_t>& outputs2)
Eric Laurente552edb2014-03-10 17:42:56 -07004646{
4647 if (outputs1.size() != outputs2.size()) {
4648 return false;
4649 }
4650 for (size_t i = 0; i < outputs1.size(); i++) {
4651 if (outputs1[i] != outputs2[i]) {
4652 return false;
4653 }
4654 }
4655 return true;
4656}
4657
Eric Laurente0720872014-03-11 09:30:41 -07004658void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004659{
4660 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4661 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4662 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4663 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4664
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004665 // also take into account external policy-related changes: add all outputs which are
4666 // associated with policies in the "before" and "after" output vectors
4667 ALOGVV("checkOutputForStrategy(): policy related outputs");
4668 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004669 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004670 if (desc != 0 && desc->mPolicyMix != NULL) {
4671 srcOutputs.add(desc->mIoHandle);
4672 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4673 }
4674 }
4675 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004676 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004677 if (desc != 0 && desc->mPolicyMix != NULL) {
4678 dstOutputs.add(desc->mIoHandle);
4679 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4680 }
4681 }
4682
Eric Laurente552edb2014-03-10 17:42:56 -07004683 if (!vectorsEqual(srcOutputs,dstOutputs)) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004684 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4685 // audio from invalidated tracks will be rendered when unmuting
4686 uint32_t maxLatency = 0;
4687 for (audio_io_handle_t srcOut : srcOutputs) {
4688 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4689 if (desc != 0 && maxLatency < desc->latency()) {
4690 maxLatency = desc->latency();
4691 }
4692 }
Eric Laurente552edb2014-03-10 17:42:56 -07004693 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4694 strategy, srcOutputs[0], dstOutputs[0]);
4695 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004696 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004697 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4698 if (desc != 0 && isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004699 setStrategyMute(strategy, true, desc);
Eric Laurentac3a6902018-05-11 16:39:10 -07004700 setStrategyMute(strategy, false, desc, maxLatency * LATENCY_MUTE_FACTOR, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004701 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004702 sp<AudioSourceDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004703 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004704 if (source != 0){
4705 connectAudioSource(source);
4706 }
Eric Laurente552edb2014-03-10 17:42:56 -07004707 }
4708
4709 // Move effects associated to this strategy from previous output to new output
4710 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004711 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004712 }
4713 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004714 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004715 if (getStrategy((audio_stream_type_t)i) == strategy) {
4716 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004717 }
4718 }
4719 }
4720}
4721
Eric Laurente0720872014-03-11 09:30:41 -07004722void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004723{
François Gaffie2110e042015-03-24 08:41:51 +01004724 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004725 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004726 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004727 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004728 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004729 checkOutputForStrategy(STRATEGY_SONIFICATION);
4730 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004731 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004732 checkOutputForStrategy(STRATEGY_MEDIA);
4733 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004734 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004735}
4736
Eric Laurente0720872014-03-11 09:30:41 -07004737void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004738{
François Gaffie53615e22015-03-19 09:24:12 +01004739 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004740 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004741 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004742 return;
4743 }
4744
Eric Laurent3a4311c2014-03-17 12:00:47 -07004745 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004746 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4747 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4748 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004749
4750 // if suspended, restore A2DP output if:
4751 // ((SCO device is NOT connected) ||
4752 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4753 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004754 //
Eric Laurentf732e072016-08-03 19:30:28 -07004755 // if not suspended, suspend A2DP output if:
4756 // (SCO device is connected) &&
4757 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4758 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004759 //
4760 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004761 if (!isScoConnected ||
4762 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4763 AUDIO_POLICY_FORCE_BT_SCO) &&
4764 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4765 AUDIO_POLICY_FORCE_BT_SCO) &&
4766 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004767 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004768
4769 mpClientInterface->restoreOutput(a2dpOutput);
4770 mA2dpSuspended = false;
4771 }
4772 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004773 if (isScoConnected &&
4774 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4775 AUDIO_POLICY_FORCE_BT_SCO) ||
4776 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4777 AUDIO_POLICY_FORCE_BT_SCO) ||
4778 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004779 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004780
4781 mpClientInterface->suspendOutput(a2dpOutput);
4782 mA2dpSuspended = true;
4783 }
4784 }
4785}
4786
Eric Laurentc75307b2015-03-17 15:29:32 -07004787audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4788 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004789{
4790 audio_devices_t device = AUDIO_DEVICE_NONE;
4791
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004792 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004793 if (index >= 0) {
4794 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4795 if (patchDesc->mUid != mUidCached) {
4796 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004797 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004798 return outputDesc->device();
4799 }
4800 }
4801
Eric Laurentf3a5a602018-05-22 18:42:55 -07004802 // Check if an explicit routing request exists for an active stream on this output and
4803 // use it in priority before any other rule
4804 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
4805 if (outputDesc->isStreamActive((audio_stream_type_t)stream)) {
4806 audio_devices_t forcedDevice =
4807 mOutputRoutes.getActiveDeviceForStream(
4808 (audio_stream_type_t)stream, mAvailableOutputDevices);
4809
4810 if (forcedDevice != AUDIO_DEVICE_NONE) {
4811 return forcedDevice;
4812 }
4813 }
4814 }
4815
Eric Laurente552edb2014-03-10 17:42:56 -07004816 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004817 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004818 // use device for strategy enforced audible
4819 // 2: we are in call or the strategy phone is active on the output:
4820 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004821 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004822 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004823 // 4: the strategy for enforced audible is active but not enforced on the output:
4824 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004825 // 5: the strategy accessibility is active on the output:
4826 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004827 // 6: the strategy "respectful" sonification is active on the output:
4828 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004829 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004830 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004831 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004832 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004833 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004834 // use device for strategy t-t-s
Eric Laurent484e9272018-06-07 17:29:23 -07004835
4836 // FIXME: extend use of isStrategyActiveOnSameModule() to all strategies
4837 // with a refined rule considering mutually exclusive devices (using same backend)
4838 // as opposed to all streams on the same audio HAL module.
François Gaffiead3183e2015-03-18 16:55:35 +01004839 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004840 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004841 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4842 } else if (isInCall() ||
Eric Laurent484e9272018-06-07 17:29:23 -07004843 isStrategyActiveOnSameModule(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004844 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
Yung Ti Su3e7eb5e2018-06-13 11:48:42 +08004845 } else if (isStrategyActiveOnSameModule(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004846 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004847 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
4848 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004849 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4850 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004851 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004852 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004853 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004854 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004855 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004856 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004857 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004858 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004859 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004860 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004861 }
4862
Eric Laurent1c333e22014-05-20 10:48:17 -07004863 ALOGV("getNewOutputDevice() selected device %x", device);
4864 return device;
4865}
4866
Eric Laurentfb66dd92016-01-28 18:32:03 -08004867audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004868{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004869 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004870
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004871 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004872 if (index >= 0) {
4873 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4874 if (patchDesc->mUid != mUidCached) {
4875 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004876 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004877 return inputDesc->mDevice;
4878 }
4879 }
4880
Eric Laurentdc95a252018-04-12 12:46:56 -07004881 // If we are not in call and no client is active on this input, this methods returns
4882 // AUDIO_DEVICE_NONE, causing the patch on the input stream to be released.
Eric Laurentfb66dd92016-01-28 18:32:03 -08004883 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
Eric Laurentdc95a252018-04-12 12:46:56 -07004884 if (source == AUDIO_SOURCE_DEFAULT && isInCall()) {
4885 source = AUDIO_SOURCE_VOICE_COMMUNICATION;
4886 }
4887 if (source != AUDIO_SOURCE_DEFAULT) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08004888 device = getDeviceAndMixForInputSource(source);
4889 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004890
Eric Laurente552edb2014-03-10 17:42:56 -07004891 return device;
4892}
4893
Eric Laurent794fde22016-03-11 09:50:45 -08004894bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4895 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004896 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004897}
4898
Eric Laurente0720872014-03-11 09:30:41 -07004899uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004900 return (uint32_t)getStrategy(stream);
4901}
4902
Eric Laurente0720872014-03-11 09:30:41 -07004903audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004904 // By checking the range of stream before calling getStrategy, we avoid
4905 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4906 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004907 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004908 return AUDIO_DEVICE_NONE;
4909 }
Eric Laurent28d09f02016-03-08 10:43:05 -08004910 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004911 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4912 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004913 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004914 }
Eric Laurent794fde22016-03-11 09:50:45 -08004915 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004916 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004917 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004918 for (audio_io_handle_t output : getOutputsForDevice(curDevices, mOutputs)) {
4919 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08004920 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004921 curDevices |= outputDesc->device();
4922 }
4923 }
4924 devices |= curDevices;
Eric Laurente552edb2014-03-10 17:42:56 -07004925 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004926
4927 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4928 and doesn't really need to.*/
4929 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4930 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4931 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4932 }
Eric Laurente552edb2014-03-10 17:42:56 -07004933 return devices;
4934}
4935
François Gaffie2110e042015-03-24 08:41:51 +01004936routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4937{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004938 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004939 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004940}
4941
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004942uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4943 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004944 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4945 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4946 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004947 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4948 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4949 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004950 // usage to strategy mapping
François Gaffie2110e042015-03-24 08:41:51 +01004951 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004952}
4953
Eric Laurente0720872014-03-11 09:30:41 -07004954void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004955 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004956 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004957 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4958 updateDevicesAndOutputs();
4959 break;
4960 default:
4961 break;
4962 }
4963}
4964
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004965uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004966
4967 // skip beacon mute management if a dedicated TTS output is available
4968 if (mTtsOutputAvailable) {
4969 return 0;
4970 }
4971
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004972 switch(event) {
4973 case STARTING_OUTPUT:
4974 mBeaconMuteRefCount++;
4975 break;
4976 case STOPPING_OUTPUT:
4977 if (mBeaconMuteRefCount > 0) {
4978 mBeaconMuteRefCount--;
4979 }
4980 break;
4981 case STARTING_BEACON:
4982 mBeaconPlayingRefCount++;
4983 break;
4984 case STOPPING_BEACON:
4985 if (mBeaconPlayingRefCount > 0) {
4986 mBeaconPlayingRefCount--;
4987 }
4988 break;
4989 }
4990
4991 if (mBeaconMuteRefCount > 0) {
4992 // any playback causes beacon to be muted
4993 return setBeaconMute(true);
4994 } else {
4995 // no other playback: unmute when beacon starts playing, mute when it stops
4996 return setBeaconMute(mBeaconPlayingRefCount == 0);
4997 }
4998}
4999
5000uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5001 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5002 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5003 // keep track of muted state to avoid repeating mute/unmute operations
5004 if (mBeaconMuted != mute) {
5005 // mute/unmute AUDIO_STREAM_TTS on all outputs
5006 ALOGV("\t muting %d", mute);
5007 uint32_t maxLatency = 0;
5008 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005009 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005010 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07005011 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005012 0 /*delay*/, AUDIO_DEVICE_NONE);
5013 const uint32_t latency = desc->latency() * 2;
5014 if (latency > maxLatency) {
5015 maxLatency = latency;
5016 }
5017 }
5018 mBeaconMuted = mute;
5019 return maxLatency;
5020 }
5021 return 0;
5022}
5023
Eric Laurente0720872014-03-11 09:30:41 -07005024audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01005025 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005026{
Eric Laurentf3a5a602018-05-22 18:42:55 -07005027 // Check if an explicit routing request exists for a stream type corresponding to the
5028 // specified strategy and use it in priority over default routing rules.
5029 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
5030 if (getStrategy((audio_stream_type_t)stream) == strategy) {
5031 audio_devices_t forcedDevice =
5032 mOutputRoutes.getActiveDeviceForStream(
5033 (audio_stream_type_t)stream, mAvailableOutputDevices);
5034 if (forcedDevice != AUDIO_DEVICE_NONE) {
5035 return forcedDevice;
5036 }
Paul McLeanaa981192015-03-21 09:55:15 -07005037 }
5038 }
5039
Eric Laurente552edb2014-03-10 17:42:56 -07005040 if (fromCache) {
5041 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
5042 strategy, mDeviceForStrategy[strategy]);
5043 return mDeviceForStrategy[strategy];
5044 }
François Gaffie2110e042015-03-24 08:41:51 +01005045 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07005046}
5047
Eric Laurente0720872014-03-11 09:30:41 -07005048void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005049{
5050 for (int i = 0; i < NUM_STRATEGIES; i++) {
5051 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
5052 }
5053 mPreviousOutputs = mOutputs;
5054}
5055
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005056uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005057 audio_devices_t prevDevice,
5058 uint32_t delayMs)
5059{
5060 // mute/unmute strategies using an incompatible device combination
5061 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5062 // if unmuting, unmute only after the specified delay
5063 if (outputDesc->isDuplicated()) {
5064 return 0;
5065 }
5066
5067 uint32_t muteWaitMs = 0;
5068 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07005069 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005070
5071 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
5072 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07005073 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07005074 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
5075 bool doMute = false;
5076
5077 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
5078 doMute = true;
5079 outputDesc->mStrategyMutedByDevice[i] = true;
5080 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
5081 doMute = true;
5082 outputDesc->mStrategyMutedByDevice[i] = false;
5083 }
Eric Laurent99401132014-05-07 19:48:15 -07005084 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005085 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005086 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005087 // skip output if it does not share any device with current output
5088 if ((desc->supportedDevices() & outputDesc->supportedDevices())
5089 == AUDIO_DEVICE_NONE) {
5090 continue;
5091 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005092 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07005093 mute ? "muting" : "unmuting", i, curDevice);
5094 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005095 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005096 if (mute) {
5097 // FIXME: should not need to double latency if volume could be applied
5098 // immediately by the audioflinger mixer. We must account for the delay
5099 // between now and the next time the audioflinger thread for this output
5100 // will process a buffer (which corresponds to one buffer size,
5101 // usually 1/2 or 1/4 of the latency).
5102 if (muteWaitMs < desc->latency() * 2) {
5103 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005104 }
5105 }
5106 }
5107 }
5108 }
5109 }
5110
Eric Laurent99401132014-05-07 19:48:15 -07005111 // temporary mute output if device selection changes to avoid volume bursts due to
5112 // different per device volumes
5113 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005114 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5115 // temporary mute duration is conservatively set to 4 times the reported latency
5116 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5117 if (muteWaitMs < tempMuteWaitMs) {
5118 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005119 }
Eric Laurentdc462862016-07-19 12:29:53 -07005120
Eric Laurent99401132014-05-07 19:48:15 -07005121 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005122 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005123 // make sure that we do not start the temporary mute period too early in case of
5124 // delayed device change
5125 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005126 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07005127 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07005128 }
5129 }
5130 }
5131
Eric Laurente552edb2014-03-10 17:42:56 -07005132 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5133 if (muteWaitMs > delayMs) {
5134 muteWaitMs -= delayMs;
5135 usleep(muteWaitMs * 1000);
5136 return muteWaitMs;
5137 }
5138 return 0;
5139}
5140
Eric Laurentc75307b2015-03-17 15:29:32 -07005141uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005142 audio_devices_t device,
5143 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07005144 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005145 audio_patch_handle_t *patchHandle,
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005146 const char *address,
5147 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005148{
Eric Laurentc75307b2015-03-17 15:29:32 -07005149 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005150 AudioParameter param;
5151 uint32_t muteWaitMs;
5152
5153 if (outputDesc->isDuplicated()) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005154 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs,
5155 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
5156 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs,
5157 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005158 return muteWaitMs;
5159 }
5160 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5161 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07005162 if ((device != AUDIO_DEVICE_NONE) &&
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005163 ((device & outputDesc->supportedDevices()) == AUDIO_DEVICE_NONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005164 return 0;
5165 }
5166
5167 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07005168 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07005169
5170 audio_devices_t prevDevice = outputDesc->mDevice;
5171
Paul McLeanaa981192015-03-21 09:55:15 -07005172 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005173
5174 if (device != AUDIO_DEVICE_NONE) {
5175 outputDesc->mDevice = device;
5176 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005177
5178 // if the outputs are not materially active, there is no need to mute.
5179 if (requiresMuteCheck) {
5180 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
5181 } else {
5182 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5183 muteWaitMs = 0;
5184 }
Eric Laurente552edb2014-03-10 17:42:56 -07005185
5186 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005187 // the requested device is AUDIO_DEVICE_NONE
5188 // OR the requested device is the same as current device
5189 // AND force is not specified
5190 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07005191 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07005192 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
5193 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005194 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005195 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005196 return muteWaitMs;
5197 }
5198
5199 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07005200
Eric Laurente552edb2014-03-10 17:42:56 -07005201 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07005202 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005203 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005204 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07005205 DeviceVector deviceList;
5206 if ((address == NULL) || (strlen(address) == 0)) {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005207 deviceList = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurentc40d9692016-04-13 19:14:13 -07005208 } else {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005209 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
5210 device, String8(address));
5211 if (deviceDesc) deviceList.add(deviceDesc);
Eric Laurentc40d9692016-04-13 19:14:13 -07005212 }
5213
Eric Laurent1c333e22014-05-20 10:48:17 -07005214 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005215 PatchBuilder patchBuilder;
5216 patchBuilder.addSource(outputDesc);
Eric Laurent1c333e22014-05-20 10:48:17 -07005217 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005218 patchBuilder.addSink(deviceList.itemAt(i));
Eric Laurent1c333e22014-05-20 10:48:17 -07005219 }
Mikhail Naganovdc769682018-05-04 15:34:08 -07005220 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005221 }
bryant_liuf5e7e792014-08-19 20:07:05 +08005222
5223 // inform all input as well
5224 for (size_t i = 0; i < mInputs.size(); i++) {
5225 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01005226 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08005227 AudioParameter inputCmd = AudioParameter();
5228 ALOGV("%s: inform input %d of device:%d", __func__,
5229 inputDescriptor->mIoHandle, device);
5230 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
5231 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
5232 inputCmd.toString(),
5233 delayMs);
5234 }
5235 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005236 }
Eric Laurente552edb2014-03-10 17:42:56 -07005237
5238 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07005239 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005240
5241 return muteWaitMs;
5242}
5243
Eric Laurentc75307b2015-03-17 15:29:32 -07005244status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005245 int delayMs,
5246 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005247{
Eric Laurent6a94d692014-05-20 11:18:06 -07005248 ssize_t index;
5249 if (patchHandle) {
5250 index = mAudioPatches.indexOfKey(*patchHandle);
5251 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005252 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005253 }
5254 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005255 return INVALID_OPERATION;
5256 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005257 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5258 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005259 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005260 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005261 removeAudioPatch(patchDesc->mHandle);
5262 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005263 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005264 return status;
5265}
5266
5267status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5268 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005269 bool force,
5270 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005271{
5272 status_t status = NO_ERROR;
5273
Eric Laurent1f2f2232014-06-02 12:01:23 -07005274 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005275 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5276 inputDesc->mDevice = device;
5277
Mikhail Naganov708e0382018-05-30 09:53:04 -07005278 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005279 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005280 PatchBuilder patchBuilder;
5281 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005282 // AUDIO_SOURCE_HOTWORD is for internal use only:
5283 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07005284 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5285 auto result = usecase;
5286 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5287 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5288 }
5289 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07005290 //only one input device for now
Mikhail Naganovdc769682018-05-04 15:34:08 -07005291 addSource(deviceList.itemAt(0));
5292 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005293 }
5294 }
5295 return status;
5296}
5297
Eric Laurent6a94d692014-05-20 11:18:06 -07005298status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5299 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005300{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005301 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005302 ssize_t index;
5303 if (patchHandle) {
5304 index = mAudioPatches.indexOfKey(*patchHandle);
5305 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005306 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005307 }
5308 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005309 return INVALID_OPERATION;
5310 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005311 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5312 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005313 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005314 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005315 removeAudioPatch(patchDesc->mHandle);
5316 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005317 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005318 return status;
5319}
5320
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005321sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005322 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005323 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005324 audio_format_t& format,
5325 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005326 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005327{
5328 // Choose an input profile based on the requested capture parameters: select the first available
5329 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005330 //
5331 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5332 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005333
Glenn Kasten730b9262018-03-29 15:01:26 -07005334 sp<IOProfile> firstInexact;
5335 uint32_t updatedSamplingRate = 0;
5336 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5337 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005338 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005339 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005340 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005341 //updatedFormat = format;
Eric Laurent275e8e92014-11-30 15:14:47 -08005342 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005343 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005344 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005345 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005346 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005347 &channelMask /*updatedChannelMask*/,
5348 // FIXME ugly cast
5349 (audio_output_flags_t) flags,
5350 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005351 return profile;
5352 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005353 if (firstInexact == nullptr && profile->isCompatibleProfile(device, address,
5354 samplingRate,
5355 &updatedSamplingRate,
5356 format,
5357 &updatedFormat,
5358 channelMask,
5359 &updatedChannelMask,
5360 // FIXME ugly cast
5361 (audio_output_flags_t) flags,
5362 false /*exactMatchRequiredForInputFlags*/)) {
5363 firstInexact = profile;
5364 }
5365
Eric Laurente552edb2014-03-10 17:42:56 -07005366 }
5367 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005368 if (firstInexact != nullptr) {
5369 samplingRate = updatedSamplingRate;
5370 format = updatedFormat;
5371 channelMask = updatedChannelMask;
5372 return firstInexact;
5373 }
Eric Laurente552edb2014-03-10 17:42:56 -07005374 return NULL;
5375}
5376
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005377
5378audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005379 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005380{
François Gaffie036e1e92015-03-19 10:16:24 +01005381 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5382 audio_devices_t selectedDeviceFromMix =
5383 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005384
François Gaffie036e1e92015-03-19 10:16:24 +01005385 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5386 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005387 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005388 return getDeviceForInputSource(inputSource);
5389}
5390
5391audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5392{
Eric Laurentad2e7b92017-09-14 20:06:42 -07005393 // Routing
5394 // Scan the whole RouteMap to see if we have an explicit route:
5395 // if the input source in the RouteMap is the same as the argument above,
5396 // and activity count is non-zero and the device in the route descriptor is available
5397 // then select this device.
Paul McLean466dc8e2015-04-17 13:15:36 -06005398 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
5399 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
Eric Laurent2157f5b2018-04-25 18:33:02 -07005400 if ((inputSource == route->mSource) && route->isActiveOrChanged() &&
Eric Laurentad2e7b92017-09-14 20:06:42 -07005401 (mAvailableInputDevices.indexOf(route->mDeviceDescriptor) >= 0)) {
Paul McLean466dc8e2015-04-17 13:15:36 -06005402 return route->mDeviceDescriptor->type();
5403 }
5404 }
5405
5406 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005407}
5408
Eric Laurente0720872014-03-11 09:30:41 -07005409float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005410 int index,
5411 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005412{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005413 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005414
5415 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5416 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5417 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5418 // the ringtone volume
5419 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5420 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5421 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5422 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5423 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5424 }
5425
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005426 // in-call: always cap earpiece volume by voice volume + some low headroom
Eric Laurent7731b5a2018-04-06 15:47:22 -07005427 if ((stream != AUDIO_STREAM_VOICE_CALL) && (device & AUDIO_DEVICE_OUT_EARPIECE) &&
5428 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005429 switch (stream) {
5430 case AUDIO_STREAM_SYSTEM:
5431 case AUDIO_STREAM_RING:
5432 case AUDIO_STREAM_MUSIC:
5433 case AUDIO_STREAM_ALARM:
5434 case AUDIO_STREAM_NOTIFICATION:
5435 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5436 case AUDIO_STREAM_DTMF:
5437 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005438 int voiceVolumeIndex =
5439 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, AUDIO_DEVICE_OUT_EARPIECE);
5440 const float maxVoiceVolDb =
5441 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, AUDIO_DEVICE_OUT_EARPIECE)
5442 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005443 if (volumeDB > maxVoiceVolDb) {
5444 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5445 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5446 volumeDB = maxVoiceVolDb;
5447 }
5448 } break;
5449 default:
5450 break;
5451 }
5452 }
5453
Eric Laurente552edb2014-03-10 17:42:56 -07005454 // if a headset is connected, apply the following rules to ring tones and notifications
5455 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005456 // - always attenuate notifications volume by 6dB
5457 // - attenuate ring tones volume by 6dB unless music is not playing and
5458 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005459 // - if music is playing, always limit the volume to current music volume,
5460 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005461 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005462 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5463 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5464 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005465 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005466 AUDIO_DEVICE_OUT_USB_HEADSET |
5467 AUDIO_DEVICE_OUT_HEARING_AID)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005468 ((stream_strategy == STRATEGY_SONIFICATION)
5469 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005470 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005471 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005472 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005473 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005474 // when the phone is ringing we must consider that music could have been paused just before
5475 // by the music application and behave as if music was active if the last music track was
5476 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005477 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005478 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005479 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005480 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005481 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005482 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5483 musicDevice),
5484 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005485 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5486 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005487 if (volumeDB > minVolDB) {
5488 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005489 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005490 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005491 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5492 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5493 // on A2DP, also ensure notification volume is not too low compared to media when
5494 // intended to be played
5495 if ((volumeDB > -96.0f) &&
5496 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5497 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5498 stream, device,
5499 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5500 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5501 }
5502 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005503 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5504 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005505 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005506 }
5507 }
5508
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005509 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005510}
5511
Eric Laurente0720872014-03-11 09:30:41 -07005512status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005513 int index,
5514 const sp<AudioOutputDescriptor>& outputDesc,
5515 audio_devices_t device,
5516 int delayMs,
5517 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005518{
Eric Laurente552edb2014-03-10 17:42:56 -07005519 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005520 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005521 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005522 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005523 return NO_ERROR;
5524 }
François Gaffie2110e042015-03-24 08:41:51 +01005525 audio_policy_forced_cfg_t forceUseForComm =
5526 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005527 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005528 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5529 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005530 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005531 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005532 return INVALID_OPERATION;
5533 }
5534
Eric Laurentc75307b2015-03-17 15:29:32 -07005535 if (device == AUDIO_DEVICE_NONE) {
5536 device = outputDesc->device();
5537 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005538
Eric Laurentffbc80f2015-03-18 18:30:19 -07005539 float volumeDb = computeVolume(stream, index, device);
HW Leeda7581e2018-05-22 18:31:34 +08005540 if (outputDesc->isFixedVolume(device) ||
5541 // Force VoIP volume to max for bluetooth SCO
5542 ((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
5543 (device & AUDIO_DEVICE_OUT_ALL_SCO) != 0)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005544 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005545 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005546
Eric Laurentffbc80f2015-03-18 18:30:19 -07005547 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005548
Eric Laurent3b73df72014-03-11 09:06:29 -07005549 if (stream == AUDIO_STREAM_VOICE_CALL ||
5550 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005551 float voiceVolume;
5552 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005553 if (stream == AUDIO_STREAM_VOICE_CALL) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005554 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005555 } else {
5556 voiceVolume = 1.0;
5557 }
5558
Eric Laurent18fba842016-03-31 14:41:26 -07005559 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005560 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5561 mLastVoiceVolume = voiceVolume;
5562 }
5563 }
5564
5565 return NO_ERROR;
5566}
5567
Eric Laurentc75307b2015-03-17 15:29:32 -07005568void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5569 audio_devices_t device,
5570 int delayMs,
5571 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005572{
Eric Laurentc75307b2015-03-17 15:29:32 -07005573 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005574
Eric Laurent794fde22016-03-11 09:50:45 -08005575 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005576 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005577 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005578 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005579 device,
5580 delayMs,
5581 force);
5582 }
5583}
5584
Eric Laurente0720872014-03-11 09:30:41 -07005585void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005586 bool on,
5587 const sp<AudioOutputDescriptor>& outputDesc,
5588 int delayMs,
5589 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005590{
Eric Laurent72249d52015-06-08 11:12:15 -07005591 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5592 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005593 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005594 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005595 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005596 }
5597 }
5598}
5599
Eric Laurente0720872014-03-11 09:30:41 -07005600void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005601 bool on,
5602 const sp<AudioOutputDescriptor>& outputDesc,
5603 int delayMs,
5604 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005605{
Eric Laurente552edb2014-03-10 17:42:56 -07005606 if (device == AUDIO_DEVICE_NONE) {
5607 device = outputDesc->device();
5608 }
5609
Eric Laurentc75307b2015-03-17 15:29:32 -07005610 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5611 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005612
5613 if (on) {
5614 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005615 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005616 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005617 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005618 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005619 }
5620 }
5621 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5622 outputDesc->mMuteCount[stream]++;
5623 } else {
5624 if (outputDesc->mMuteCount[stream] == 0) {
5625 ALOGV("setStreamMute() unmuting non muted stream!");
5626 return;
5627 }
5628 if (--outputDesc->mMuteCount[stream] == 0) {
5629 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005630 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005631 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005632 device,
5633 delayMs);
5634 }
5635 }
5636}
5637
Eric Laurente0720872014-03-11 09:30:41 -07005638void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005639 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005640{
Eric Laurent87ffa392015-05-22 10:32:38 -07005641 if(!hasPrimaryOutput()) {
5642 return;
5643 }
5644
Eric Laurente552edb2014-03-10 17:42:56 -07005645 // if the stream pertains to sonification strategy and we are in call we must
5646 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5647 // in the device used for phone strategy and play the tone if the selected device does not
5648 // interfere with the device used for phone strategy
5649 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5650 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005651 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005652 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5653 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005654 sp<SwAudioOutputDescriptor> outputDesc = mPrimaryOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07005655 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5656 stream, starting, outputDesc->mDevice, stateChange);
5657 if (outputDesc->mRefCount[stream]) {
5658 int muteCount = 1;
5659 if (stateChange) {
5660 muteCount = outputDesc->mRefCount[stream];
5661 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005662 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005663 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5664 for (int i = 0; i < muteCount; i++) {
5665 setStreamMute(stream, starting, mPrimaryOutput);
5666 }
5667 } else {
5668 ALOGV("handleIncallSonification() high visibility");
5669 if (outputDesc->device() &
5670 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5671 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5672 for (int i = 0; i < muteCount; i++) {
5673 setStreamMute(stream, starting, mPrimaryOutput);
5674 }
5675 }
5676 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005677 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5678 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005679 } else {
5680 mpClientInterface->stopTone();
5681 }
5682 }
5683 }
5684 }
5685}
5686
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005687audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5688{
5689 // flags to stream type mapping
5690 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5691 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5692 }
5693 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5694 return AUDIO_STREAM_BLUETOOTH_SCO;
5695 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005696 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5697 return AUDIO_STREAM_TTS;
5698 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005699
5700 // usage to stream type mapping
5701 switch (attr->usage) {
5702 case AUDIO_USAGE_MEDIA:
5703 case AUDIO_USAGE_GAME:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005704 case AUDIO_USAGE_ASSISTANT:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005705 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5706 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005707 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5708 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005709 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5710 return AUDIO_STREAM_SYSTEM;
5711 case AUDIO_USAGE_VOICE_COMMUNICATION:
5712 return AUDIO_STREAM_VOICE_CALL;
5713
5714 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5715 return AUDIO_STREAM_DTMF;
5716
5717 case AUDIO_USAGE_ALARM:
5718 return AUDIO_STREAM_ALARM;
5719 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5720 return AUDIO_STREAM_RING;
5721
5722 case AUDIO_USAGE_NOTIFICATION:
5723 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5724 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5725 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5726 case AUDIO_USAGE_NOTIFICATION_EVENT:
5727 return AUDIO_STREAM_NOTIFICATION;
5728
5729 case AUDIO_USAGE_UNKNOWN:
5730 default:
5731 return AUDIO_STREAM_MUSIC;
5732 }
5733}
Eric Laurente83b55d2014-11-14 10:06:21 -08005734
François Gaffie53615e22015-03-19 09:24:12 +01005735bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5736{
Eric Laurente83b55d2014-11-14 10:06:21 -08005737 // has flags that map to a strategy?
5738 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5739 return true;
5740 }
5741
5742 // has known usage?
5743 switch (paa->usage) {
5744 case AUDIO_USAGE_UNKNOWN:
5745 case AUDIO_USAGE_MEDIA:
5746 case AUDIO_USAGE_VOICE_COMMUNICATION:
5747 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5748 case AUDIO_USAGE_ALARM:
5749 case AUDIO_USAGE_NOTIFICATION:
5750 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5751 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5752 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5753 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5754 case AUDIO_USAGE_NOTIFICATION_EVENT:
5755 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5756 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5757 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5758 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005759 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005760 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005761 break;
5762 default:
5763 return false;
5764 }
5765 return true;
5766}
5767
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005768bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005769 routing_strategy strategy, uint32_t inPastMs,
5770 nsecs_t sysTime) const
5771{
5772 if ((sysTime == 0) && (inPastMs != 0)) {
5773 sysTime = systemTime();
5774 }
Eric Laurent794fde22016-03-11 09:50:45 -08005775 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005776 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5777 (NUM_STRATEGIES == strategy)) &&
5778 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5779 return true;
5780 }
5781 }
5782 return false;
5783}
5784
Eric Laurent484e9272018-06-07 17:29:23 -07005785bool AudioPolicyManager::isStrategyActiveOnSameModule(const sp<AudioOutputDescriptor>& outputDesc,
5786 routing_strategy strategy, uint32_t inPastMs,
5787 nsecs_t sysTime) const
5788{
5789 for (size_t i = 0; i < mOutputs.size(); i++) {
5790 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5791 if (outputDesc->sharesHwModuleWith(desc)
5792 && isStrategyActive(desc, strategy, inPastMs, sysTime)) {
5793 return true;
5794 }
5795 }
5796 return false;
5797}
5798
François Gaffie2110e042015-03-24 08:41:51 +01005799audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5800{
5801 return mEngine->getForceUse(usage);
5802}
5803
5804bool AudioPolicyManager::isInCall()
5805{
5806 return isStateInCall(mEngine->getPhoneState());
5807}
5808
5809bool AudioPolicyManager::isStateInCall(int state)
5810{
5811 return is_state_in_call(state);
5812}
5813
Eric Laurentd60560a2015-04-10 11:31:20 -07005814void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5815{
5816 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5817 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
5818 if (sourceDesc->mDevice->equals(deviceDesc)) {
5819 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle());
5820 stopAudioSource(sourceDesc->getHandle());
5821 }
5822 }
5823
5824 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5825 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5826 bool release = false;
5827 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5828 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5829 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5830 source->ext.device.type == deviceDesc->type()) {
5831 release = true;
5832 }
5833 }
5834 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5835 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5836 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5837 sink->ext.device.type == deviceDesc->type()) {
5838 release = true;
5839 }
5840 }
5841 if (release) {
5842 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5843 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5844 }
5845 }
5846}
5847
Phil Burk09bc4612016-02-24 15:58:15 -08005848// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005849void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5850 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005851 // TODO Set this based on Config properties.
5852 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005853
5854 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5855 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005856 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005857
jiabin81772902018-04-02 17:52:27 -07005858 // If MANUAL, keep the supported surround sound formats as current enabled ones.
5859 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
5860 formats.clear();
5861 for (auto it = mSurroundFormats.begin(); it != mSurroundFormats.end(); it++) {
5862 formats.add(*it);
Phil Burk09bc4612016-02-24 15:58:15 -08005863 }
jiabin81772902018-04-02 17:52:27 -07005864 // Always enable IEC61937 when in MANUAL mode.
5865 formats.add(AUDIO_FORMAT_IEC61937);
5866 } else { // NEVER, AUTO or ALWAYS
5867 // Analyze original support for various formats.
5868 bool supportsAC3 = false;
5869 bool supportsOtherSurround = false;
5870 bool supportsIEC61937 = false;
5871 mSurroundFormats.clear();
5872 for (ssize_t formatIndex = 0; formatIndex < (ssize_t)formats.size(); formatIndex++) {
5873 audio_format_t format = formats[formatIndex];
5874 switch (format) {
5875 case AUDIO_FORMAT_AC3:
5876 supportsAC3 = true;
5877 break;
5878 case AUDIO_FORMAT_E_AC3:
5879 case AUDIO_FORMAT_DTS:
5880 case AUDIO_FORMAT_DTS_HD:
5881 // If ALWAYS, remove all other surround formats here
5882 // since we will add them later.
5883 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5884 formats.removeAt(formatIndex);
5885 formatIndex--;
5886 }
5887 supportsOtherSurround = true;
5888 break;
5889 case AUDIO_FORMAT_IEC61937:
5890 supportsIEC61937 = true;
5891 break;
5892 default:
5893 break;
5894 }
5895 }
Phil Burk09bc4612016-02-24 15:58:15 -08005896
jiabin81772902018-04-02 17:52:27 -07005897 // Modify formats based on surround preferences.
5898 // If NEVER, remove support for surround formats.
5899 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5900 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5901 // Remove surround sound related formats.
5902 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5903 audio_format_t format = formats[formatIndex];
5904 switch(format) {
5905 case AUDIO_FORMAT_AC3:
5906 case AUDIO_FORMAT_E_AC3:
5907 case AUDIO_FORMAT_DTS:
5908 case AUDIO_FORMAT_DTS_HD:
5909 case AUDIO_FORMAT_IEC61937:
5910 formats.removeAt(formatIndex);
5911 break;
5912 default:
5913 formatIndex++; // keep it
5914 break;
5915 }
5916 }
5917 supportsAC3 = false;
5918 supportsOtherSurround = false;
5919 supportsIEC61937 = false;
5920 }
5921 } else { // AUTO or ALWAYS
5922 // Most TVs support AC3 even if they do not report it in the EDID.
5923 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
5924 && !supportsAC3) {
5925 formats.add(AUDIO_FORMAT_AC3);
5926 supportsAC3 = true;
5927 }
5928
5929 // If ALWAYS, add support for raw surround formats if all are missing.
5930 // This assumes that if any of these formats are reported by the HAL
5931 // then the report is valid and should not be modified.
5932 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5933 formats.add(AUDIO_FORMAT_E_AC3);
5934 formats.add(AUDIO_FORMAT_DTS);
5935 formats.add(AUDIO_FORMAT_DTS_HD);
5936 supportsOtherSurround = true;
5937 }
5938
5939 // Add support for IEC61937 if any raw surround supported.
5940 // The HAL could do this but add it here, just in case.
5941 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
5942 formats.add(AUDIO_FORMAT_IEC61937);
5943 supportsIEC61937 = true;
5944 }
5945
5946 // Add reported surround sound formats to enabled surround formats.
5947 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
Phil Burk07ac1142016-03-25 13:39:29 -07005948 audio_format_t format = formats[formatIndex];
5949 switch(format) {
5950 case AUDIO_FORMAT_AC3:
5951 case AUDIO_FORMAT_E_AC3:
5952 case AUDIO_FORMAT_DTS:
5953 case AUDIO_FORMAT_DTS_HD:
jiabin81772902018-04-02 17:52:27 -07005954 case AUDIO_FORMAT_AAC_LC:
5955 case AUDIO_FORMAT_DOLBY_TRUEHD:
5956 case AUDIO_FORMAT_E_AC3_JOC:
5957 mSurroundFormats.insert(format);
Phil Burk07ac1142016-03-25 13:39:29 -07005958 default:
Phil Burk07ac1142016-03-25 13:39:29 -07005959 break;
5960 }
Phil Burk09bc4612016-02-24 15:58:15 -08005961 }
Phil Burk07ac1142016-03-25 13:39:29 -07005962 }
Phil Burk09bc4612016-02-24 15:58:15 -08005963 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005964}
5965
5966// Modify the list of channel masks supported.
5967void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
5968 ChannelsVector &channelMasks = *channelMasksPtr;
5969 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5970 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5971
5972 // If NEVER, then remove support for channelMasks > stereo.
5973 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5974 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5975 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5976 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5977 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5978 channelMasks.removeAt(maskIndex);
5979 } else {
5980 maskIndex++;
5981 }
5982 }
jiabin81772902018-04-02 17:52:27 -07005983 // If ALWAYS or MANUAL, then make sure we at least support 5.1
5984 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
5985 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005986 bool supports5dot1 = false;
5987 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005988 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005989 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5990 supports5dot1 = true;
5991 break;
5992 }
5993 }
5994 // If not then add 5.1 support.
5995 if (!supports5dot1) {
5996 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
5997 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
5998 }
Phil Burk09bc4612016-02-24 15:58:15 -08005999 }
6000}
6001
Phil Burk00eeb322016-03-31 12:41:00 -07006002void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
6003 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01006004 AudioProfileVector &profiles)
6005{
6006 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07006007
François Gaffie112b0af2015-11-19 16:13:25 +01006008 // Format MUST be checked first to update the list of AudioProfile
6009 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006010 reply = mpClientInterface->getParameters(
6011 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07006012 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006013 AudioParameter repliedParameters(reply);
6014 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006015 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01006016 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
6017 return;
6018 }
Phil Burk09bc4612016-02-24 15:58:15 -08006019 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07006020 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006021 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07006022 }
Phil Burk09bc4612016-02-24 15:58:15 -08006023 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01006024 }
François Gaffie112b0af2015-11-19 16:13:25 +01006025
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006026 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08006027 ChannelsVector channelMasks;
6028 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01006029 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07006030 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01006031
6032 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006033 reply = mpClientInterface->getParameters(
6034 ioHandle,
6035 requestedParameters.toString() + ";" +
6036 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01006037 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006038 AudioParameter repliedParameters(reply);
6039 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006040 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006041 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01006042 }
6043 }
6044 if (profiles.hasDynamicChannelsFor(format)) {
6045 reply = mpClientInterface->getParameters(ioHandle,
6046 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07006047 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01006048 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006049 AudioParameter repliedParameters(reply);
6050 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006051 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006052 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07006053 if (device == AUDIO_DEVICE_OUT_HDMI) {
6054 filterSurroundChannelMasks(&channelMasks);
6055 }
François Gaffie112b0af2015-11-19 16:13:25 +01006056 }
6057 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08006058 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006059 }
6060}
Eric Laurentd60560a2015-04-10 11:31:20 -07006061
Mikhail Naganovdc769682018-05-04 15:34:08 -07006062status_t AudioPolicyManager::installPatch(const char *caller,
6063 audio_patch_handle_t *patchHandle,
6064 AudioIODescriptorInterface *ioDescriptor,
6065 const struct audio_patch *patch,
6066 int delayMs)
6067{
6068 ssize_t index = mAudioPatches.indexOfKey(
6069 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6070 *patchHandle : ioDescriptor->getPatchHandle());
6071 sp<AudioPatch> patchDesc;
6072 status_t status = installPatch(
6073 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6074 if (status == NO_ERROR) {
6075 ioDescriptor->setPatchHandle(patchDesc->mHandle);
6076 }
6077 return status;
6078}
6079
6080status_t AudioPolicyManager::installPatch(const char *caller,
6081 ssize_t index,
6082 audio_patch_handle_t *patchHandle,
6083 const struct audio_patch *patch,
6084 int delayMs,
6085 uid_t uid,
6086 sp<AudioPatch> *patchDescPtr)
6087{
6088 sp<AudioPatch> patchDesc;
6089 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6090 if (index >= 0) {
6091 patchDesc = mAudioPatches.valueAt(index);
6092 afPatchHandle = patchDesc->mAfPatchHandle;
6093 }
6094
6095 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6096 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6097 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6098 if (status == NO_ERROR) {
6099 if (index < 0) {
6100 patchDesc = new AudioPatch(patch, uid);
6101 addAudioPatch(patchDesc->mHandle, patchDesc);
6102 } else {
6103 patchDesc->mPatch = *patch;
6104 }
6105 patchDesc->mAfPatchHandle = afPatchHandle;
6106 if (patchHandle) {
6107 *patchHandle = patchDesc->mHandle;
6108 }
6109 nextAudioPortGeneration();
6110 mpClientInterface->onAudioPatchListUpdate();
6111 }
6112 if (patchDescPtr) *patchDescPtr = patchDesc;
6113 return status;
6114}
6115
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006116} // namespace android