blob: c50839db084a68d2b5697d1c8570c602e3ac261a [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"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090018
19// Need to keep the log statements even in production builds
20// to enable VERBOSE logging dynamically.
21// You can enable VERBOSE logging as follows:
22// adb shell setprop log.tag.APM_AudioPolicyManager V
23#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070024
25//#define VERY_VERBOSE_LOGGING
26#ifdef VERY_VERBOSE_LOGGING
27#define ALOGVV ALOGV
28#else
29#define ALOGVV(a...) do { } while(0)
30#endif
31
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +090032#define AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH 128
33#define AUDIO_POLICY_XML_CONFIG_FILE_NAME "audio_policy_configuration.xml"
Petri Gyntherf497f292018-04-17 18:46:10 -070034#define AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME \
35 "audio_policy_configuration_a2dp_offload_disabled.xml"
François Gaffief4ad6e52015-11-19 16:59:57 +010036
Eric Laurentd4692962014-05-05 18:13:44 -070037#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070038#include <math.h>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080039#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110040#include <vector>
Eric Laurentd4692962014-05-05 18:13:44 -070041
François Gaffie2110e042015-03-24 08:41:51 +010042#include <AudioPolicyManagerInterface.h>
43#include <AudioPolicyEngineInstance.h>
Eric Laurente552edb2014-03-10 17:42:56 -070044#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070045#include <utils/Log.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070046#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080047#include <media/AudioPolicyHelper.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070048#include <private/android_filesystem_config.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070049#include <soundtrigger/SoundTrigger.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070050#include <system/audio.h>
Mikhail Naganov9ee05402016-10-13 15:58:17 -070051#include <audio_policy_conf.h>
Eric Laurentd4692962014-05-05 18:13:44 -070052#include "AudioPolicyManager.h"
François Gaffied1ab2bd2015-12-02 18:20:06 +010053#include <Serializer.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010054#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010055#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070056
Eric Laurent3b73df72014-03-11 09:06:29 -070057namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070058
Eric Laurentdc462862016-07-19 12:29:53 -070059//FIXME: workaround for truncated touch sounds
60// to be removed when the problem is handled by system UI
61#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070062
63// Largest difference in dB on earpiece in call between the voice volume and another
64// media / notification / system volume.
65constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
66
Mikhail Naganov15be9d22017-11-08 14:18:13 +110067// Compressed formats for MSD module, ordered from most preferred to least preferred.
68static const std::vector<audio_format_t> compressedFormatsOrder = {{
69 AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
70 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
71// Channel masks for MSD module, 3D > 2D > 1D ordering (most preferred to least preferred).
72static const std::vector<audio_channel_mask_t> surroundChannelMasksOrder = {{
73 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
74 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
75 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
76
Eric Laurente552edb2014-03-10 17:42:56 -070077// ----------------------------------------------------------------------------
78// AudioPolicyInterface implementation
79// ----------------------------------------------------------------------------
80
Eric Laurente0720872014-03-11 09:30:41 -070081status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -080082 audio_policy_dev_state_t state,
83 const char *device_address,
84 const char *device_name)
Eric Laurente552edb2014-03-10 17:42:56 -070085{
jiabina7b43792018-02-15 16:04:46 -080086 status_t status = setDeviceConnectionStateInt(device, state, device_address, device_name);
87 nextAudioPortGeneration();
88 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -080089}
90
François Gaffie44481e72016-04-20 07:49:57 +020091void AudioPolicyManager::broadcastDeviceConnectionState(audio_devices_t device,
92 audio_policy_dev_state_t state,
93 const String8 &device_address)
94{
95 AudioParameter param(device_address);
96 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganov388360c2016-10-17 17:09:41 -070097 AudioParameter::keyStreamConnect : AudioParameter::keyStreamDisconnect);
François Gaffie44481e72016-04-20 07:49:57 +020098 param.addInt(key, device);
99 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
100}
101
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800102status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800103 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -0800104 const char *device_address,
105 const char *device_name)
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800106{
Paul McLeane743a472015-01-28 11:07:31 -0800107 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s",
Mikhail Naganov7e22e942017-12-07 10:04:29 -0800108 device, state, device_address, device_name);
Eric Laurente552edb2014-03-10 17:42:56 -0700109
110 // connect/disconnect only 1 device at a time
111 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
112
François Gaffie53615e22015-03-19 09:24:12 +0100113 sp<DeviceDescriptor> devDesc =
114 mHwModules.getDeviceDescriptor(device, device_address, device_name);
Paul McLeane743a472015-01-28 11:07:31 -0800115
Eric Laurente552edb2014-03-10 17:42:56 -0700116 // handle output devices
117 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700118 SortedVector <audio_io_handle_t> outputs;
119
Eric Laurent3a4311c2014-03-17 12:00:47 -0700120 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
121
Eric Laurente552edb2014-03-10 17:42:56 -0700122 // save a copy of the opened output descriptors before any output is opened or closed
123 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
124 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700125 switch (state)
126 {
127 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800128 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700129 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700130 ALOGW("setDeviceConnectionState() device already connected: %x", device);
131 return INVALID_OPERATION;
132 }
133 ALOGV("setDeviceConnectionState() connecting device %x", device);
134
Eric Laurente552edb2014-03-10 17:42:56 -0700135 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700136 index = mAvailableOutputDevices.add(devDesc);
137 if (index >= 0) {
François Gaffie53615e22015-03-19 09:24:12 +0100138 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700139 if (module == 0) {
140 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
141 device);
142 mAvailableOutputDevices.remove(devDesc);
143 return INVALID_OPERATION;
144 }
Paul McLeane743a472015-01-28 11:07:31 -0800145 mAvailableOutputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700146 } else {
147 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700148 }
149
François Gaffie44481e72016-04-20 07:49:57 +0200150 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
151 // parameters on newly connected devices (instead of opening the outputs...)
152 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
153
Eric Laurenta1d525f2015-01-29 13:36:45 -0800154 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700155 mAvailableOutputDevices.remove(devDesc);
François Gaffie44481e72016-04-20 07:49:57 +0200156
157 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
158 devDesc->mAddress);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700159 return INVALID_OPERATION;
160 }
François Gaffie2110e042015-03-24 08:41:51 +0100161 // Propagate device availability to Engine
162 mEngine->setDeviceConnectionState(devDesc, state);
163
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700164 // outputs should never be empty here
165 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
166 "checkOutputsForDevice() returned no outputs but status OK");
167 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
168 outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800169
Eric Laurent3ae5f312015-02-03 17:12:08 -0800170 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700171 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700172 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700173 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700174 ALOGW("setDeviceConnectionState() device not connected: %x", device);
175 return INVALID_OPERATION;
176 }
177
Paul McLean5c477aa2014-08-20 16:47:57 -0700178 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
179
Paul McLeane743a472015-01-28 11:07:31 -0800180 // Send Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200181 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700182
Eric Laurente552edb2014-03-10 17:42:56 -0700183 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700184 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700185
Eric Laurenta1d525f2015-01-29 13:36:45 -0800186 checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress);
François Gaffie2110e042015-03-24 08:41:51 +0100187
188 // Propagate device availability to Engine
189 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700190 } break;
191
192 default:
193 ALOGE("setDeviceConnectionState() invalid state: %x", state);
194 return BAD_VALUE;
195 }
196
Mikhail Naganov37977152018-07-11 15:54:44 -0700197 checkForDeviceAndOutputChanges([&]() {
198 // outputs must be closed after checkOutputForAllStrategies() is executed
199 if (!outputs.isEmpty()) {
200 for (audio_io_handle_t output : outputs) {
201 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
202 // close unused outputs after device disconnection or direct outputs that have been
203 // opened by checkOutputsForDevice() to query dynamic parameters
204 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
205 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
206 (desc->mDirectOpenCount == 0))) {
207 closeOutput(output);
208 }
Eric Laurente552edb2014-03-10 17:42:56 -0700209 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700210 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
211 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700212 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700213 return false;
214 });
Eric Laurente552edb2014-03-10 17:42:56 -0700215
Eric Laurent87ffa392015-05-22 10:32:38 -0700216 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700217 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
218 updateCallRouting(newDevice);
219 }
Mikhail Naganov100f0122018-11-29 11:22:16 -0800220 const audio_devices_t msdOutDevice = getModuleDeviceTypes(
221 mAvailableOutputDevices, AUDIO_HARDWARE_MODULE_ID_MSD);
Eric Laurente552edb2014-03-10 17:42:56 -0700222 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700223 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
224 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
225 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700226 // do not force device change on duplicated output because if device is 0, it will
227 // also force a device 0 for the two outputs it is duplicated to which may override
228 // a valid device selection on those outputs.
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100229 bool force = (msdOutDevice == AUDIO_DEVICE_NONE || msdOutDevice != desc->device())
230 && !desc->isDuplicated()
François Gaffie53615e22015-03-19 09:24:12 +0100231 && (!device_distinguishes_on_address(device)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700232 // always force when disconnecting (a non-duplicated device)
233 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
Eric Laurentc75307b2015-03-17 15:29:32 -0700234 setOutputDevice(desc, newDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700235 }
Eric Laurente552edb2014-03-10 17:42:56 -0700236 }
237
Eric Laurentd60560a2015-04-10 11:31:20 -0700238 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
239 cleanUpForDevice(devDesc);
240 }
241
Eric Laurent72aa32f2014-05-30 18:51:48 -0700242 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700243 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700244 } // end if is output device
245
Eric Laurente552edb2014-03-10 17:42:56 -0700246 // handle input devices
247 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700248 SortedVector <audio_io_handle_t> inputs;
249
Eric Laurent3a4311c2014-03-17 12:00:47 -0700250 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700251 switch (state)
252 {
253 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700254 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700255 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700256 ALOGW("setDeviceConnectionState() device already connected: %d", device);
257 return INVALID_OPERATION;
258 }
François Gaffie53615e22015-03-19 09:24:12 +0100259 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700260 if (module == NULL) {
261 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
262 device);
263 return INVALID_OPERATION;
264 }
François Gaffie44481e72016-04-20 07:49:57 +0200265
266 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
267 // parameters on newly connected devices (instead of opening the inputs...)
268 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
269
Paul McLean9080a4c2015-06-18 08:24:02 -0700270 if (checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress) != NO_ERROR) {
François Gaffie44481e72016-04-20 07:49:57 +0200271 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
272 devDesc->mAddress);
Eric Laurentd4692962014-05-05 18:13:44 -0700273 return INVALID_OPERATION;
274 }
275
Eric Laurent3a4311c2014-03-17 12:00:47 -0700276 index = mAvailableInputDevices.add(devDesc);
277 if (index >= 0) {
Paul McLeane743a472015-01-28 11:07:31 -0800278 mAvailableInputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700279 } else {
280 return NO_MEMORY;
281 }
Eric Laurent3ae5f312015-02-03 17:12:08 -0800282
François Gaffie2110e042015-03-24 08:41:51 +0100283 // Propagate device availability to Engine
284 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700285 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700286
287 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700288 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700289 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700290 ALOGW("setDeviceConnectionState() device not connected: %d", device);
291 return INVALID_OPERATION;
292 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700293
294 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
295
296 // Set Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200297 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700298
Paul McLean9080a4c2015-06-18 08:24:02 -0700299 checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700300 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700301
François Gaffie2110e042015-03-24 08:41:51 +0100302 // Propagate device availability to Engine
303 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700304 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700305
306 default:
307 ALOGE("setDeviceConnectionState() invalid state: %x", state);
308 return BAD_VALUE;
309 }
310
Eric Laurentd4692962014-05-05 18:13:44 -0700311 closeAllInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700312 // As the input device list can impact the output device selection, update
313 // getDeviceForStrategy() cache
314 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700315
Eric Laurent87ffa392015-05-22 10:32:38 -0700316 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700317 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
318 updateCallRouting(newDevice);
319 }
320
Eric Laurentd60560a2015-04-10 11:31:20 -0700321 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
322 cleanUpForDevice(devDesc);
323 }
324
Eric Laurentb52c1522014-05-20 11:27:36 -0700325 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700326 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700327 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700328
329 ALOGW("setDeviceConnectionState() invalid device: %x", device);
330 return BAD_VALUE;
331}
332
Eric Laurente0720872014-03-11 09:30:41 -0700333audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100334 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700335{
Eric Laurent634b7142016-04-20 13:48:02 -0700336 sp<DeviceDescriptor> devDesc =
337 mHwModules.getDeviceDescriptor(device, device_address, "",
338 (strlen(device_address) != 0)/*matchAddress*/);
339
340 if (devDesc == 0) {
341 ALOGW("getDeviceConnectionState() undeclared device, type %08x, address: %s",
342 device, device_address);
343 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
344 }
François Gaffie53615e22015-03-19 09:24:12 +0100345
Eric Laurent3a4311c2014-03-17 12:00:47 -0700346 DeviceVector *deviceVector;
347
Eric Laurente552edb2014-03-10 17:42:56 -0700348 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700349 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700350 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700351 deviceVector = &mAvailableInputDevices;
352 } else {
353 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
354 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700355 }
Eric Laurent634b7142016-04-20 13:48:02 -0700356
357 return (deviceVector->getDevice(device, String8(device_address)) != 0) ?
358 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800359}
360
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800361status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
362 const char *device_address,
363 const char *device_name)
364{
365 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700366 String8 reply;
367 AudioParameter param;
368 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800369
370 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s",
371 device, device_address, device_name);
372
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800373 // connect/disconnect only 1 device at a time
374 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
375
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800376 // Check if the device is currently connected
377 sp<DeviceDescriptor> devDesc =
378 mHwModules.getDeviceDescriptor(device, device_address, device_name);
379 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
380 if (index < 0) {
381 // Nothing to do: device is not connected
382 return NO_ERROR;
383 }
384
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700385 // For offloaded A2DP, Hw modules may have the capability to
386 // configure codecs. Check if any of the loaded hw modules
387 // supports this.
388 // If supported, send a set parameter to configure A2DP codecs
389 // and return. No need to toggle device state.
390 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
391 reply = mpClientInterface->getParameters(
392 AUDIO_IO_HANDLE_NONE,
393 String8(AudioParameter::keyReconfigA2dpSupported));
394 AudioParameter repliedParameters(reply);
395 repliedParameters.getInt(
396 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
397 if (isReconfigA2dpSupported) {
398 const String8 key(AudioParameter::keyReconfigA2dp);
399 param.add(key, String8("true"));
400 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
401 return NO_ERROR;
402 }
403 }
404
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800405 // Toggle the device state: UNAVAILABLE -> AVAILABLE
406 // This will force reading again the device configuration
407 status = setDeviceConnectionState(device,
408 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
409 device_address, device_name);
410 if (status != NO_ERROR) {
411 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
412 status);
413 return status;
414 }
415
416 status = setDeviceConnectionState(device,
417 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
418 device_address, device_name);
419 if (status != NO_ERROR) {
420 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
421 status);
422 return status;
423 }
424
425 return NO_ERROR;
426}
427
Eric Laurentdc462862016-07-19 12:29:53 -0700428uint32_t AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700429{
430 bool createTxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700431 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700432
Andy Hunga76c7de2016-12-13 19:14:31 -0800433 if(!hasPrimaryOutput() || mPrimaryOutput->device() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurentdc462862016-07-19 12:29:53 -0700434 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700435 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800436 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700437 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
438
439 // release existing RX patch if any
440 if (mCallRxPatch != 0) {
441 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
442 mCallRxPatch.clear();
443 }
444 // release TX patch if any
445 if (mCallTxPatch != 0) {
446 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
447 mCallTxPatch.clear();
448 }
449
450 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
451 // via setOutputDevice() on primary output.
452 // Otherwise, create two audio patches for TX and RX path.
453 if (availablePrimaryOutputDevices() & rxDevice) {
Eric Laurentdc462862016-07-19 12:29:53 -0700454 muteWaitMs = setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700455 // If the TX device is also on the primary HW module, setOutputDevice() will take care
456 // of it due to legacy implementation. If not, create a patch.
457 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
458 == AUDIO_DEVICE_NONE) {
459 createTxPatch = true;
460 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700461 } else { // create RX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800462 mCallRxPatch = createTelephonyPatch(true /*isRx*/, rxDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700463 createTxPatch = true;
464 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700465 if (createTxPatch) { // create TX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800466 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txDevice, delayMs);
467 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700468
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800469 return muteWaitMs;
470}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700471
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800472sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
473 bool isRx, audio_devices_t device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700474 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700475
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800476 sp<DeviceDescriptor> txSourceDeviceDesc;
477 if (isRx) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700478 patchBuilder.addSink(findDevice(mAvailableOutputDevices, device)).
479 addSource(findDevice(mAvailableInputDevices, AUDIO_DEVICE_IN_TELEPHONY_RX));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800480 } else {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700481 patchBuilder.addSource(txSourceDeviceDesc = findDevice(mAvailableInputDevices, device)).
482 addSink(findDevice(mAvailableOutputDevices, AUDIO_DEVICE_OUT_TELEPHONY_TX));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800483 }
484
485 audio_devices_t outputDevice = isRx ? device : AUDIO_DEVICE_OUT_TELEPHONY_TX;
486 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(outputDevice, mOutputs);
487 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
488 // request to reuse existing output stream if one is already opened to reach the target device
489 if (output != AUDIO_IO_HANDLE_NONE) {
490 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
491 ALOG_ASSERT(!outputDesc->isDuplicated(),
492 "%s() %#x device output %d is duplicated", __func__, outputDevice, output);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700493 patchBuilder.addSource(outputDesc, { .stream = AUDIO_STREAM_PATCH });
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800494 }
495
496 if (!isRx) {
Eric Laurentc0a889f2015-10-14 14:36:34 -0700497 // terminate active capture if on the same HW module as the call TX source device
498 // FIXME: would be better to refine to only inputs whose profile connects to the
499 // call TX device but this information is not in the audio patch and logic here must be
500 // symmetric to the one in startInput()
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800501 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800502 if (activeDesc->hasSameHwModuleAs(txSourceDeviceDesc)) {
Eric Laurent8f42ea12018-08-08 09:08:25 -0700503 closeActiveClients(activeDesc);
Eric Laurentc0a889f2015-10-14 14:36:34 -0700504 }
505 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700506 }
Eric Laurentdc462862016-07-19 12:29:53 -0700507
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800508 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Mikhail Naganovdc769682018-05-04 15:34:08 -0700509 status_t status = mpClientInterface->createAudioPatch(
510 patchBuilder.patch(), &afPatchHandle, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800511 ALOGW_IF(status != NO_ERROR,
512 "%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
513 sp<AudioPatch> audioPatch;
514 if (status == NO_ERROR) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700515 audioPatch = new AudioPatch(patchBuilder.patch(), mUidCached);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800516 audioPatch->mAfPatchHandle = afPatchHandle;
517 audioPatch->mUid = mUidCached;
518 }
519 return audioPatch;
520}
521
Mikhail Naganovdc769682018-05-04 15:34:08 -0700522sp<DeviceDescriptor> AudioPolicyManager::findDevice(
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100523 const DeviceVector& devices, audio_devices_t device) const {
Mikhail Naganov708e0382018-05-30 09:53:04 -0700524 DeviceVector deviceList = devices.getDevicesFromTypeMask(device);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800525 ALOG_ASSERT(!deviceList.isEmpty(),
526 "%s() selected device type %#x is not in devices list", __func__, device);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700527 return deviceList.itemAt(0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700528}
529
Mikhail Naganov100f0122018-11-29 11:22:16 -0800530audio_devices_t AudioPolicyManager::getModuleDeviceTypes(
531 const DeviceVector& devices, const char *moduleId) const {
532 sp<HwModule> mod = mHwModules.getModuleFromName(moduleId);
533 return mod != 0 ? devices.getDeviceTypesFromHwModule(mod->getHandle()) : AUDIO_DEVICE_NONE;
534}
535
536bool AudioPolicyManager::isDeviceOfModule(
537 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
538 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
539 if (module != 0) {
540 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
541 .indexOf(devDesc) != NAME_NOT_FOUND
542 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
543 .indexOf(devDesc) != NAME_NOT_FOUND;
544 }
545 return false;
546}
547
Eric Laurente0720872014-03-11 09:30:41 -0700548void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700549{
550 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100551 // store previous phone state for management of sonification strategy below
552 int oldState = mEngine->getPhoneState();
553
554 if (mEngine->setPhoneState(state) != NO_ERROR) {
555 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700556 return;
557 }
François Gaffie2110e042015-03-24 08:41:51 +0100558 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700559 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700560 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700561 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800562 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700563 }
564
François Gaffie2110e042015-03-24 08:41:51 +0100565 /**
566 * Switching to or from incall state or switching between telephony and VoIP lead to force
567 * routing command.
568 */
569 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
570 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700571
572 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700573 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700574
Eric Laurente552edb2014-03-10 17:42:56 -0700575 int delayMs = 0;
576 if (isStateInCall(state)) {
577 nsecs_t sysTime = systemTime();
578 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700579 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700580 // mute media and sonification strategies and delay device switch by the largest
581 // latency of any output where either strategy is active.
582 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100583 if ((isStrategyActive(desc, STRATEGY_MEDIA,
584 SONIFICATION_HEADSET_MUSIC_DELAY,
585 sysTime) ||
586 isStrategyActive(desc, STRATEGY_SONIFICATION,
587 SONIFICATION_HEADSET_MUSIC_DELAY,
588 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700589 (delayMs < (int)desc->latency()*2)) {
590 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700591 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700592 setStrategyMute(STRATEGY_MEDIA, true, desc);
593 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700594 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700595 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
596 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700597 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
598 }
599 }
600
Eric Laurent87ffa392015-05-22 10:32:38 -0700601 if (hasPrimaryOutput()) {
602 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
603 // the device returned is not necessarily reachable via this output
604 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
605 // force routing command to audio hardware when ending call
606 // even if no device change is needed
607 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
608 rxDevice = mPrimaryOutput->device();
609 }
Eric Laurente552edb2014-03-10 17:42:56 -0700610
Eric Laurent87ffa392015-05-22 10:32:38 -0700611 if (state == AUDIO_MODE_IN_CALL) {
612 updateCallRouting(rxDevice, delayMs);
613 } else if (oldState == AUDIO_MODE_IN_CALL) {
614 if (mCallRxPatch != 0) {
615 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
616 mCallRxPatch.clear();
617 }
618 if (mCallTxPatch != 0) {
619 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
620 mCallTxPatch.clear();
621 }
622 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
623 } else {
624 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700625 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700626 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700627
628 // reevaluate routing on all outputs in case tracks have been started during the call
629 for (size_t i = 0; i < mOutputs.size(); i++) {
630 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
631 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
632 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
Yung Ti Suf60c8242018-05-10 18:07:26 +0800633 setOutputDevice(desc, newDevice, (newDevice != AUDIO_DEVICE_NONE), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700634 }
635 }
636
Eric Laurente552edb2014-03-10 17:42:56 -0700637 if (isStateInCall(state)) {
638 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700639 // force reevaluating accessibility routing when call starts
640 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700641 }
642
643 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700644 if (state == AUDIO_MODE_RINGTONE &&
645 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700646 mLimitRingtoneVolume = true;
647 } else {
648 mLimitRingtoneVolume = false;
649 }
650}
651
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700652audio_mode_t AudioPolicyManager::getPhoneState() {
653 return mEngine->getPhoneState();
654}
655
Eric Laurente0720872014-03-11 09:30:41 -0700656void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700657 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700658{
François Gaffie2110e042015-03-24 08:41:51 +0100659 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700660 if (config == mEngine->getForceUse(usage)) {
661 return;
662 }
Eric Laurente552edb2014-03-10 17:42:56 -0700663
François Gaffie2110e042015-03-24 08:41:51 +0100664 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
665 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
666 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700667 }
François Gaffie2110e042015-03-24 08:41:51 +0100668 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
669 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
670 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700671
672 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700673 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800674
Eric Laurentdc462862016-07-19 12:29:53 -0700675 //FIXME: workaround for truncated touch sounds
676 // to be removed when the problem is handled by system UI
677 uint32_t delayMs = 0;
678 uint32_t waitMs = 0;
679 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
680 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
681 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700682 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700683 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
Eric Laurentdc462862016-07-19 12:29:53 -0700684 waitMs = updateCallRouting(newDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700685 }
Eric Laurente552edb2014-03-10 17:42:56 -0700686 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700687 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
688 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
689 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700690 waitMs = setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE),
691 delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700692 }
Eric Laurente552edb2014-03-10 17:42:56 -0700693 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700694 applyStreamVolumes(outputDesc, newDevice, waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700695 }
696 }
697
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800698 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800699 audio_devices_t newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700700 // Force new input selection if the new device can not be reached via current input
Eric Laurentfb66dd92016-01-28 18:32:03 -0800701 if (activeDesc->mProfile->getSupportedDevices().types() &
702 (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
703 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700704 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800705 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700706 }
Eric Laurente552edb2014-03-10 17:42:56 -0700707 }
Eric Laurente552edb2014-03-10 17:42:56 -0700708}
709
Eric Laurente0720872014-03-11 09:30:41 -0700710void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700711{
712 ALOGV("setSystemProperty() property %s, value %s", property, value);
713}
714
715// Find a direct output profile compatible with the parameters passed, even if the input flags do
716// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800717sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700718 audio_devices_t device,
719 uint32_t samplingRate,
720 audio_format_t format,
721 audio_channel_mask_t channelMask,
722 audio_output_flags_t flags)
723{
Eric Laurent861a6282015-05-18 15:40:16 -0700724 // only retain flags that will drive the direct output profile selection
725 // if explicitly requested
726 static const uint32_t kRelevantFlags =
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700727 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
728 AUDIO_OUTPUT_FLAG_VOIP_RX);
Eric Laurent861a6282015-05-18 15:40:16 -0700729 flags =
730 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
731
732 sp<IOProfile> profile;
733
Mikhail Naganovd4120142017-12-06 15:49:22 -0800734 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800735 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent861a6282015-05-18 15:40:16 -0700736 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700737 samplingRate, NULL /*updatedSamplingRate*/,
738 format, NULL /*updatedFormat*/,
739 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700740 flags)) {
741 continue;
742 }
743 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100744 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700745 continue;
746 }
747 // if several profiles are compatible, give priority to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100748 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700749 continue;
750 }
751 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100752 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700753 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700754 }
Eric Laurente552edb2014-03-10 17:42:56 -0700755 }
756 }
Eric Laurent861a6282015-05-18 15:40:16 -0700757 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700758}
759
Eric Laurentf4e63452017-11-06 19:31:46 +0000760audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700761{
Eric Laurent3b73df72014-03-11 09:06:29 -0700762 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700763 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800764
765 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
766 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
767 // format, flags, etc. This may result in some discrepancy for functions that utilize
768 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
769 // and AudioSystem::getOutputSamplingRate().
770
Eric Laurentf4e63452017-11-06 19:31:46 +0000771 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
772 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
Eric Laurente552edb2014-03-10 17:42:56 -0700773
Eric Laurentf4e63452017-11-06 19:31:46 +0000774 ALOGV("getOutput() stream %d selected device %08x, output %d", stream, device, output);
775 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700776}
777
Eric Laurente83b55d2014-11-14 10:06:21 -0800778status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
779 audio_io_handle_t *output,
780 audio_session_t session,
781 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700782 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800783 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200784 audio_output_flags_t *flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700785 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800786 audio_port_handle_t *portId)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700787{
Eric Laurente83b55d2014-11-14 10:06:21 -0800788 audio_attributes_t attributes;
Eric Laurent8fc147b2018-07-22 19:13:55 -0700789 DeviceVector outputDevices;
790 routing_strategy strategy;
791 audio_devices_t device;
Eric Laurent97ac8712018-07-27 18:59:02 -0700792 const audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Mikhail Naganov100f0122018-11-29 11:22:16 -0800793 audio_devices_t msdDevice =
794 getModuleDeviceTypes(mAvailableOutputDevices, AUDIO_HARDWARE_MODULE_ID_MSD);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700795
Eric Laurent8f42ea12018-08-08 09:08:25 -0700796 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
797 if (*portId != AUDIO_PORT_HANDLE_NONE) {
798 return INVALID_OPERATION;
799 }
800
Eric Laurente83b55d2014-11-14 10:06:21 -0800801 if (attr != NULL) {
802 if (!isValidAttributes(attr)) {
803 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
804 attr->usage, attr->content_type, attr->flags,
805 attr->tags);
806 return BAD_VALUE;
807 }
808 attributes = *attr;
809 } else {
810 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
811 ALOGE("getOutputForAttr(): invalid stream type");
812 return BAD_VALUE;
813 }
814 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700815 }
Eric Laurent20b9ef02016-12-05 11:03:16 -0800816
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700817 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
Eric Laurent97ac8712018-07-27 18:59:02 -0700818 " session %d selectedDeviceId %d",
819 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
820 session, requestedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700821
Eric Laurent97ac8712018-07-27 18:59:02 -0700822 *stream = streamTypefromAttributesInt(&attributes);
823
824 strategy = getStrategyForAttr(&attributes);
825
Scott Randolph7b1fd232018-06-18 15:33:03 -0700826 // First check for explicit routing (eg. setPreferredDevice)
Eric Laurent97ac8712018-07-27 18:59:02 -0700827 if (requestedDeviceId != AUDIO_PORT_HANDLE_NONE) {
828 sp<DeviceDescriptor> deviceDesc =
829 mAvailableOutputDevices.getDeviceFromId(requestedDeviceId);
830 device = deviceDesc->type();
Scott Randolph7b1fd232018-06-18 15:33:03 -0700831 } else {
832 // If no explict route, is there a matching dynamic policy that applies?
833 sp<SwAudioOutputDescriptor> desc;
834 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
835 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
836 if (!audio_has_proportional_frames(config->format)) {
837 return BAD_VALUE;
838 }
839 *stream = streamTypefromAttributesInt(&attributes);
840 *output = desc->mIoHandle;
Eric Laurent97ac8712018-07-27 18:59:02 -0700841 AudioMix *mix = desc->mPolicyMix;
842 sp<DeviceDescriptor> deviceDesc =
843 mAvailableOutputDevices.getDevice(mix->mDeviceType, mix->mDeviceAddress);
844 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Scott Randolph7b1fd232018-06-18 15:33:03 -0700845 ALOGV("getOutputForAttr() returns output %d", *output);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700846 goto exit;
Scott Randolph7b1fd232018-06-18 15:33:03 -0700847 }
848
849 // Virtual sources must always be dynamicaly or explicitly routed
850 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
851 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
852 return BAD_VALUE;
853 }
Eric Laurent97ac8712018-07-27 18:59:02 -0700854 device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700855 }
Scott Randolph7b1fd232018-06-18 15:33:03 -0700856
Eric Laurente83b55d2014-11-14 10:06:21 -0800857 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200858 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -0700859 }
860
Nadav Barb2f18162018-07-18 13:01:53 +0300861 // Set incall music only if device was explicitly set, and fallback to the device which is
862 // chosen by the engine if not.
863 // FIXME: provide a more generic approach which is not device specific and move this back
864 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +0200865 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
Nadav Barb2f18162018-07-18 13:01:53 +0300866 if (device == AUDIO_DEVICE_OUT_TELEPHONY_TX &&
Nadav Bar20919492018-11-20 10:20:51 +0200867 (*stream == AUDIO_STREAM_MUSIC || attributes.usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +0300868 audio_is_linear_pcm(config->format) &&
869 isInCall()) {
Eric Laurent97ac8712018-07-27 18:59:02 -0700870 if (requestedDeviceId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +0300871 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
872 } else {
Eric Laurent97ac8712018-07-27 18:59:02 -0700873 // Get the devce type directly from the engine to bypass preferred route logic
Nadav Barb2f18162018-07-18 13:01:53 +0300874 device = mEngine->getDeviceForStrategy(strategy);
875 }
876 }
877
Glenn Kasten49f36ba2017-12-06 13:02:02 -0800878 ALOGV("getOutputForAttr() device 0x%x, sampling rate %d, format %#x, channel mask %#x, "
879 "flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +0200880 device, config->sample_rate, config->format, config->channel_mask, *flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700881
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100882 *output = AUDIO_IO_HANDLE_NONE;
883 if (msdDevice != AUDIO_DEVICE_NONE) {
884 *output = getOutputForDevice(msdDevice, session, *stream, config, flags);
885 if (*output != AUDIO_IO_HANDLE_NONE && setMsdPatch(device) == NO_ERROR) {
886 ALOGV("%s() Using MSD device 0x%x instead of device 0x%x",
887 __func__, msdDevice, device);
888 device = msdDevice;
889 } else {
890 *output = AUDIO_IO_HANDLE_NONE;
891 }
892 }
893 if (*output == AUDIO_IO_HANDLE_NONE) {
894 *output = getOutputForDevice(device, session, *stream, config, flags);
895 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800896 if (*output == AUDIO_IO_HANDLE_NONE) {
897 return INVALID_OPERATION;
898 }
Paul McLeanaa981192015-03-21 09:55:15 -0700899
Eric Laurent8fc147b2018-07-22 19:13:55 -0700900 outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -0700901 *selectedDeviceId = outputDevices.size() > 0 ? outputDevices.itemAt(0)->getId()
902 : AUDIO_PORT_HANDLE_NONE;
903
Eric Laurent8fc147b2018-07-22 19:13:55 -0700904exit:
905 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
906 .format = config->format,
907 .channel_mask = config->channel_mask };
Eric Laurent8f42ea12018-08-08 09:08:25 -0700908 *portId = AudioPort::getNextUniqueId();
909
Eric Laurent8fc147b2018-07-22 19:13:55 -0700910 sp<TrackClientDescriptor> clientDesc =
Eric Laurent97ac8712018-07-27 18:59:02 -0700911 new TrackClientDescriptor(*portId, uid, session, attributes, clientConfig,
912 requestedDeviceId, *stream,
913 getStrategyForAttr(&attributes),
914 *flags);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700915 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Andy Hung39efb7a2018-09-26 15:39:28 -0700916 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700917
918 ALOGV(" getOutputForAttr() returns output %d selectedDeviceId %d for port ID %d",
919 *output, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -0700920
Eric Laurente83b55d2014-11-14 10:06:21 -0800921 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700922}
923
924audio_io_handle_t AudioPolicyManager::getOutputForDevice(
925 audio_devices_t device,
Kevin Rocard169753c2017-03-06 14:18:23 -0800926 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700927 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -0800928 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200929 audio_output_flags_t *flags)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700930{
Andy Hungc88b0642018-04-27 15:42:35 -0700931 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700932 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700933
Eric Laurente552edb2014-03-10 17:42:56 -0700934 // open a direct output if required by specified parameters
935 //force direct flag if offload flag is set: offloading implies a direct output stream
936 // and all common behaviors are driven by checking only the direct flag
937 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +0200938 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
939 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700940 }
Nadav Bar766fb022018-01-07 12:18:03 +0200941 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
942 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -0700943 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800944 // only allow deep buffering for music stream type
945 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +0200946 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700947 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +0200948 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700949 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
950 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +0200951 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800952 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700953 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +0200954 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700955 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +0200956 audio_is_linear_pcm(config->format) &&
957 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200958 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700959 AUDIO_OUTPUT_FLAG_DIRECT);
960 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700961 }
Eric Laurente552edb2014-03-10 17:42:56 -0700962
Nadav Bar766fb022018-01-07 12:18:03 +0200963
Eric Laurentb732cf52014-09-24 19:08:21 -0700964 sp<IOProfile> profile;
965
966 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700967 // and not explicitly requested
Nadav Bar766fb022018-01-07 12:18:03 +0200968 if (((*flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Eric Laurentfe231122017-11-17 17:48:06 -0800969 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
970 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
Eric Laurentb732cf52014-09-24 19:08:21 -0700971 goto non_direct_output;
972 }
973
Andy Hung2ddee192015-12-18 17:34:44 -0800974 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
975 // This prevents creating an offloaded track and tearing it down immediately after start
976 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700977 // FIXME: We should check the audio session here but we do not have it in this context.
978 // This may prevent offloading in rare situations where effects are left active by apps
979 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700980
Nadav Bar766fb022018-01-07 12:18:03 +0200981 if (((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800982 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700983 profile = getProfileForDirectOutput(device,
Eric Laurentfe231122017-11-17 17:48:06 -0800984 config->sample_rate,
985 config->format,
986 config->channel_mask,
Nadav Bar766fb022018-01-07 12:18:03 +0200987 (audio_output_flags_t)*flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700988 }
989
Eric Laurent1c333e22014-05-20 10:48:17 -0700990 if (profile != 0) {
Andy Hungc88b0642018-04-27 15:42:35 -0700991 // exclusive outputs for MMAP and Offload are enforced by different session ids.
992 for (size_t i = 0; i < mOutputs.size(); i++) {
993 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
994 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
995 // reuse direct output if currently open by the same client
996 // and configured with same parameters
997 if ((config->sample_rate == desc->mSamplingRate) &&
Andy Hung5659ed52018-04-30 10:31:26 -0700998 (config->format == desc->mFormat) &&
Andy Hungc88b0642018-04-27 15:42:35 -0700999 (config->channel_mask == desc->mChannelMask) &&
1000 (session == desc->mDirectClientSession)) {
1001 desc->mDirectOpenCount++;
1002 ALOGI("getOutputForDevice() reusing direct output %d for session %d",
1003 mOutputs.keyAt(i), session);
1004 return mOutputs.keyAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001005 }
1006 }
1007 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08001008
1009 if (!profile->canOpenNewIo()) {
1010 goto non_direct_output;
Eric Laurente552edb2014-03-10 17:42:56 -07001011 }
Eric Laurent861a6282015-05-18 15:40:16 -07001012
Eric Laurent3974e3b2017-12-07 17:58:43 -08001013 sp<SwAudioOutputDescriptor> outputDesc =
1014 new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurent53b810e2017-12-10 17:25:10 -08001015
Mikhail Naganov708e0382018-05-30 09:53:04 -07001016 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -08001017 String8 address = outputDevices.size() > 0 ? outputDevices.itemAt(0)->mAddress
1018 : String8("");
1019
Dean Wheatley3023b382018-08-09 07:42:40 +10001020 // MSD patch may be using the only output stream that can service this request. Release
1021 // MSD patch to prioritize this request over any active output on MSD.
1022 AudioPatchCollection msdPatches = getMsdPatches();
1023 for (size_t i = 0; i < msdPatches.size(); i++) {
1024 const auto& patch = msdPatches[i];
1025 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1026 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1027 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
1028 (sink->ext.device.type & device) != AUDIO_DEVICE_NONE &&
1029 (address.isEmpty() || strncmp(sink->ext.device.address, address.string(),
1030 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
1031 releaseAudioPatch(patch->mHandle, mUidCached);
1032 break;
1033 }
1034 }
1035 }
1036
Nadav Bar766fb022018-01-07 12:18:03 +02001037 status = outputDesc->open(config, device, address, stream, *flags, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07001038
1039 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001040 if (status != NO_ERROR ||
Eric Laurentfe231122017-11-17 17:48:06 -08001041 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
Andy Hung5659ed52018-04-30 10:31:26 -07001042 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->mFormat) ||
Eric Laurentfe231122017-11-17 17:48:06 -08001043 (config->channel_mask != 0 && config->channel_mask != outputDesc->mChannelMask)) {
1044 ALOGV("getOutputForDevice() failed opening direct output: output %d sample rate %d %d,"
1045 "format %d %d, channel mask %04x %04x", output, config->sample_rate,
1046 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
1047 config->channel_mask, outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001048 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001049 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07001050 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001051 // fall back to mixer output if possible when the direct output could not be open
Eric Laurentfe231122017-11-17 17:48:06 -08001052 if (audio_is_linear_pcm(config->format) &&
1053 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -08001054 goto non_direct_output;
1055 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001056 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001057 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001058 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -08001059 outputDesc->mDirectClientSession = session;
1060
Eric Laurente552edb2014-03-10 17:42:56 -07001061 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001062 mPreviousOutputs = mOutputs;
Eric Laurentf4e63452017-11-06 19:31:46 +00001063 ALOGV("getOutputForDevice() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001064 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001065 return output;
1066 }
1067
Eric Laurentb732cf52014-09-24 19:08:21 -07001068non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001069
1070 // A request for HW A/V sync cannot fallback to a mixed output because time
1071 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001072 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001073 return AUDIO_IO_HANDLE_NONE;
1074 }
1075
Eric Laurente552edb2014-03-10 17:42:56 -07001076 // ignoring channel mask due to downmix capability in mixer
1077
1078 // open a non direct output
1079
1080 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001081 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001082 // get which output is suitable for the specified stream. The actual
1083 // routing change will happen when startOutput() will be called
1084 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1085
Eric Laurent8838a382014-09-08 16:44:28 -07001086 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001087 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1088 output = selectOutput(outputs, *flags, config->format);
Eric Laurente552edb2014-03-10 17:42:56 -07001089 }
Eric Laurentf4e63452017-11-06 19:31:46 +00001090 ALOGW_IF((output == 0), "getOutputForDevice() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001091 "sampling rate %d, format %#x, channels %#x, flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +02001092 stream, config->sample_rate, config->format, config->channel_mask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001093
Eric Laurente552edb2014-03-10 17:42:56 -07001094 return output;
1095}
1096
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001097sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001098 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001099 if (msdModule != 0) {
1100 DeviceVector msdInputDevices = mAvailableInputDevices.getDevicesFromHwModule(
1101 msdModule->getHandle());
1102 if (!msdInputDevices.isEmpty()) return msdInputDevices.itemAt(0);
1103 }
1104 return 0;
1105}
1106
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001107const AudioPatchCollection AudioPolicyManager::getMsdPatches() const {
1108 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001109 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1110 if (msdModule != 0) {
1111 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1112 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1113 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1114 const struct audio_port_config *source = &patch->mPatch.sources[j];
1115 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1116 source->ext.device.hw_module == msdModule->getHandle()) {
1117 msdPatches.addAudioPatch(patch->mHandle, patch);
1118 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001119 }
1120 }
1121 }
1122 return msdPatches;
1123}
1124
1125status_t AudioPolicyManager::getBestMsdAudioProfileFor(audio_devices_t outputDevice,
1126 bool hwAvSync, audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1127{
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001128 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001129 if (msdModule == nullptr) {
1130 ALOGE("%s() unable to get MSD module", __func__);
1131 return NO_INIT;
1132 }
1133 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(outputDevice);
1134 if (deviceModule == nullptr) {
1135 ALOGE("%s() unable to get module for %#x", __func__, outputDevice);
1136 return NO_INIT;
1137 }
1138 const InputProfileCollection &inputProfiles = msdModule->getInputProfiles();
1139 if (inputProfiles.isEmpty()) {
1140 ALOGE("%s() no input profiles for MSD module", __func__);
1141 return NO_INIT;
1142 }
1143 const OutputProfileCollection &outputProfiles = deviceModule->getOutputProfiles();
1144 if (outputProfiles.isEmpty()) {
1145 ALOGE("%s() no output profiles for device %#x", __func__, outputDevice);
1146 return NO_INIT;
1147 }
1148 AudioProfileVector msdProfiles;
1149 // Each IOProfile represents a MixPort from audio_policy_configuration.xml
1150 for (const auto &inProfile : inputProfiles) {
1151 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0)) {
1152 msdProfiles.appendVector(inProfile->getAudioProfiles());
1153 }
1154 }
1155 AudioProfileVector deviceProfiles;
1156 for (const auto &outProfile : outputProfiles) {
1157 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0)) {
1158 deviceProfiles.appendVector(outProfile->getAudioProfiles());
1159 }
1160 }
1161 struct audio_config_base bestSinkConfig;
1162 status_t result = msdProfiles.findBestMatchingOutputConfig(deviceProfiles,
1163 compressedFormatsOrder, surroundChannelMasksOrder, true /*preferHigherSamplingRates*/,
1164 &bestSinkConfig);
1165 if (result != NO_ERROR) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001166 ALOGD("%s() no matching profiles found for device: %#x, hwAvSync: %d",
1167 __func__, outputDevice, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001168 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001169 }
1170 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1171 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1172 sinkConfig->format = bestSinkConfig.format;
1173 // For encoded streams force direct flag to prevent downstream mixing.
1174 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1175 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
1176 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1177 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1178 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1179 sourceConfig->format = bestSinkConfig.format;
1180 // Copy input stream directly without any processing (e.g. resampling).
1181 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1182 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1183 if (hwAvSync) {
1184 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1185 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1186 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1187 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1188 }
1189 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1190 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1191 sinkConfig->config_mask |= config_mask;
1192 sourceConfig->config_mask |= config_mask;
1193 return NO_ERROR;
1194}
1195
1196PatchBuilder AudioPolicyManager::buildMsdPatch(audio_devices_t outputDevice) const
1197{
1198 PatchBuilder patchBuilder;
1199 patchBuilder.addSource(getMsdAudioInDevice()).
1200 addSink(findDevice(mAvailableOutputDevices, outputDevice));
1201 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1202 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
1203 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1204 // For now, we just forcefully try with HwAvSync first.
1205 status_t res = getBestMsdAudioProfileFor(outputDevice, true /*hwAvSync*/,
1206 &sourceConfig, &sinkConfig) == NO_ERROR ? NO_ERROR :
1207 getBestMsdAudioProfileFor(
1208 outputDevice, false /*hwAvSync*/, &sourceConfig, &sinkConfig);
1209 if (res == NO_ERROR) {
1210 // Found a matching profile for encoded audio. Re-create PatchBuilder with this config.
1211 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1212 }
1213 ALOGV("%s() no matching profile found. Fall through to default PCM patch"
1214 " supporting PCM format conversion.", __func__);
1215 return patchBuilder;
1216}
1217
1218status_t AudioPolicyManager::setMsdPatch(audio_devices_t outputDevice) {
1219 ALOGV("%s() for outputDevice %#x", __func__, outputDevice);
1220 if (outputDevice == AUDIO_DEVICE_NONE) {
1221 // Use media strategy for unspecified output device. This should only
1222 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1223 // therefore invalidate explicit routing requests.
1224 outputDevice = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
1225 }
1226 PatchBuilder patchBuilder = buildMsdPatch(outputDevice);
1227 const struct audio_patch* patch = patchBuilder.patch();
1228 const AudioPatchCollection msdPatches = getMsdPatches();
1229 if (!msdPatches.isEmpty()) {
1230 LOG_ALWAYS_FATAL_IF(msdPatches.size() > 1,
1231 "The current MSD prototype only supports one output patch");
1232 sp<AudioPatch> currentPatch = msdPatches.valueAt(0);
1233 if (audio_patches_are_equal(&currentPatch->mPatch, patch)) {
1234 return NO_ERROR;
1235 }
1236 releaseAudioPatch(currentPatch->mHandle, mUidCached);
1237 }
1238 status_t status = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1239 patch, 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1240 ALOGE_IF(status != NO_ERROR, "%s() error %d creating MSD audio patch", __func__, status);
1241 ALOGI_IF(status == NO_ERROR, "%s() Patch created from MSD_IN to "
1242 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__, outputDevice,
1243 patch->sources[0].format, patch->sources[0].channel_mask, patch->sources[0].sample_rate);
1244 return status;
1245}
1246
Eric Laurente0720872014-03-11 09:30:41 -07001247audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001248 audio_output_flags_t flags,
1249 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001250{
1251 // select one output among several that provide a path to a particular device or set of
1252 // devices (the list was previously build by getOutputsForDevice()).
1253 // The priority is as follows:
1254 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001255 // 2: the output with the bit depth the closest to the requested one
1256 // 3: the primary output
1257 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001258
1259 if (outputs.size() == 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001260 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001261 }
1262 if (outputs.size() == 1) {
1263 return outputs[0];
1264 }
1265
1266 int maxCommonFlags = 0;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001267 audio_io_handle_t outputForFlags = AUDIO_IO_HANDLE_NONE;
1268 audio_io_handle_t outputForPrimary = AUDIO_IO_HANDLE_NONE;
1269 audio_io_handle_t outputForFormat = AUDIO_IO_HANDLE_NONE;
Eric Laurente6930022016-02-11 10:20:40 -08001270 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1271 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001272
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001273 for (audio_io_handle_t output : outputs) {
1274 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001275 if (!outputDesc->isDuplicated()) {
chenhg1794d712018-10-09 15:20:37 -07001276 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1277 continue;
1278 }
Eric Laurent8838a382014-09-08 16:44:28 -07001279 // if a valid format is specified, skip output if not compatible
1280 if (format != AUDIO_FORMAT_INVALID) {
chenhg1794d712018-10-09 15:20:37 -07001281 if (!audio_is_linear_pcm(format)) {
Eric Laurent8838a382014-09-08 16:44:28 -07001282 continue;
1283 }
Eric Laurente6930022016-02-11 10:20:40 -08001284 if (AudioPort::isBetterFormatMatch(
1285 outputDesc->mFormat, bestFormat, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001286 outputForFormat = output;
Eric Laurente6930022016-02-11 10:20:40 -08001287 bestFormat = outputDesc->mFormat;
1288 }
Eric Laurent8838a382014-09-08 16:44:28 -07001289 }
1290
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001291 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001292 if (commonFlags >= maxCommonFlags) {
1293 if (commonFlags == maxCommonFlags) {
Andy Hungc9901522017-11-10 20:07:54 -08001294 if (format != AUDIO_FORMAT_INVALID
1295 && AudioPort::isBetterFormatMatch(
1296 outputDesc->mFormat, bestFormatForFlags, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001297 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001298 bestFormatForFlags = outputDesc->mFormat;
1299 }
1300 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001301 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001302 maxCommonFlags = commonFlags;
1303 bestFormatForFlags = outputDesc->mFormat;
1304 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001305 ALOGV("selectOutput() commonFlags for output %d, %04x", output, commonFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001306 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001307 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001308 outputForPrimary = output;
Eric Laurente552edb2014-03-10 17:42:56 -07001309 }
1310 }
1311 }
1312
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001313 if (outputForFlags != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001314 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001315 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001316 if (outputForFormat != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001317 return outputForFormat;
1318 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001319 if (outputForPrimary != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001320 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001321 }
1322
1323 return outputs[0];
1324}
1325
Eric Laurent8fc147b2018-07-22 19:13:55 -07001326status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001327{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001328 ALOGV("%s portId %d", __FUNCTION__, portId);
1329
1330 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1331 if (outputDesc == 0) {
1332 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001333 return BAD_VALUE;
1334 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001335 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001336
Eric Laurent8fc147b2018-07-22 19:13:55 -07001337 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001338 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001339
Eric Laurent733ce942017-12-07 12:18:25 -08001340 status_t status = outputDesc->start();
1341 if (status != NO_ERROR) {
1342 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001343 }
1344
Eric Laurent97ac8712018-07-27 18:59:02 -07001345 uint32_t delayMs;
1346 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001347
1348 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001349 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001350 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001351 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001352 if (delayMs != 0) {
1353 usleep(delayMs * 1000);
1354 }
1355
1356 return status;
1357}
1358
Eric Laurent97ac8712018-07-27 18:59:02 -07001359status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1360 const sp<TrackClientDescriptor>& client,
1361 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001362{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001363 // cannot start playback of STREAM_TTS if any other output is being used
1364 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001365
1366 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001367 audio_stream_type_t stream = client->stream();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001368 if (stream == AUDIO_STREAM_TTS) {
1369 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001370 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001371 return INVALID_OPERATION;
1372 } else {
1373 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1374 }
1375 } else {
1376 // some playback other than beacon starts
1377 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1378 }
1379
Eric Laurent77305a62016-07-25 16:39:22 -07001380 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001381 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001382 bool force = !outputDesc->isActive() &&
1383 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001384
Eric Laurent97ac8712018-07-27 18:59:02 -07001385 audio_devices_t device = AUDIO_DEVICE_NONE;
1386 AudioMix *policyMix = NULL;
1387 const char *address = NULL;
1388 if (outputDesc->mPolicyMix != NULL) {
1389 policyMix = outputDesc->mPolicyMix;
1390 address = policyMix->mDeviceAddress.string();
1391 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1392 device = policyMix->mDeviceType;
1393 } else {
1394 device = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1395 }
1396 }
1397
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001398 // requiresMuteCheck is false when we can bypass mute strategy.
1399 // It covers a common case when there is no materially active audio
1400 // and muting would result in unnecessary delay and dropped audio.
1401 const uint32_t outputLatencyMs = outputDesc->latency();
1402 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1403
Eric Laurente552edb2014-03-10 17:42:56 -07001404 // increment usage count for this stream on the requested output:
1405 // NOTE that the usage count is the same for duplicated output and hardware output which is
1406 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001407 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001408
1409 if (client->hasPreferredDevice(true)) {
1410 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
1411 if (device != outputDesc->device()) {
1412 checkStrategyRoute(getStrategy(stream), outputDesc->mIoHandle);
1413 }
1414 }
Eric Laurente552edb2014-03-10 17:42:56 -07001415
Eric Laurent36829f92017-04-07 19:04:42 -07001416 if (stream == AUDIO_STREAM_MUSIC) {
1417 selectOutputForMusicEffects();
1418 }
1419
Eric Laurent592dd7b2018-08-05 18:58:48 -07001420 if (outputDesc->streamActiveCount(stream) == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001421 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001422 if (device == AUDIO_DEVICE_NONE) {
1423 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001424 }
Eric Laurent36829f92017-04-07 19:04:42 -07001425
Eric Laurente552edb2014-03-10 17:42:56 -07001426 routing_strategy strategy = getStrategy(stream);
1427 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001428 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1429 (beaconMuteLatency > 0);
1430 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001431 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001432 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001433 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001434 // An output has a shared device if
1435 // - managed by the same hw module
1436 // - supports the currently selected device
1437 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
1438 && (desc->supportedDevices() & device) != AUDIO_DEVICE_NONE;
1439
Eric Laurent77305a62016-07-25 16:39:22 -07001440 // force a device change if any other output is:
1441 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001442 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001443 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001444 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001445 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001446 // change the device currently selected by the other output.
1447 if (sharedDevice &&
Eric Laurent77305a62016-07-25 16:39:22 -07001448 desc->device() != device &&
Eric Laurent77305a62016-07-25 16:39:22 -07001449 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001450 force = true;
1451 }
1452 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001453 // a notification so that audio focus effect can propagate, or that a mute/unmute
1454 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001455 const uint32_t latencyMs = desc->latency();
1456 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1457
1458 if (shouldWait && isActive && (waitMs < latencyMs)) {
1459 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001460 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001461
1462 // Require mute check if another output is on a shared device
1463 // and currently active to have proper drain and avoid pops.
1464 // Note restoring AudioTracks onto this output needs to invoke
1465 // a volume ramp if there is no mute.
1466 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001467 }
1468 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001469
1470 const uint32_t muteWaitMs =
1471 setOutputDevice(outputDesc, device, force, 0, NULL, address, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001472
Eric Laurente552edb2014-03-10 17:42:56 -07001473 // apply volume rules for current stream and device if necessary
1474 checkAndSetVolume(stream,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001475 mVolumeCurves->getVolumeIndex(stream, outputDesc->device()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001476 outputDesc,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001477 outputDesc->device());
Eric Laurente552edb2014-03-10 17:42:56 -07001478
1479 // update the outputs if starting an output with a stream that can affect notification
1480 // routing
1481 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001482
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001483 // force reevaluating accessibility routing when ringtone or alarm starts
1484 if (strategy == STRATEGY_SONIFICATION) {
1485 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1486 }
Eric Laurentdc462862016-07-19 12:29:53 -07001487
1488 if (waitMs > muteWaitMs) {
1489 *delayMs = waitMs - muteWaitMs;
1490 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001491
1492 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1493 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1494 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1495 // change occurs after the MixerThread starts and causes a stream volume
1496 // glitch.
1497 //
1498 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001499 }
Eric Laurentdc462862016-07-19 12:29:53 -07001500
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001501 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1502 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1503 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1504 }
1505
Eric Laurent97ac8712018-07-27 18:59:02 -07001506 // Automatically enable the remote submix input when output is started on a re routing mix
1507 // of type MIX_TYPE_RECORDERS
1508 if (audio_is_remote_submix_device(device) && policyMix != NULL &&
1509 policyMix->mMixType == MIX_TYPE_RECORDERS) {
1510 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1511 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1512 address,
1513 "remote-submix");
1514 }
1515
Eric Laurente552edb2014-03-10 17:42:56 -07001516 return NO_ERROR;
1517}
1518
Eric Laurent8fc147b2018-07-22 19:13:55 -07001519status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001520{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001521 ALOGV("%s portId %d", __FUNCTION__, portId);
1522
1523 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1524 if (outputDesc == 0) {
1525 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001526 return BAD_VALUE;
1527 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001528 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001529
Eric Laurent97ac8712018-07-27 18:59:02 -07001530 ALOGV("stopOutput() output %d, stream %d, session %d",
1531 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07001532
Eric Laurent97ac8712018-07-27 18:59:02 -07001533 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08001534
Eric Laurent733ce942017-12-07 12:18:25 -08001535 if (status == NO_ERROR ) {
1536 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001537 }
1538 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001539}
1540
Eric Laurent97ac8712018-07-27 18:59:02 -07001541status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1542 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07001543{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001544 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07001545 audio_stream_type_t stream = client->stream();
1546
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001547 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1548
Eric Laurent592dd7b2018-08-05 18:58:48 -07001549 if (outputDesc->streamActiveCount(stream) > 0) {
1550 if (outputDesc->streamActiveCount(stream) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001551 // Automatically disable the remote submix input when output is stopped on a
1552 // re routing mix of type MIX_TYPE_RECORDERS
1553 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1554 outputDesc->mPolicyMix != NULL &&
1555 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1556 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1557 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1558 outputDesc->mPolicyMix->mDeviceAddress,
1559 "remote-submix");
1560 }
1561 }
1562 bool forceDeviceUpdate = false;
1563 if (client->hasPreferredDevice(true)) {
1564 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1565 forceDeviceUpdate = true;
1566 }
1567
Eric Laurente552edb2014-03-10 17:42:56 -07001568 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07001569 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07001570
Eric Laurente552edb2014-03-10 17:42:56 -07001571 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001572 if (outputDesc->streamActiveCount(stream) == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001573 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001574 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001575 // delay the device switch by twice the latency because stopOutput() is executed when
1576 // the track stop() command is received and at that time the audio track buffer can
1577 // still contain data that needs to be drained. The latency only covers the audio HAL
1578 // and kernel buffers. Also the latency does not always include additional delay in the
1579 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001580 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001581
1582 // force restoring the device selection on other active outputs if it differs from the
1583 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001584 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001585 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001586 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001587 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001588 desc->isActive() &&
1589 outputDesc->sharesHwModuleWith(desc) &&
1590 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001591 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1592 bool force = desc->device() != newDevice2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001593
Eric Laurentc75307b2015-03-17 15:29:32 -07001594 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001595 newDevice2,
1596 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001597 delayMs);
1598 // re-apply device specific volume if not done by setOutputDevice()
1599 if (!force) {
1600 applyStreamVolumes(desc, newDevice2, delayMs);
1601 }
Eric Laurente552edb2014-03-10 17:42:56 -07001602 }
1603 }
1604 // update the outputs if stopping one with a stream that can affect notification routing
1605 handleNotificationRoutingForStream(stream);
1606 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001607
1608 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1609 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1610 setStrategyMute(STRATEGY_SONIFICATION, false, outputDesc);
1611 }
1612
Eric Laurent36829f92017-04-07 19:04:42 -07001613 if (stream == AUDIO_STREAM_MUSIC) {
1614 selectOutputForMusicEffects();
1615 }
Eric Laurente552edb2014-03-10 17:42:56 -07001616 return NO_ERROR;
1617 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001618 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001619 return INVALID_OPERATION;
1620 }
1621}
1622
Eric Laurent8fc147b2018-07-22 19:13:55 -07001623void AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001624{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001625 ALOGV("%s portId %d", __FUNCTION__, portId);
1626
1627 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1628 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07001629 // If an output descriptor is closed due to a device routing change,
1630 // then there are race conditions with releaseOutput from tracks
1631 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
1632 // destroyed shortly thereafter.
1633 //
1634 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07001635 ALOGW("releaseOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001636 return;
1637 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001638
1639 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001640
Eric Laurent8fc147b2018-07-22 19:13:55 -07001641 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1642 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001643 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07001644 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001645 return;
1646 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001647 if (--outputDesc->mDirectOpenCount == 0) {
1648 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07001649 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001650 }
1651 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001652 // stopOutput() needs to be successfully called before releaseOutput()
1653 // otherwise there may be inaccurate stream reference counts.
1654 // This is checked in outputDesc->removeClient below.
1655 outputDesc->removeClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001656}
1657
Eric Laurentcaf7f482014-11-25 17:50:47 -08001658status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1659 audio_io_handle_t *input,
1660 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001661 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001662 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001663 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001664 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001665 input_type_t *inputType,
1666 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001667{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001668 ALOGV("getInputForAttr() source %d, sampling rate %d, format %#x, channel mask %#x,"
Eric Laurentcaf7f482014-11-25 17:50:47 -08001669 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001670 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001671
Eric Laurentad2e7b92017-09-14 20:06:42 -07001672 status_t status = NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -08001673 // handle legacy remote submix case where the address was not always specified
1674 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001675 audio_source_t halInputSource;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001676 audio_source_t inputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001677 AudioMix *policyMix = NULL;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001678 DeviceVector inputDevices;
Eric Laurent8fc147b2018-07-22 19:13:55 -07001679 sp<AudioInputDescriptor> inputDesc;
1680 sp<RecordClientDescriptor> clientDesc;
1681 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001682 bool isSoundTrigger;
1683 audio_devices_t device;
1684
1685 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1686 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1687 return INVALID_OPERATION;
1688 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001689
Eric Laurentfe231122017-11-17 17:48:06 -08001690 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1691 inputSource = AUDIO_SOURCE_MIC;
1692 }
1693
Paul McLean466dc8e2015-04-17 13:15:36 -06001694 // Explicit routing?
1695 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -07001696 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
jiabinc0c831a2018-01-29 17:55:15 -08001697 deviceDesc = mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001698 }
Paul McLean466dc8e2015-04-17 13:15:36 -06001699
Eric Laurentad2e7b92017-09-14 20:06:42 -07001700 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1701 // possible
1702 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1703 *input != AUDIO_IO_HANDLE_NONE) {
1704 ssize_t index = mInputs.indexOfKey(*input);
1705 if (index < 0) {
1706 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1707 status = BAD_VALUE;
1708 goto error;
1709 }
1710 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001711 RecordClientVector clients = inputDesc->getClientsForSession(session);
1712 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001713 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1714 status = BAD_VALUE;
1715 goto error;
1716 }
1717 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1718 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001719 // corresponds to a new client and is only permitted from the same UID.
1720 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07001721 if (clients.size() > 1) {
1722 for (const auto& client : clients) {
1723 // The client map is ordered by key values (portId) and portIds are allocated
1724 // incrementaly. So the first client in this list is the one opened by audio flinger
1725 // when the mmap stream is created and should be ignored as it does not correspond
1726 // to an actual client
1727 if (client == *clients.cbegin()) {
1728 continue;
1729 }
1730 if (uid != client->uid() && !client->isSilenced()) {
1731 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
1732 uid, client->portId(), client->uid());
1733 status = INVALID_OPERATION;
1734 goto error;
1735 }
Eric Laurent331679c2018-04-16 17:03:16 -07001736 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001737 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001738 *inputType = API_INPUT_LEGACY;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001739 device = inputDesc->mDevice;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001740
Eric Laurent8f42ea12018-08-08 09:08:25 -07001741 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001742 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001743 }
1744
1745 *input = AUDIO_IO_HANDLE_NONE;
1746 *inputType = API_INPUT_INVALID;
1747
Eric Laurentad2e7b92017-09-14 20:06:42 -07001748 halInputSource = inputSource;
1749
Eric Laurentc447ded2015-01-06 08:47:05 -08001750 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001751 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001752 status = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
1753 if (status != NO_ERROR) {
1754 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001755 }
1756 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001757 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1758 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001759 } else {
Eric Laurent97ac8712018-07-27 18:59:02 -07001760 if (deviceDesc != 0) {
1761 device = deviceDesc->type();
1762 } else {
1763 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
1764 }
Eric Laurent275e8e92014-11-30 15:14:47 -08001765 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001766 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001767 status = BAD_VALUE;
1768 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001769 }
Eric Laurentc722f302014-12-10 11:21:49 -08001770 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001771 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001772 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1773 // there is an external policy, but this input is attached to a mix of recorders,
1774 // meaning it receives audio injected into the framework, so the recorder doesn't
1775 // know about it and is therefore considered "legacy"
1776 *inputType = API_INPUT_LEGACY;
1777 } else {
1778 // recording a mix of players defined by an external policy, we're rerouting for
1779 // an external policy
1780 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1781 }
Eric Laurentc722f302014-12-10 11:21:49 -08001782 } else if (audio_is_remote_submix_device(device)) {
1783 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001784 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001785 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1786 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001787 } else {
1788 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001789 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001790
Eric Laurent599c7582015-12-07 18:05:55 -08001791 }
1792
Eric Laurent8f42ea12018-08-08 09:08:25 -07001793 *input = getInputForDevice(device, address, session, inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001794 config, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001795 policyMix);
1796 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001797 status = INVALID_OPERATION;
1798 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001799 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001800
Eric Laurent8f42ea12018-08-08 09:08:25 -07001801exit:
1802
Mikhail Naganov708e0382018-05-30 09:53:04 -07001803 inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -07001804 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
Eric Laurent8f42ea12018-08-08 09:08:25 -07001805 : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07001806
Eric Laurent8f42ea12018-08-08 09:08:25 -07001807 isSoundTrigger = inputSource == AUDIO_SOURCE_HOTWORD &&
1808 mSoundTriggerSessions.indexOfKey(session) > 0;
1809 *portId = AudioPort::getNextUniqueId();
1810
Eric Laurent8fc147b2018-07-22 19:13:55 -07001811 clientDesc = new RecordClientDescriptor(*portId, uid, session,
Eric Laurent8f42ea12018-08-08 09:08:25 -07001812 *attr, *config, requestedDeviceId,
1813 inputSource,flags, isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001814 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07001815 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001816
1817 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
1818 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001819
Eric Laurent599c7582015-12-07 18:05:55 -08001820 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001821
1822error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07001823 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001824}
1825
1826
1827audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1828 String8 address,
1829 audio_session_t session,
Eric Laurent599c7582015-12-07 18:05:55 -08001830 audio_source_t inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001831 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08001832 audio_input_flags_t flags,
1833 AudioMix *policyMix)
1834{
1835 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1836 audio_source_t halInputSource = inputSource;
1837 bool isSoundTrigger = false;
1838
1839 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1840 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1841 if (index >= 0) {
1842 input = mSoundTriggerSessions.valueFor(session);
1843 isSoundTrigger = true;
1844 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1845 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1846 } else {
1847 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001848 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001849 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08001850 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001851 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001852 }
1853
Andy Hungf129b032015-04-07 13:45:50 -07001854 // find a compatible input profile (not necessarily identical in parameters)
1855 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08001856 // sampling rate and flags may be updated by getInputProfile
1857 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
1858 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07001859 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08001860 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07001861 audio_input_flags_t profileFlags = flags;
1862 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07001863 profileFormat = config->format; // reset each time through loop, in case it is updated
Eric Laurent275e8e92014-11-30 15:14:47 -08001864 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001865 profileSamplingRate, profileFormat, profileChannelMask,
1866 profileFlags);
1867 if (profile != 0) {
1868 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001869 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1870 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001871 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1872 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1873 } else { // fail
Glenn Kastenfaa10a62017-05-25 15:52:05 -07001874 ALOGW("getInputForDevice() could not find profile for device 0x%X, "
Eric Laurentfe231122017-11-17 17:48:06 -08001875 "sampling rate %u, format %#x, channel mask 0x%X, flags %#x",
1876 device, config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001877 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001878 }
Eric Laurente552edb2014-03-10 17:42:56 -07001879 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001880 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08001881 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08001882 if (samplingRate == 0) {
1883 samplingRate = profileSamplingRate;
1884 }
Eric Laurente552edb2014-03-10 17:42:56 -07001885
Eric Laurent322b4d22015-04-03 15:57:54 -07001886 if (profile->getModuleHandle() == 0) {
1887 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001888 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001889 }
1890
Eric Laurent3974e3b2017-12-07 17:58:43 -08001891 if (!profile->canOpenNewIo()) {
Eric Laurentdf628922018-12-06 21:45:51 +00001892 return AUDIO_IO_HANDLE_NONE;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001893 }
1894
Eric Laurentfe231122017-11-17 17:48:06 -08001895 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001896
Eric Laurentfe231122017-11-17 17:48:06 -08001897 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
1898 lConfig.sample_rate = profileSamplingRate;
1899 lConfig.channel_mask = profileChannelMask;
1900 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07001901
Eric Laurent53b810e2017-12-10 17:25:10 -08001902 if (address == "") {
Mikhail Naganov708e0382018-05-30 09:53:04 -07001903 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -08001904 // the inputs vector must be of size >= 1, but we don't want to crash here
1905 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress : String8("");
1906 }
1907
Eric Laurentfe231122017-11-17 17:48:06 -08001908 status_t status = inputDesc->open(&lConfig, device, address,
1909 halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001910
1911 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001912 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08001913 (profileSamplingRate != lConfig.sample_rate) ||
1914 !audio_formats_match(profileFormat, lConfig.format) ||
1915 (profileChannelMask != lConfig.channel_mask)) {
1916 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001917 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08001918 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001919 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001920 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07001921 }
Eric Laurent599c7582015-12-07 18:05:55 -08001922 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001923 }
1924
Eric Laurentc722f302014-12-10 11:21:49 -08001925 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001926
Eric Laurent599c7582015-12-07 18:05:55 -08001927 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001928 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001929
Eric Laurent599c7582015-12-07 18:05:55 -08001930 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001931}
1932
Eric Laurentdf628922018-12-06 21:45:51 +00001933//static
1934bool AudioPolicyManager::isConcurrentSource(audio_source_t source)
Eric Laurentbb948092017-01-23 18:33:30 -08001935{
Eric Laurentdf628922018-12-06 21:45:51 +00001936 return (source == AUDIO_SOURCE_HOTWORD) ||
1937 (source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
1938 (source == AUDIO_SOURCE_FM_TUNER);
1939}
1940
1941// FIXME: remove when concurrent capture is ready. This is a hack to work around bug b/63083537.
1942bool AudioPolicyManager::soundTriggerSupportsConcurrentCapture() {
1943 if (!mHasComputedSoundTriggerSupportsConcurrentCapture) {
1944 bool soundTriggerSupportsConcurrentCapture = false;
1945 unsigned int numModules = 0;
1946 struct sound_trigger_module_descriptor* nModules = NULL;
1947
1948 status_t status = SoundTrigger::listModules(nModules, &numModules);
1949 if (status == NO_ERROR && numModules != 0) {
1950 nModules = (struct sound_trigger_module_descriptor*) calloc(
1951 numModules, sizeof(struct sound_trigger_module_descriptor));
1952 if (nModules == NULL) {
1953 // We failed to malloc the buffer, so just say no for now, and hope that we have more
1954 // ram the next time this function is called.
1955 ALOGE("Failed to allocate buffer for module descriptors");
1956 return false;
1957 }
1958
1959 status = SoundTrigger::listModules(nModules, &numModules);
1960 if (status == NO_ERROR) {
1961 soundTriggerSupportsConcurrentCapture = true;
1962 for (size_t i = 0; i < numModules; ++i) {
1963 soundTriggerSupportsConcurrentCapture &=
1964 nModules[i].properties.concurrent_capture;
1965 }
1966 }
1967 free(nModules);
1968 }
1969 mSoundTriggerSupportsConcurrentCapture = soundTriggerSupportsConcurrentCapture;
1970 mHasComputedSoundTriggerSupportsConcurrentCapture = true;
1971 }
1972 return mSoundTriggerSupportsConcurrentCapture;
1973}
1974
1975
1976status_t AudioPolicyManager::startInput(audio_port_handle_t portId,
1977 bool silenced,
1978 concurrency_type__mask_t *concurrency)
1979{
1980 *concurrency = API_INPUT_CONCURRENCY_NONE;
1981
Eric Laurent8fc147b2018-07-22 19:13:55 -07001982 ALOGV("%s portId %d", __FUNCTION__, portId);
1983
1984 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
1985 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07001986 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001987 return BAD_VALUE;
1988 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001989 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07001990 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001991 if (client->active()) {
1992 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
1993 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07001994 }
1995
Eric Laurent8f42ea12018-08-08 09:08:25 -07001996 audio_session_t session = client->session();
1997
Eric Laurentdf628922018-12-06 21:45:51 +00001998 ALOGV("%s input:%d, session:%d, silenced:%d, concurrency:%d)",
1999 __FUNCTION__, input, session, silenced, *concurrency);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002000
Eric Laurentdf628922018-12-06 21:45:51 +00002001 if (!is_virtual_input_device(inputDesc->mDevice)) {
2002 if (mCallTxPatch != 0 &&
2003 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
2004 ALOGW("startInput(%d) failed: call in progress", input);
2005 *concurrency |= API_INPUT_CONCURRENCY_CALL;
2006 return INVALID_OPERATION;
2007 }
Eric Laurent74708e72017-04-07 17:13:42 -07002008
Eric Laurentdf628922018-12-06 21:45:51 +00002009 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
2010
2011 // If a UID is idle and records silence and another not silenced recording starts
2012 // from another UID (idle or active) we stop the current idle UID recording in
2013 // favor of the new one - "There can be only one" TM
2014 if (!silenced) {
2015 for (const auto& activeDesc : activeInputs) {
2016 if ((activeDesc->getAudioPort()->getFlags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
2017 activeDesc->getId() == inputDesc->getId()) {
2018 continue;
2019 }
2020
2021 RecordClientVector activeClients = activeDesc->clientsList(true /*activeOnly*/);
2022 for (const auto& activeClient : activeClients) {
2023 if (activeClient->isSilenced()) {
2024 closeClient(activeClient->portId());
2025 ALOGV("%s client %d stopping silenced client %d", __FUNCTION__,
2026 portId, activeClient->portId());
2027 activeInputs = mInputs.getActiveInputs();
2028 }
2029 }
2030 }
2031 }
2032
2033 for (const auto& activeDesc : activeInputs) {
2034 if ((client->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
2035 activeDesc->getId() == inputDesc->getId()) {
2036 continue;
2037 }
2038
2039 audio_source_t activeSource = activeDesc->inputSource(true);
2040 if (client->source() == AUDIO_SOURCE_HOTWORD) {
2041 if (activeSource == AUDIO_SOURCE_HOTWORD) {
2042 if (activeDesc->hasPreemptedSession(session)) {
2043 ALOGW("%s input %d failed for HOTWORD: "
2044 "other input %d already started for HOTWORD", __FUNCTION__,
2045 input, activeDesc->mIoHandle);
2046 *concurrency |= API_INPUT_CONCURRENCY_HOTWORD;
2047 return INVALID_OPERATION;
2048 }
2049 } else {
2050 ALOGV("%s input %d failed for HOTWORD: other input %d already started",
2051 __FUNCTION__, input, activeDesc->mIoHandle);
2052 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
2053 return INVALID_OPERATION;
2054 }
2055 } else {
2056 if (activeSource != AUDIO_SOURCE_HOTWORD) {
2057 ALOGW("%s input %d failed: other input %d already started", __FUNCTION__,
2058 input, activeDesc->mIoHandle);
2059 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
2060 return INVALID_OPERATION;
2061 }
2062 }
2063 }
2064
2065 // We only need to check if the sound trigger session supports concurrent capture if the
2066 // input is also a sound trigger input. Otherwise, we should preempt any hotword stream
2067 // that's running.
2068 const bool allowConcurrentWithSoundTrigger =
2069 inputDesc->isSoundTrigger() ? soundTriggerSupportsConcurrentCapture() : false;
2070
2071 // if capture is allowed, preempt currently active HOTWORD captures
2072 for (const auto& activeDesc : activeInputs) {
2073 if (allowConcurrentWithSoundTrigger && activeDesc->isSoundTrigger()) {
2074 continue;
2075 }
2076 RecordClientVector activeHotwordClients =
2077 activeDesc->clientsList(true, AUDIO_SOURCE_HOTWORD);
2078 if (activeHotwordClients.size() > 0) {
2079 SortedVector<audio_session_t> sessions = activeDesc->getPreemptedSessions();
2080
2081 for (const auto& activeClient : activeHotwordClients) {
2082 *concurrency |= API_INPUT_CONCURRENCY_PREEMPT;
2083 sessions.add(activeClient->session());
2084 closeClient(activeClient->portId());
2085 ALOGV("%s input %d for HOTWORD preempting HOTWORD input %d", __FUNCTION__,
2086 input, activeDesc->mIoHandle);
2087 }
2088
2089 inputDesc->setPreemptedSessions(sessions);
2090 }
2091 }
Eric Laurent74708e72017-04-07 17:13:42 -07002092 }
Eric Laurente552edb2014-03-10 17:42:56 -07002093
Eric Laurentdf628922018-12-06 21:45:51 +00002094 // Make sure we start with the correct silence state
2095 client->setSilenced(silenced);
2096
2097 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002098 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002099 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002100
Eric Laurent8f42ea12018-08-08 09:08:25 -07002101 // indicate active capture to sound trigger service if starting capture from a mic on
2102 // primary HW module
2103 audio_devices_t device = getNewInputDevice(inputDesc);
2104 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002105
Eric Laurentdf628922018-12-06 21:45:51 +00002106 status_t status = inputDesc->start();
2107 if (status != NO_ERROR) {
2108 inputDesc->setClientActive(client, false);
2109 return status;
2110 }
2111
Eric Laurent8f42ea12018-08-08 09:08:25 -07002112 if (inputDesc->activeCount() == 1) {
2113 // if input maps to a dynamic policy with an activity listener, notify of state change
2114 if ((inputDesc->mPolicyMix != NULL)
2115 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2116 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2117 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002118 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002119
Eric Laurent8f42ea12018-08-08 09:08:25 -07002120 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2121 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2122 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
2123 SoundTrigger::setCaptureState(true);
2124 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002125
Eric Laurent8f42ea12018-08-08 09:08:25 -07002126 // automatically enable the remote submix output when input is started if not
2127 // used by a policy mix of type MIX_TYPE_RECORDERS
2128 // For remote submix (a virtual device), we open only one input per capture request.
2129 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2130 String8 address = String8("");
2131 if (inputDesc->mPolicyMix == NULL) {
2132 address = String8("0");
2133 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2134 address = inputDesc->mPolicyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002135 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002136 if (address != "") {
2137 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2138 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2139 address, "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08002140 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002141 }
Eric Laurente552edb2014-03-10 17:42:56 -07002142 }
2143
Eric Laurent8f42ea12018-08-08 09:08:25 -07002144 ALOGV("%s input %d source = %d exit", __FUNCTION__, input, client->source());
Eric Laurente552edb2014-03-10 17:42:56 -07002145
Eric Laurente552edb2014-03-10 17:42:56 -07002146 return NO_ERROR;
2147}
2148
Eric Laurent8fc147b2018-07-22 19:13:55 -07002149status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002150{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002151 ALOGV("%s portId %d", __FUNCTION__, portId);
2152
2153 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2154 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002155 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002156 return BAD_VALUE;
2157 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002158 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002159 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002160 if (!client->active()) {
2161 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002162 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002163 }
2164
Eric Laurent8f42ea12018-08-08 09:08:25 -07002165 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002166
Eric Laurent8f42ea12018-08-08 09:08:25 -07002167 inputDesc->stop();
2168 if (inputDesc->isActive()) {
2169 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2170 } else {
2171 // if input maps to a dynamic policy with an activity listener, notify of state change
2172 if ((inputDesc->mPolicyMix != NULL)
2173 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2174 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2175 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002176 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002177
2178 // automatically disable the remote submix output when input is stopped if not
2179 // used by a policy mix of type MIX_TYPE_RECORDERS
2180 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2181 String8 address = String8("");
2182 if (inputDesc->mPolicyMix == NULL) {
2183 address = String8("0");
2184 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2185 address = inputDesc->mPolicyMix->mDeviceAddress;
2186 }
2187 if (address != "") {
2188 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2189 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2190 address, "remote-submix");
2191 }
2192 }
2193
2194 audio_devices_t device = inputDesc->mDevice;
2195 resetInputDevice(input);
2196
2197 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2198 // primary HW module
2199 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2200 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2201 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
2202 SoundTrigger::setCaptureState(false);
2203 }
2204 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002205 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002206 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002207}
2208
Eric Laurent8fc147b2018-07-22 19:13:55 -07002209void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002210{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002211 ALOGV("%s portId %d", __FUNCTION__, portId);
2212
2213 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2214 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002215 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002216 return;
2217 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002218 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002219 audio_io_handle_t input = inputDesc->mIoHandle;
2220
Eric Laurent8f42ea12018-08-08 09:08:25 -07002221 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002222
Andy Hung39efb7a2018-09-26 15:39:28 -07002223 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002224
Andy Hung39efb7a2018-09-26 15:39:28 -07002225 if (inputDesc->getClientCount() > 0) {
2226 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002227 return;
2228 }
2229
Eric Laurent05b90f82014-08-27 15:32:29 -07002230 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002231 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002232 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002233}
2234
Eric Laurent8f42ea12018-08-08 09:08:25 -07002235void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002236{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002237 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002238
2239 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002240 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002241 }
2242}
2243
Eric Laurent8f42ea12018-08-08 09:08:25 -07002244void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2245{
2246 stopInput(portId);
2247 releaseInput(portId);
2248}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002249
Eric Laurentd4692962014-05-05 18:13:44 -07002250void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002251 bool patchRemoved = false;
2252
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002253 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002254 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002255 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002256 if (patch_index >= 0) {
2257 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002258 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002259 mAudioPatches.removeItemsAt(patch_index);
2260 patchRemoved = true;
2261 }
Eric Laurentfe231122017-11-17 17:48:06 -08002262 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002263 }
2264 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002265 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002266 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002267
2268 if (patchRemoved) {
2269 mpClientInterface->onAudioPatchListUpdate();
2270 }
Eric Laurentd4692962014-05-05 18:13:44 -07002271}
2272
Eric Laurente0720872014-03-11 09:30:41 -07002273void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002274 int indexMin,
2275 int indexMax)
2276{
2277 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002278 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002279
2280 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002281 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2282 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002283 continue;
2284 }
2285 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002286 }
Eric Laurente552edb2014-03-10 17:42:56 -07002287}
2288
Eric Laurente0720872014-03-11 09:30:41 -07002289status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002290 int index,
2291 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002292{
2293
Nadav Bar7c605f62017-12-25 00:01:52 +02002294 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2295 // app that has MODIFY_PHONE_STATE permission.
2296 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
2297 !(stream == AUDIO_STREAM_VOICE_CALL && index == 0)) ||
François Gaffied1ab2bd2015-12-02 18:20:06 +01002298 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002299 return BAD_VALUE;
2300 }
2301 if (!audio_is_output_device(device)) {
2302 return BAD_VALUE;
2303 }
2304
2305 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002306 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002307
Eric Laurent1fd372e2016-04-06 14:23:53 -07002308 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002309 stream, device, index);
2310
Eric Laurent28d09f02016-03-08 10:43:05 -08002311 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002312 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2313 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002314 continue;
2315 }
2316 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2317 }
Eric Laurente552edb2014-03-10 17:42:56 -07002318
Eric Laurent1fd372e2016-04-06 14:23:53 -07002319 // update volume on all outputs and streams matching the following:
2320 // - The requested stream (or a stream matching for volume control) is active on the output
2321 // - The device (or devices) selected by the strategy corresponding to this stream includes
2322 // the requested device
2323 // - For non default requested device, currently selected device on the output is either the
2324 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002325 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2326 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002327 status_t status = NO_ERROR;
2328 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002329 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2330 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08002331 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
Eric Laurent3839bc02018-07-10 18:33:34 -07002332 if (!(streamsMatchForvolume(stream, (audio_stream_type_t)curStream))) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002333 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002334 }
Eric Laurentdcd4ab12018-06-29 17:45:13 -07002335 if (!(desc->isStreamActive((audio_stream_type_t)curStream) || isInCall())) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002336 continue;
2337 }
Eric Laurent794fde22016-03-11 09:50:45 -08002338 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002339 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2340 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002341 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2342 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002343 continue;
2344 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002345 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002346 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002347 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07002348 applyVolume = (curDevice & curStreamDevice) != 0;
2349 } else {
2350 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002351 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002352 }
Eric Laurent3839bc02018-07-10 18:33:34 -07002353 // rescale index before applying to curStream as ranges may be different for
2354 // stream and curStream
2355 int idx = rescaleVolumeIndex(index, stream, (audio_stream_type_t)curStream);
Eric Laurente76f29c2016-09-14 17:17:53 -07002356 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002357 //FIXME: workaround for truncated touch sounds
2358 // delayed volume change for system stream to be removed when the problem is
2359 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002360 status_t volStatus =
Eric Laurent3839bc02018-07-10 18:33:34 -07002361 checkAndSetVolume((audio_stream_type_t)curStream, idx, desc, curDevice,
Eric Laurentdc462862016-07-19 12:29:53 -07002362 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002363 if (volStatus != NO_ERROR) {
2364 status = volStatus;
2365 }
2366 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002367 }
Eric Laurente552edb2014-03-10 17:42:56 -07002368 }
2369 return status;
2370}
2371
Eric Laurente0720872014-03-11 09:30:41 -07002372status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002373 int *index,
2374 audio_devices_t device)
2375{
2376 if (index == NULL) {
2377 return BAD_VALUE;
2378 }
2379 if (!audio_is_output_device(device)) {
2380 return BAD_VALUE;
2381 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002382 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002383 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002384 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002385 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2386 }
François Gaffiedfd74092015-03-19 12:10:59 +01002387 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002388
François Gaffied1ab2bd2015-12-02 18:20:06 +01002389 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002390 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2391 return NO_ERROR;
2392}
2393
Eric Laurent36829f92017-04-07 19:04:42 -07002394audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002395{
2396 // select one output among several suitable for global effects.
2397 // The priority is as follows:
2398 // 1: An offloaded output. If the effect ends up not being offloadable,
2399 // AudioFlinger will invalidate the track and the offloaded output
2400 // will be closed causing the effect to be moved to a PCM output.
2401 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002402 // 3: The primary output
2403 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002404
Eric Laurent3b73df72014-03-11 09:06:29 -07002405 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002406 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent36829f92017-04-07 19:04:42 -07002407 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002408
Eric Laurent36829f92017-04-07 19:04:42 -07002409 if (outputs.size() == 0) {
2410 return AUDIO_IO_HANDLE_NONE;
2411 }
Eric Laurente552edb2014-03-10 17:42:56 -07002412
Eric Laurent36829f92017-04-07 19:04:42 -07002413 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2414 bool activeOnly = true;
2415
2416 while (output == AUDIO_IO_HANDLE_NONE) {
2417 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2418 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2419 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2420
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002421 for (audio_io_handle_t output : outputs) {
2422 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002423 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2424 continue;
2425 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002426 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2427 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002428 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002429 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002430 }
2431 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002432 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002433 }
2434 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002435 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002436 }
2437 }
2438 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2439 output = outputOffloaded;
2440 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2441 output = outputDeepBuffer;
2442 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2443 output = outputPrimary;
2444 } else {
2445 output = outputs[0];
2446 }
2447 activeOnly = false;
2448 }
2449
2450 if (output != mMusicEffectOutput) {
2451 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2452 mMusicEffectOutput = output;
2453 }
2454
2455 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002456 return output;
2457}
2458
Eric Laurent36829f92017-04-07 19:04:42 -07002459audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2460{
2461 return selectOutputForMusicEffects();
2462}
2463
Eric Laurente0720872014-03-11 09:30:41 -07002464status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002465 audio_io_handle_t io,
2466 uint32_t strategy,
2467 int session,
2468 int id)
2469{
2470 ssize_t index = mOutputs.indexOfKey(io);
2471 if (index < 0) {
2472 index = mInputs.indexOfKey(io);
2473 if (index < 0) {
2474 ALOGW("registerEffect() unknown io %d", io);
2475 return INVALID_OPERATION;
2476 }
2477 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002478 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002479}
2480
Eric Laurentc75307b2015-03-17 15:29:32 -07002481bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2482{
Eric Laurent28d09f02016-03-08 10:43:05 -08002483 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002484 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2485 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002486 continue;
2487 }
2488 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2489 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002490 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002491}
2492
2493bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2494{
2495 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2496}
2497
Eric Laurente0720872014-03-11 09:30:41 -07002498bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002499{
2500 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002501 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002502 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002503 return true;
2504 }
2505 }
2506 return false;
2507}
2508
Eric Laurent275e8e92014-11-30 15:14:47 -08002509// Register a list of custom mixes with their attributes and format.
2510// When a mix is registered, corresponding input and output profiles are
2511// added to the remote submix hw module. The profile contains only the
2512// parameters (sampling rate, format...) specified by the mix.
2513// The corresponding input remote submix device is also connected.
2514//
2515// When a remote submix device is connected, the address is checked to select the
2516// appropriate profile and the corresponding input or output stream is opened.
2517//
2518// When capture starts, getInputForAttr() will:
2519// - 1 look for a mix matching the address passed in attribtutes tags if any
2520// - 2 if none found, getDeviceForInputSource() will:
2521// - 2.1 look for a mix matching the attributes source
2522// - 2.2 if none found, default to device selection by policy rules
2523// At this time, the corresponding output remote submix device is also connected
2524// and active playback use cases can be transferred to this mix if needed when reconnecting
2525// after AudioTracks are invalidated
2526//
2527// When playback starts, getOutputForAttr() will:
2528// - 1 look for a mix matching the address passed in attribtutes tags if any
2529// - 2 if none found, look for a mix matching the attributes usage
2530// - 3 if none found, default to device and output selection by policy rules.
2531
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002532status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002533{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002534 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2535 status_t res = NO_ERROR;
2536
2537 sp<HwModule> rSubmixModule;
2538 // examine each mix's route type
2539 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002540 AudioMix mix = mixes[i];
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002541 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
Eric Laurent97ac8712018-07-27 18:59:02 -07002542 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002543 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002544 break;
2545 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002546 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002547 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002548 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002549 rSubmixModule = mHwModules.getModuleFromName(
2550 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2551 if (rSubmixModule == 0) {
2552 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2553 i);
2554 res = INVALID_OPERATION;
2555 break;
2556 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002557 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002558
Eric Laurent97ac8712018-07-27 18:59:02 -07002559 String8 address = mix.mDeviceAddress;
2560 if (mix.mMixType == MIX_TYPE_PLAYERS) {
2561 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2562 } else {
2563 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
2564 }
François Gaffie036e1e92015-03-19 10:16:24 +01002565
Eric Laurent97ac8712018-07-27 18:59:02 -07002566 if (mPolicyMixes.registerMix(address, mix, 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002567 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002568 res = INVALID_OPERATION;
2569 break;
2570 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002571 audio_config_t outputConfig = mix.mFormat;
2572 audio_config_t inputConfig = mix.mFormat;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002573 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2574 // stereo and let audio flinger do the channel conversion if needed.
2575 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2576 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2577 rSubmixModule->addOutputProfile(address, &outputConfig,
2578 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2579 rSubmixModule->addInputProfile(address, &inputConfig,
2580 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002581
Eric Laurent97ac8712018-07-27 18:59:02 -07002582 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002583 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2584 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2585 address.string(), "remote-submix");
2586 } else {
2587 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2588 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2589 address.string(), "remote-submix");
2590 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002591 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2592 String8 address = mix.mDeviceAddress;
2593 audio_devices_t device = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002594 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2595 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002596
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002597 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002598 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2599 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2600 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2601 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2602 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2603 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002604 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2605 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002606 if (mPolicyMixes.registerMix(address, mix, desc) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002607 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002608 } else {
2609 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002610 }
2611 break;
2612 }
2613 }
2614
2615 if (res != NO_ERROR) {
2616 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002617 i, device, address.string());
2618 res = INVALID_OPERATION;
2619 break;
2620 } else if (!foundOutput) {
2621 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2622 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002623 res = INVALID_OPERATION;
2624 break;
2625 }
Eric Laurentc722f302014-12-10 11:21:49 -08002626 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002627 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002628 if (res != NO_ERROR) {
2629 unregisterPolicyMixes(mixes);
2630 }
2631 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002632}
2633
2634status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2635{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002636 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002637 status_t res = NO_ERROR;
2638 sp<HwModule> rSubmixModule;
2639 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002640 for (const auto& mix : mixes) {
2641 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002642
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002643 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002644 rSubmixModule = mHwModules.getModuleFromName(
2645 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2646 if (rSubmixModule == 0) {
2647 res = INVALID_OPERATION;
2648 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002649 }
2650 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002651
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002652 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002653
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002654 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2655 res = INVALID_OPERATION;
2656 continue;
2657 }
2658
2659 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2660 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2661 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2662 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2663 address.string(), "remote-submix");
2664 }
2665 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2666 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2667 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2668 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2669 address.string(), "remote-submix");
2670 }
2671 rSubmixModule->removeOutputProfile(address);
2672 rSubmixModule->removeInputProfile(address);
2673
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002674 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2675 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002676 res = INVALID_OPERATION;
2677 continue;
2678 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002679 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002680 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002681 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002682}
2683
Mikhail Naganov100f0122018-11-29 11:22:16 -08002684void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
2685{
2686 size_t i = 0;
2687 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
2688 for (const auto& fmt : mManualSurroundFormats) {
2689 if (i++ != 0) dst->append(", ");
2690 std::string sfmt;
2691 FormatConverter::toString(fmt, sfmt);
2692 dst->append(sfmt.size() >= audioFormatPrefixLen ?
2693 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
2694 }
2695}
2696
Andy Hungc29d82b2018-10-05 12:23:17 -07002697void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07002698{
Andy Hungc29d82b2018-10-05 12:23:17 -07002699 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
2700 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07002701 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002702 std::string stateLiteral;
2703 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07002704 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002705 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
2706 "communications", "media", "record", "dock", "system",
2707 "HDMI system audio", "encoded surround output", "vibrate ringing" };
2708 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
2709 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08002710 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
2711 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
2712 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
2713 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
2714 dst->append(" (MANUAL: ");
2715 dumpManualSurroundFormats(dst);
2716 dst->append(")");
2717 }
2718 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002719 }
Andy Hungc29d82b2018-10-05 12:23:17 -07002720 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
2721 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
2722 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
2723 mAvailableOutputDevices.dump(dst, String8("Available output"));
2724 mAvailableInputDevices.dump(dst, String8("Available input"));
2725 mHwModulesAll.dump(dst);
2726 mOutputs.dump(dst);
2727 mInputs.dump(dst);
2728 mVolumeCurves->dump(dst);
2729 mEffects.dump(dst);
2730 mAudioPatches.dump(dst);
2731 mPolicyMixes.dump(dst);
2732 mAudioSources.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07002733}
2734
2735status_t AudioPolicyManager::dump(int fd)
2736{
2737 String8 result;
2738 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07002739 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002740 return NO_ERROR;
2741}
2742
2743// This function checks for the parameters which can be offloaded.
2744// This can be enhanced depending on the capability of the DSP and policy
2745// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002746bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002747{
2748 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002749 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002750 offloadInfo.sample_rate, offloadInfo.channel_mask,
2751 offloadInfo.format,
2752 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2753 offloadInfo.has_video);
2754
Andy Hung2ddee192015-12-18 17:34:44 -08002755 if (mMasterMono) {
2756 return false; // no offloading if mono is set.
2757 }
2758
Eric Laurente552edb2014-03-10 17:42:56 -07002759 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07002760 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
2761 ALOGV("offload disabled by audio.offload.disable");
2762 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002763 }
2764
2765 // Check if stream type is music, then only allow offload as of now.
2766 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2767 {
2768 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2769 return false;
2770 }
2771
2772 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002773 const bool allowOffloadWithVideo =
2774 property_get_bool("audio.offload.video", false /* default_value */);
2775 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002776 ALOGV("isOffloadSupported: has_video == true, returning false");
2777 return false;
2778 }
2779
2780 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07002781 const int min_duration_secs = property_get_int32(
2782 "audio.offload.min.duration.secs", -1 /* default_value */);
2783 if (min_duration_secs >= 0) {
2784 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
2785 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%d)",
2786 min_duration_secs);
Eric Laurente552edb2014-03-10 17:42:56 -07002787 return false;
2788 }
2789 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2790 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2791 return false;
2792 }
2793
2794 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2795 // creating an offloaded track and tearing it down immediately after start when audioflinger
2796 // detects there is an active non offloadable effect.
2797 // FIXME: We should check the audio session here but we do not have it in this context.
2798 // This may prevent offloading in rare situations where effects are left active by apps
2799 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002800 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002801 return false;
2802 }
2803
2804 // See if there is a profile to support this.
2805 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002806 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002807 offloadInfo.sample_rate,
2808 offloadInfo.format,
2809 offloadInfo.channel_mask,
2810 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002811 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2812 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002813}
2814
Eric Laurent6a94d692014-05-20 11:18:06 -07002815status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2816 audio_port_type_t type,
2817 unsigned int *num_ports,
2818 struct audio_port *ports,
2819 unsigned int *generation)
2820{
2821 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2822 generation == NULL) {
2823 return BAD_VALUE;
2824 }
2825 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2826 if (ports == NULL) {
2827 *num_ports = 0;
2828 }
2829
2830 size_t portsWritten = 0;
2831 size_t portsMax = *num_ports;
2832 *num_ports = 0;
2833 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002834 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2835 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002836 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002837 for (const auto& dev : mAvailableOutputDevices) {
2838 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002839 continue;
2840 }
2841 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002842 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002843 }
2844 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002845 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002846 }
2847 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002848 for (const auto& dev : mAvailableInputDevices) {
2849 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002850 continue;
2851 }
2852 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002853 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002854 }
2855 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002856 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002857 }
2858 }
2859 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2860 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2861 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2862 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2863 }
2864 *num_ports += mInputs.size();
2865 }
2866 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002867 size_t numOutputs = 0;
2868 for (size_t i = 0; i < mOutputs.size(); i++) {
2869 if (!mOutputs[i]->isDuplicated()) {
2870 numOutputs++;
2871 if (portsWritten < portsMax) {
2872 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2873 }
2874 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002875 }
Eric Laurent84c70242014-06-23 08:46:27 -07002876 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002877 }
2878 }
2879 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002880 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002881 return NO_ERROR;
2882}
2883
Eric Laurent99fcae42018-05-17 16:59:18 -07002884status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07002885{
Eric Laurent99fcae42018-05-17 16:59:18 -07002886 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
2887 return BAD_VALUE;
2888 }
2889 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
2890 if (dev != 0) {
2891 dev->toAudioPort(port);
2892 return NO_ERROR;
2893 }
2894 dev = mAvailableInputDevices.getDeviceFromId(port->id);
2895 if (dev != 0) {
2896 dev->toAudioPort(port);
2897 return NO_ERROR;
2898 }
2899 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
2900 if (out != 0) {
2901 out->toAudioPort(port);
2902 return NO_ERROR;
2903 }
2904 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
2905 if (in != 0) {
2906 in->toAudioPort(port);
2907 return NO_ERROR;
2908 }
2909 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002910}
2911
Eric Laurent6a94d692014-05-20 11:18:06 -07002912status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2913 audio_patch_handle_t *handle,
2914 uid_t uid)
2915{
2916 ALOGV("createAudioPatch()");
2917
2918 if (handle == NULL || patch == NULL) {
2919 return BAD_VALUE;
2920 }
2921 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2922
Mikhail Naganovac9858b2018-06-15 13:12:37 -07002923 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07002924 return BAD_VALUE;
2925 }
2926 // only one source per audio patch supported for now
2927 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002928 return INVALID_OPERATION;
2929 }
Eric Laurent874c42872014-08-08 15:13:39 -07002930
2931 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002932 return INVALID_OPERATION;
2933 }
Eric Laurent874c42872014-08-08 15:13:39 -07002934 for (size_t i = 0; i < patch->num_sinks; i++) {
2935 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2936 return INVALID_OPERATION;
2937 }
2938 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002939
2940 sp<AudioPatch> patchDesc;
2941 ssize_t index = mAudioPatches.indexOfKey(*handle);
2942
Eric Laurent6a94d692014-05-20 11:18:06 -07002943 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2944 patch->sources[0].role,
2945 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002946#if LOG_NDEBUG == 0
2947 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002948 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002949 patch->sinks[i].role,
2950 patch->sinks[i].type);
2951 }
2952#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002953
2954 if (index >= 0) {
2955 patchDesc = mAudioPatches.valueAt(index);
2956 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2957 mUidCached, patchDesc->mUid, uid);
2958 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2959 return INVALID_OPERATION;
2960 }
2961 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002962 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002963 }
2964
2965 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002966 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002967 if (outputDesc == NULL) {
2968 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2969 return BAD_VALUE;
2970 }
Eric Laurent84c70242014-06-23 08:46:27 -07002971 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2972 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002973 if (patchDesc != 0) {
2974 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2975 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2976 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2977 return BAD_VALUE;
2978 }
2979 }
Eric Laurent874c42872014-08-08 15:13:39 -07002980 DeviceVector devices;
2981 for (size_t i = 0; i < patch->num_sinks; i++) {
2982 // Only support mix to devices connection
2983 // TODO add support for mix to mix connection
2984 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2985 ALOGV("createAudioPatch() source mix but sink is not a device");
2986 return INVALID_OPERATION;
2987 }
2988 sp<DeviceDescriptor> devDesc =
2989 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2990 if (devDesc == 0) {
2991 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2992 return BAD_VALUE;
2993 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002994
François Gaffie53615e22015-03-19 09:24:12 +01002995 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002996 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002997 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002998 NULL, // updatedSamplingRate
2999 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003000 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01003001 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003002 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01003003 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07003004 ALOGV("createAudioPatch() profile not supported for device %08x",
3005 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07003006 return INVALID_OPERATION;
3007 }
3008 devices.add(devDesc);
3009 }
3010 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003011 return INVALID_OPERATION;
3012 }
Eric Laurent874c42872014-08-08 15:13:39 -07003013
Eric Laurent6a94d692014-05-20 11:18:06 -07003014 // TODO: reconfigure output format and channels here
3015 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07003016 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07003017 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003018 index = mAudioPatches.indexOfKey(*handle);
3019 if (index >= 0) {
3020 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3021 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
3022 }
3023 patchDesc = mAudioPatches.valueAt(index);
3024 patchDesc->mUid = uid;
3025 ALOGV("createAudioPatch() success");
3026 } else {
3027 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
3028 return INVALID_OPERATION;
3029 }
3030 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3031 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3032 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003033 // only one sink supported when connecting an input device to a mix
3034 if (patch->num_sinks > 1) {
3035 return INVALID_OPERATION;
3036 }
François Gaffie53615e22015-03-19 09:24:12 +01003037 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003038 if (inputDesc == NULL) {
3039 return BAD_VALUE;
3040 }
3041 if (patchDesc != 0) {
3042 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3043 return BAD_VALUE;
3044 }
3045 }
3046 sp<DeviceDescriptor> devDesc =
3047 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
3048 if (devDesc == 0) {
3049 return BAD_VALUE;
3050 }
3051
François Gaffie53615e22015-03-19 09:24:12 +01003052 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08003053 devDesc->mAddress,
3054 patch->sinks[0].sample_rate,
3055 NULL, /*updatedSampleRate*/
3056 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003057 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003058 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003059 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003060 // FIXME for the parameter type,
3061 // and the NONE
3062 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003063 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003064 return INVALID_OPERATION;
3065 }
3066 // TODO: reconfigure output format and channels here
3067 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01003068 devDesc->type(), inputDesc->mIoHandle);
3069 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003070 index = mAudioPatches.indexOfKey(*handle);
3071 if (index >= 0) {
3072 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3073 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
3074 }
3075 patchDesc = mAudioPatches.valueAt(index);
3076 patchDesc->mUid = uid;
3077 ALOGV("createAudioPatch() success");
3078 } else {
3079 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
3080 return INVALID_OPERATION;
3081 }
3082 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3083 // device to device connection
3084 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003085 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003086 return BAD_VALUE;
3087 }
3088 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003089 sp<DeviceDescriptor> srcDeviceDesc =
3090 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07003091 if (srcDeviceDesc == 0) {
3092 return BAD_VALUE;
3093 }
Eric Laurent874c42872014-08-08 15:13:39 -07003094
Eric Laurent6a94d692014-05-20 11:18:06 -07003095 //update source and sink with our own data as the data passed in the patch may
3096 // be incomplete.
3097 struct audio_patch newPatch = *patch;
3098 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003099
Eric Laurent874c42872014-08-08 15:13:39 -07003100 for (size_t i = 0; i < patch->num_sinks; i++) {
3101 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3102 ALOGV("createAudioPatch() source device but one sink is not a device");
3103 return INVALID_OPERATION;
3104 }
3105
3106 sp<DeviceDescriptor> sinkDeviceDesc =
3107 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3108 if (sinkDeviceDesc == 0) {
3109 return BAD_VALUE;
3110 }
3111 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
3112
Eric Laurent3bcf8592015-04-03 12:13:24 -07003113 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003114 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003115 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08003116 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003117 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003118 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003119 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003120 return INVALID_OPERATION;
3121 }
Eric Laurent874c42872014-08-08 15:13:39 -07003122 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01003123 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003124 // if the sink device is reachable via an opened output stream, request to go via
3125 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07003126 audio_io_handle_t output = selectOutput(outputs,
3127 AUDIO_OUTPUT_FLAG_NONE,
3128 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07003129 if (output != AUDIO_IO_HANDLE_NONE) {
3130 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3131 if (outputDesc->isDuplicated()) {
3132 return INVALID_OPERATION;
3133 }
3134 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003135 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003136 newPatch.num_sources = 2;
3137 }
Eric Laurent83b88082014-06-20 18:31:16 -07003138 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003139 }
3140 // TODO: check from routing capabilities in config file and other conflicting patches
3141
Mikhail Naganovdc769682018-05-04 15:34:08 -07003142 status_t status = installPatch(__func__, index, handle, &newPatch, 0, uid, &patchDesc);
3143 if (status != NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003144 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3145 status);
3146 return INVALID_OPERATION;
3147 }
3148 } else {
3149 return BAD_VALUE;
3150 }
3151 } else {
3152 return BAD_VALUE;
3153 }
3154 return NO_ERROR;
3155}
3156
3157status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3158 uid_t uid)
3159{
3160 ALOGV("releaseAudioPatch() patch %d", handle);
3161
3162 ssize_t index = mAudioPatches.indexOfKey(handle);
3163
3164 if (index < 0) {
3165 return BAD_VALUE;
3166 }
3167 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3168 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3169 mUidCached, patchDesc->mUid, uid);
3170 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3171 return INVALID_OPERATION;
3172 }
3173
3174 struct audio_patch *patch = &patchDesc->mPatch;
3175 patchDesc->mUid = mUidCached;
3176 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003177 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003178 if (outputDesc == NULL) {
3179 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3180 return BAD_VALUE;
3181 }
3182
Eric Laurentc75307b2015-03-17 15:29:32 -07003183 setOutputDevice(outputDesc,
3184 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07003185 true,
3186 0,
3187 NULL);
3188 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3189 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003190 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003191 if (inputDesc == NULL) {
3192 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3193 return BAD_VALUE;
3194 }
3195 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003196 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003197 true,
3198 NULL);
3199 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003200 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3201 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3202 status, patchDesc->mAfPatchHandle);
3203 removeAudioPatch(patchDesc->mHandle);
3204 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003205 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003206 } else {
3207 return BAD_VALUE;
3208 }
3209 } else {
3210 return BAD_VALUE;
3211 }
3212 return NO_ERROR;
3213}
3214
3215status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3216 struct audio_patch *patches,
3217 unsigned int *generation)
3218{
François Gaffie53615e22015-03-19 09:24:12 +01003219 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003220 return BAD_VALUE;
3221 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003222 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003223 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003224}
3225
Eric Laurente1715a42014-05-20 11:30:42 -07003226status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003227{
Eric Laurente1715a42014-05-20 11:30:42 -07003228 ALOGV("setAudioPortConfig()");
3229
3230 if (config == NULL) {
3231 return BAD_VALUE;
3232 }
3233 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3234 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003235 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3236 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003237 }
3238
Eric Laurenta121f902014-06-03 13:32:54 -07003239 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003240 if (config->type == AUDIO_PORT_TYPE_MIX) {
3241 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003242 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003243 if (outputDesc == NULL) {
3244 return BAD_VALUE;
3245 }
Eric Laurent84c70242014-06-23 08:46:27 -07003246 ALOG_ASSERT(!outputDesc->isDuplicated(),
3247 "setAudioPortConfig() called on duplicated output %d",
3248 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003249 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003250 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003251 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003252 if (inputDesc == NULL) {
3253 return BAD_VALUE;
3254 }
Eric Laurenta121f902014-06-03 13:32:54 -07003255 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003256 } else {
3257 return BAD_VALUE;
3258 }
3259 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3260 sp<DeviceDescriptor> deviceDesc;
3261 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3262 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3263 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3264 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3265 } else {
3266 return BAD_VALUE;
3267 }
3268 if (deviceDesc == NULL) {
3269 return BAD_VALUE;
3270 }
Eric Laurenta121f902014-06-03 13:32:54 -07003271 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003272 } else {
3273 return BAD_VALUE;
3274 }
3275
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003276 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003277 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3278 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003279 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003280 audioPortConfig->toAudioPortConfig(&newConfig, config);
3281 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003282 }
Eric Laurenta121f902014-06-03 13:32:54 -07003283 if (status != NO_ERROR) {
3284 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003285 }
Eric Laurente1715a42014-05-20 11:30:42 -07003286
3287 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003288}
3289
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003290void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3291{
Eric Laurentd60560a2015-04-10 11:31:20 -07003292 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003293 clearAudioPatches(uid);
3294 clearSessionRoutes(uid);
3295}
3296
Eric Laurent6a94d692014-05-20 11:18:06 -07003297void AudioPolicyManager::clearAudioPatches(uid_t uid)
3298{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003299 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003300 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3301 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003302 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003303 }
3304 }
3305}
3306
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003307void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3308 audio_io_handle_t ouptutToSkip)
3309{
3310 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3311 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3312 for (size_t j = 0; j < mOutputs.size(); j++) {
3313 if (mOutputs.keyAt(j) == ouptutToSkip) {
3314 continue;
3315 }
3316 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3317 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3318 continue;
3319 }
3320 // If the default device for this strategy is on another output mix,
3321 // invalidate all tracks in this strategy to force re connection.
3322 // Otherwise select new device on the output mix.
3323 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003324 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003325 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3326 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3327 }
3328 }
3329 } else {
3330 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3331 setOutputDevice(outputDesc, newDevice, false);
3332 }
3333 }
3334}
3335
3336void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3337{
3338 // remove output routes associated with this uid
3339 SortedVector<routing_strategy> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07003340 for (size_t i = 0; i < mOutputs.size(); i++) {
3341 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003342 for (const auto& client : outputDesc->getClientIterable()) {
3343 if (client->hasPreferredDevice() && client->uid() == uid) {
3344 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3345 affectedStrategies.add(getStrategy(client->stream()));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003346 }
3347 }
3348 }
3349 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003350 for (const auto& strategy : affectedStrategies) {
3351 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003352 }
3353
3354 // remove input routes associated with this uid
3355 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07003356 for (size_t i = 0; i < mInputs.size(); i++) {
3357 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003358 for (const auto& client : inputDesc->getClientIterable()) {
3359 if (client->hasPreferredDevice() && client->uid() == uid) {
3360 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3361 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003362 }
3363 }
3364 }
3365 // reroute inputs if necessary
3366 SortedVector<audio_io_handle_t> inputsToClose;
3367 for (size_t i = 0; i < mInputs.size(); i++) {
3368 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurentdf628922018-12-06 21:45:51 +00003369 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003370 inputsToClose.add(inputDesc->mIoHandle);
3371 }
3372 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003373 for (const auto& input : inputsToClose) {
3374 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003375 }
3376}
3377
Eric Laurentd60560a2015-04-10 11:31:20 -07003378void AudioPolicyManager::clearAudioSources(uid_t uid)
3379{
3380 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003381 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3382 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07003383 stopAudioSource(mAudioSources.keyAt(i));
3384 }
3385 }
3386}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003387
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003388status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3389 audio_io_handle_t *ioHandle,
3390 audio_devices_t *device)
3391{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003392 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3393 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003394 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003395
François Gaffiedf372692015-03-19 10:43:27 +01003396 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003397}
3398
Eric Laurentd60560a2015-04-10 11:31:20 -07003399status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003400 const audio_attributes_t *attributes,
3401 audio_port_handle_t *portId,
3402 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003403{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003404 ALOGV("%s", __FUNCTION__);
3405 *portId = AUDIO_PORT_HANDLE_NONE;
3406
3407 if (source == NULL || attributes == NULL || portId == NULL) {
3408 ALOGW("%s invalid argument: source %p attributes %p handle %p",
3409 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003410 return BAD_VALUE;
3411 }
3412
Eric Laurentd60560a2015-04-10 11:31:20 -07003413 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3414 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003415 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
3416 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003417 return INVALID_OPERATION;
3418 }
3419
3420 sp<DeviceDescriptor> srcDeviceDesc =
3421 mAvailableInputDevices.getDevice(source->ext.device.type,
3422 String8(source->ext.device.address));
3423 if (srcDeviceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003424 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003425 return BAD_VALUE;
3426 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003427
3428 *portId = AudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07003429
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003430 struct audio_patch dummyPatch = {};
Eric Laurentd60560a2015-04-10 11:31:20 -07003431 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003432
3433 sp<SourceClientDescriptor> sourceDesc =
3434 new SourceClientDescriptor(*portId, uid, *attributes, patchDesc, srcDeviceDesc,
Eric Laurent97ac8712018-07-27 18:59:02 -07003435 streamTypefromAttributesInt(attributes),
3436 getStrategyForAttr(attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07003437
3438 status_t status = connectAudioSource(sourceDesc);
3439 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003440 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003441 }
3442 return status;
3443}
3444
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003445status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003446{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003447 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003448
3449 // make sure we only have one patch per source.
3450 disconnectAudioSource(sourceDesc);
3451
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003452 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003453 routing_strategy strategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003454 audio_stream_type_t stream = sourceDesc->stream();
3455 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->srcDevice();
Eric Laurentd60560a2015-04-10 11:31:20 -07003456
3457 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3458 sp<DeviceDescriptor> sinkDeviceDesc =
3459 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3460
3461 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003462
3463 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3464 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003465 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003466 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3467 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3468 // create patch between src device and output device
3469 // create Hwoutput and add to mHwOutputs
3470 } else {
3471 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3472 audio_io_handle_t output =
3473 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3474 if (output == AUDIO_IO_HANDLE_NONE) {
3475 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3476 return INVALID_OPERATION;
3477 }
3478 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3479 if (outputDesc->isDuplicated()) {
3480 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3481 return INVALID_OPERATION;
3482 }
Eric Laurent733ce942017-12-07 12:18:25 -08003483 status_t status = outputDesc->start();
3484 if (status != NO_ERROR) {
3485 return status;
3486 }
3487
Eric Laurentd60560a2015-04-10 11:31:20 -07003488 // create a special patch with no sink and two sources:
3489 // - the second source indicates to PatchPanel through which output mix this patch should
3490 // be connected as well as the stream type for volume control
3491 // - the sink is defined by whatever output device is currently selected for the output
3492 // though which this patch is routed.
Mikhail Naganovdc769682018-05-04 15:34:08 -07003493 PatchBuilder patchBuilder;
3494 patchBuilder.addSource(srcDeviceDesc).addSource(outputDesc, { .stream = stream });
3495 status = mpClientInterface->createAudioPatch(patchBuilder.patch(),
Eric Laurentd60560a2015-04-10 11:31:20 -07003496 &afPatchHandle,
3497 0);
3498 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3499 status, afPatchHandle);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003500 sourceDesc->patchDesc()->mPatch = *patchBuilder.patch();
Eric Laurentd60560a2015-04-10 11:31:20 -07003501 if (status != NO_ERROR) {
3502 ALOGW("%s patch panel could not connect device patch, error %d",
3503 __FUNCTION__, status);
3504 return INVALID_OPERATION;
3505 }
3506 uint32_t delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07003507 status = startSource(outputDesc, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003508
3509 if (status != NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003510 mpClientInterface->releaseAudioPatch(sourceDesc->patchDesc()->mAfPatchHandle, 0);
Eric Laurentd60560a2015-04-10 11:31:20 -07003511 return status;
3512 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003513 sourceDesc->setSwOutput(outputDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003514 if (delayMs != 0) {
3515 usleep(delayMs * 1000);
3516 }
3517 }
3518
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003519 sourceDesc->patchDesc()->mAfPatchHandle = afPatchHandle;
3520 addAudioPatch(sourceDesc->patchDesc()->mHandle, sourceDesc->patchDesc());
Eric Laurentd60560a2015-04-10 11:31:20 -07003521
3522 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003523}
3524
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003525status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07003526{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003527 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
3528 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003529 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003530 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003531 return BAD_VALUE;
3532 }
3533 status_t status = disconnectAudioSource(sourceDesc);
3534
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003535 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003536 return status;
3537}
3538
Andy Hung2ddee192015-12-18 17:34:44 -08003539status_t AudioPolicyManager::setMasterMono(bool mono)
3540{
3541 if (mMasterMono == mono) {
3542 return NO_ERROR;
3543 }
3544 mMasterMono = mono;
3545 // if enabling mono we close all offloaded devices, which will invalidate the
3546 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3547 // for recreating the new AudioTrack as non-offloaded PCM.
3548 //
3549 // If disabling mono, we leave all tracks as is: we don't know which clients
3550 // and tracks are able to be recreated as offloaded. The next "song" should
3551 // play back offloaded.
3552 if (mMasterMono) {
3553 Vector<audio_io_handle_t> offloaded;
3554 for (size_t i = 0; i < mOutputs.size(); ++i) {
3555 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3556 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3557 offloaded.push(desc->mIoHandle);
3558 }
3559 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003560 for (const auto& handle : offloaded) {
3561 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003562 }
3563 }
3564 // update master mono for all remaining outputs
3565 for (size_t i = 0; i < mOutputs.size(); ++i) {
3566 updateMono(mOutputs.keyAt(i));
3567 }
3568 return NO_ERROR;
3569}
3570
3571status_t AudioPolicyManager::getMasterMono(bool *mono)
3572{
3573 *mono = mMasterMono;
3574 return NO_ERROR;
3575}
3576
Eric Laurentac9cef52017-06-09 15:46:26 -07003577float AudioPolicyManager::getStreamVolumeDB(
3578 audio_stream_type_t stream, int index, audio_devices_t device)
3579{
3580 return computeVolume(stream, index, device);
3581}
3582
jiabin81772902018-04-02 17:52:27 -07003583status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3584 audio_format_t *surroundFormats,
3585 bool *surroundFormatsEnabled,
3586 bool reported)
3587{
3588 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3589 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3590 return BAD_VALUE;
3591 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003592 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p reported %d",
3593 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled, reported);
jiabin81772902018-04-02 17:52:27 -07003594
3595 size_t formatsWritten = 0;
3596 size_t formatsMax = *numSurroundFormats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08003597 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
jiabin81772902018-04-02 17:52:27 -07003598 if (reported) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003599 // Return formats from all device profiles that have already been resolved by
Mikhail Naganov2563f232018-09-27 14:48:01 -07003600 // checkOutputsForDevice().
Mikhail Naganov100f0122018-11-29 11:22:16 -08003601 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
3602 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
3603 FormatVector supportedFormats =
3604 device->getAudioPort()->getAudioProfiles().getSupportedFormats();
3605 for (size_t j = 0; j < supportedFormats.size(); j++) {
3606 if (mConfig.getSurroundFormats().count(supportedFormats[j]) != 0) {
3607 formats.insert(supportedFormats[j]);
3608 } else {
3609 for (const auto& pair : mConfig.getSurroundFormats()) {
3610 if (pair.second.count(supportedFormats[j]) != 0) {
3611 formats.insert(pair.first);
3612 break;
3613 }
3614 }
3615 }
3616 }
jiabin81772902018-04-02 17:52:27 -07003617 }
3618 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003619 for (const auto& pair : mConfig.getSurroundFormats()) {
3620 formats.insert(pair.first);
jiabin81772902018-04-02 17:52:27 -07003621 }
3622 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003623 *numSurroundFormats = formats.size();
3624 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3625 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov2563f232018-09-27 14:48:01 -07003626 for (const auto& format: formats) {
jiabin81772902018-04-02 17:52:27 -07003627 if (formatsWritten < formatsMax) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003628 surroundFormats[formatsWritten] = format;
Mikhail Naganov100f0122018-11-29 11:22:16 -08003629 bool formatEnabled = true;
3630 switch (forceUse) {
3631 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
3632 formatEnabled = mManualSurroundFormats.count(format) != 0;
3633 break;
3634 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
3635 formatEnabled = false;
3636 break;
3637 default: // AUTO or ALWAYS => true
3638 break;
jiabin81772902018-04-02 17:52:27 -07003639 }
3640 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3641 }
jiabin81772902018-04-02 17:52:27 -07003642 }
3643 return NO_ERROR;
3644}
3645
3646status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3647{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003648 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003649 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
3650 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003651 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07003652 return BAD_VALUE;
3653 }
3654
Mikhail Naganov100f0122018-11-29 11:22:16 -08003655 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
3656 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003657 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07003658 return INVALID_OPERATION;
3659 }
3660
Mikhail Naganov100f0122018-11-29 11:22:16 -08003661 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07003662 return NO_ERROR;
3663 }
3664
Mikhail Naganov100f0122018-11-29 11:22:16 -08003665 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07003666 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003667 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003668 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003669 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07003670 }
3671 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003672 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003673 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003674 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07003675 }
3676 }
3677
3678 sp<SwAudioOutputDescriptor> outputDesc;
3679 bool profileUpdated = false;
Mikhail Naganov708e0382018-05-30 09:53:04 -07003680 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003681 AUDIO_DEVICE_OUT_HDMI);
3682 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3683 // Simulate reconnection to update enabled surround sound formats.
3684 String8 address = hdmiOutputDevices[i]->mAddress;
3685 String8 name = hdmiOutputDevices[i]->getName();
3686 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3687 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3688 address.c_str(),
3689 name.c_str());
3690 if (status != NO_ERROR) {
3691 continue;
3692 }
3693 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3694 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3695 address.c_str(),
3696 name.c_str());
3697 profileUpdated |= (status == NO_ERROR);
3698 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003699 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
Mikhail Naganov708e0382018-05-30 09:53:04 -07003700 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003701 AUDIO_DEVICE_IN_HDMI);
3702 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3703 // Simulate reconnection to update enabled surround sound formats.
3704 String8 address = hdmiInputDevices[i]->mAddress;
3705 String8 name = hdmiInputDevices[i]->getName();
3706 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3707 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3708 address.c_str(),
3709 name.c_str());
3710 if (status != NO_ERROR) {
3711 continue;
3712 }
3713 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3714 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3715 address.c_str(),
3716 name.c_str());
3717 profileUpdated |= (status == NO_ERROR);
3718 }
3719
jiabin81772902018-04-02 17:52:27 -07003720 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003721 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08003722 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07003723 }
3724
3725 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3726}
3727
Eric Laurentf32108e2018-10-04 17:22:04 -07003728void AudioPolicyManager::setAppState(uid_t uid, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003729{
Eric Laurentf32108e2018-10-04 17:22:04 -07003730 Vector<sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
Eric Laurentdf628922018-12-06 21:45:51 +00003731 bool silenced = state == APP_STATE_IDLE;
Eric Laurentf32108e2018-10-04 17:22:04 -07003732
Eric Laurentdf628922018-12-06 21:45:51 +00003733 ALOGV("AudioPolicyManager:setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003734
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003735 for (size_t i = 0; i < activeInputs.size(); i++) {
3736 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
Eric Laurent8f42ea12018-08-08 09:08:25 -07003737 RecordClientVector clients = activeDesc->clientsList(true /*activeOnly*/);
3738 for (const auto& client : clients) {
3739 if (uid == client->uid()) {
Eric Laurentdf628922018-12-06 21:45:51 +00003740 client->setSilenced(silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003741 }
3742 }
3743 }
3744}
3745
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003746status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003747{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003748 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003749
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003750 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003751 if (patchDesc == 0) {
3752 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003753 sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003754 return BAD_VALUE;
3755 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003756 removeAudioPatch(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003757
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003758 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003759 if (swOutputDesc != 0) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003760 status_t status = stopSource(swOutputDesc, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08003761 if (status == NO_ERROR) {
3762 swOutputDesc->stop();
3763 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003764 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3765 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003766 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003767 if (hwOutputDesc != 0) {
3768 // release patch between src device and output device
3769 // close Hwoutput and remove from mHwOutputs
3770 } else {
3771 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3772 }
3773 }
3774 return NO_ERROR;
3775}
3776
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003777sp<SourceClientDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
Eric Laurentd60560a2015-04-10 11:31:20 -07003778 audio_io_handle_t output, routing_strategy strategy)
3779{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003780 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07003781 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003782 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3783 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003784 routing_strategy sourceStrategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003785 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003786 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3787 source = sourceDesc;
3788 break;
3789 }
3790 }
3791 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003792}
3793
Eric Laurente552edb2014-03-10 17:42:56 -07003794// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003795// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003796// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003797uint32_t AudioPolicyManager::nextAudioPortGeneration()
3798{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003799 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003800}
3801
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003802// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3803static const char *kConfigLocationList[] =
3804 {"/odm/etc", "/vendor/etc", "/system/etc"};
3805static const int kConfigLocationListSize =
3806 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3807
3808static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3809 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07003810 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003811 status_t ret;
3812
Petri Gyntherf497f292018-04-17 18:46:10 -07003813 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
3814 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
3815 // A2DP offload supported but disabled: try to use special XML file
3816 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
3817 }
3818 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3819
3820 for (const char* fileName : fileNames) {
3821 for (int i = 0; i < kConfigLocationListSize; i++) {
Petri Gyntherf497f292018-04-17 18:46:10 -07003822 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
3823 "%s/%s", kConfigLocationList[i], fileName);
Mikhail Naganova289aea2018-09-17 15:26:23 -07003824 ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile, &config);
Petri Gyntherf497f292018-04-17 18:46:10 -07003825 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003826 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07003827 return ret;
3828 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003829 }
3830 }
3831 return ret;
3832}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003833
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003834AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
3835 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07003836 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07003837 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003838 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07003839 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003840 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003841 mVolumeCurves(new VolumeCurvesCollection()),
3842 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08003843 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003844 mAudioPortGeneration(1),
3845 mBeaconMuteRefCount(0),
3846 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003847 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003848 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003849 mMasterMono(false),
Eric Laurentdf628922018-12-06 21:45:51 +00003850 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE),
3851 mHasComputedSoundTriggerSupportsConcurrentCapture(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003852{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003853}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003854
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003855AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
3856 : AudioPolicyManager(clientInterface, false /*forTesting*/)
3857{
3858 loadConfig();
3859 initialize();
3860}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003861
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07003862// This check is to catch any legacy platform updating to Q without having
3863// switched to XML since its deprecation on O.
3864// TODO: after Q release, remove this check and flag as XML is now the only
3865// option and all legacy platform should have transitioned to XML.
3866#ifndef USE_XML_AUDIO_POLICY_CONF
3867#error Audio policy no longer supports legacy .conf configuration format
François Gaffied1ab2bd2015-12-02 18:20:06 +01003868#endif
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07003869
3870void AudioPolicyManager::loadConfig() {
3871 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003872 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003873 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01003874 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003875}
3876
3877status_t AudioPolicyManager::initialize() {
3878 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01003879
3880 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003881 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3882 if (!engineInstance) {
3883 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003884 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003885 }
3886 // Retrieve the Policy Manager Interface
3887 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3888 if (mEngine == NULL) {
3889 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003890 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003891 }
3892 mEngine->setObserver(this);
3893 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003894 if (status != NO_ERROR) {
3895 LOG_FATAL("Policy engine not initialized(err=%d)", status);
3896 return status;
3897 }
François Gaffie2110e042015-03-24 08:41:51 +01003898
Eric Laurent3a4311c2014-03-17 12:00:47 -07003899 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003900 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003901 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3902 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Mikhail Naganovd4120142017-12-06 15:49:22 -08003903 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003904 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08003905 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
3906 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003907 continue;
3908 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08003909 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07003910 // open all output streams needed to access attached devices
3911 // except for direct output streams that are only opened when they are actually
3912 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003913 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003914 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003915 if (!outProfile->canOpenNewIo()) {
3916 ALOGE("Invalid Output profile max open count %u for profile %s",
3917 outProfile->maxOpenCount, outProfile->getTagName().c_str());
3918 continue;
3919 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003920 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003921 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003922 continue;
3923 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003924 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003925 mTtsOutputAvailable = true;
3926 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003927
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003928 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003929 continue;
3930 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003931 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003932 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3933 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003934 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003935 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003936 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003937 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003938 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003939 if ((profileType & outputDeviceTypes) == 0) {
3940 continue;
3941 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003942 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3943 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003944 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov708e0382018-05-30 09:53:04 -07003945 const DeviceVector &devicesForType = supportedDevices.getDevicesFromTypeMask(
3946 profileType);
Eric Laurentc40d9692016-04-13 19:14:13 -07003947 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3948 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003949 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08003950 status_t status = outputDesc->open(nullptr, profileType, address,
3951 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07003952
3953 if (status != NO_ERROR) {
3954 ALOGW("Cannot open output stream for device %08x on hw module %s",
3955 outputDesc->mDevice,
Mikhail Naganovd4120142017-12-06 15:49:22 -08003956 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003957 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003958 for (const auto& dev : supportedDevices) {
3959 ssize_t index = mAvailableOutputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07003960 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003961 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003962 mAvailableOutputDevices[index]->attach(hwModule);
Eric Laurentd78f1532014-09-16 16:38:20 -07003963 }
3964 }
3965 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003966 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003967 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003968 }
3969 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003970 setOutputDevice(outputDesc,
Eric Laurentfe231122017-11-17 17:48:06 -08003971 profileType,
Eric Laurentc40d9692016-04-13 19:14:13 -07003972 true,
3973 0,
3974 NULL,
Eric Laurentfe231122017-11-17 17:48:06 -08003975 address);
Eric Laurentd78f1532014-09-16 16:38:20 -07003976 }
Eric Laurente552edb2014-03-10 17:42:56 -07003977 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003978 // open input streams needed to access attached devices to validate
3979 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003980 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003981 if (!inProfile->canOpenNewIo()) {
3982 ALOGE("Invalid Input profile max open count %u for profile %s",
3983 inProfile->maxOpenCount, inProfile->getTagName().c_str());
3984 continue;
3985 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003986 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003987 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003988 continue;
3989 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003990 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003991 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003992 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
3993
Eric Laurentd78f1532014-09-16 16:38:20 -07003994 if ((profileType & inputDeviceTypes) == 0) {
3995 continue;
3996 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08003997 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08003998 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07003999
Mikhail Naganov708e0382018-05-30 09:53:04 -07004000 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(profileType);
Eric Laurent53b810e2017-12-10 17:25:10 -08004001 // the inputs vector must be of size >= 1, but we don't want to crash here
4002 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
4003 : String8("");
4004 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
4005 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
4006
Eric Laurentd78f1532014-09-16 16:38:20 -07004007 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004008 status_t status = inputDesc->open(nullptr,
4009 profileType,
Eric Laurent53b810e2017-12-10 17:25:10 -08004010 address,
Eric Laurentfe231122017-11-17 17:48:06 -08004011 AUDIO_SOURCE_MIC,
4012 AUDIO_INPUT_FLAG_NONE,
4013 &input);
Eric Laurentd78f1532014-09-16 16:38:20 -07004014
4015 if (status == NO_ERROR) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004016 for (const auto& dev : inProfile->getSupportedDevices()) {
4017 ssize_t index = mAvailableInputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07004018 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07004019 if (index >= 0) {
4020 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
4021 if (!devDesc->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004022 devDesc->attach(hwModule);
Eric Laurent83efe1c2017-07-09 16:51:08 -07004023 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07004024 }
Eric Laurentd78f1532014-09-16 16:38:20 -07004025 }
4026 }
Eric Laurentfe231122017-11-17 17:48:06 -08004027 inputDesc->close();
Eric Laurentd78f1532014-09-16 16:38:20 -07004028 } else {
4029 ALOGW("Cannot open input stream for device %08x on hw module %s",
Eric Laurentfe231122017-11-17 17:48:06 -08004030 profileType,
Mikhail Naganovd4120142017-12-06 15:49:22 -08004031 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07004032 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004033 }
4034 }
4035 // make sure all attached devices have been allocated a unique ID
4036 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004037 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004038 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004039 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
4040 continue;
4041 }
François Gaffie2110e042015-03-24 08:41:51 +01004042 // The device is now validated and can be appended to the available devices of the engine
4043 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
4044 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004045 i++;
4046 }
4047 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004048 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01004049 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004050 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
4051 continue;
4052 }
François Gaffie2110e042015-03-24 08:41:51 +01004053 // The device is now validated and can be appended to the available devices of the engine
4054 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
4055 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004056 i++;
4057 }
4058 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004059 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01004060 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004061 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004062 }
jiabin9ff780e2018-03-19 18:19:52 -07004063 // If microphones address is empty, set it according to device type
4064 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
4065 if (mAvailableInputDevices[i]->mAddress.isEmpty()) {
4066 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
4067 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
4068 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
4069 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BACK_MICROPHONE_ADDRESS);
4070 }
4071 }
4072 }
Eric Laurente552edb2014-03-10 17:42:56 -07004073
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004074 if (mPrimaryOutput == 0) {
4075 ALOGE("Failed to open primary output");
4076 status = NO_INIT;
4077 }
Eric Laurente552edb2014-03-10 17:42:56 -07004078
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09004079 // Silence ALOGV statements
4080 property_set("log.tag." LOG_TAG, "D");
4081
Eric Laurente552edb2014-03-10 17:42:56 -07004082 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004083 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004084}
4085
Eric Laurente0720872014-03-11 09:30:41 -07004086AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004087{
Eric Laurente552edb2014-03-10 17:42:56 -07004088 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004089 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004090 }
4091 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004092 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004093 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004094 mAvailableOutputDevices.clear();
4095 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004096 mOutputs.clear();
4097 mInputs.clear();
4098 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004099 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004100 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004101}
4102
Eric Laurente0720872014-03-11 09:30:41 -07004103status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004104{
Eric Laurent87ffa392015-05-22 10:32:38 -07004105 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004106}
4107
Eric Laurente552edb2014-03-10 17:42:56 -07004108// ---
4109
Eric Laurent98e38192018-02-15 18:31:53 -08004110void AudioPolicyManager::addOutput(audio_io_handle_t output,
4111 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004112{
Eric Laurent1c333e22014-05-20 10:48:17 -07004113 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08004114 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004115 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004116 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004117 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004118}
4119
François Gaffie53615e22015-03-19 09:24:12 +01004120void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4121{
4122 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004123 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004124}
4125
Eric Laurent98e38192018-02-15 18:31:53 -08004126void AudioPolicyManager::addInput(audio_io_handle_t input,
4127 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004128{
Eric Laurent1c333e22014-05-20 10:48:17 -07004129 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004130 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004131}
Eric Laurente552edb2014-03-10 17:42:56 -07004132
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004133void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08004134 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004135 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004136 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08004137 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004138 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08004139 if (devDesc != 0) {
4140 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
4141 desc->mIoHandle, address.string());
4142 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004143 }
4144}
4145
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004146status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004147 audio_policy_dev_state_t state,
4148 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004149 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07004150{
François Gaffie53615e22015-03-19 09:24:12 +01004151 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07004152 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004153
4154 if (audio_device_is_digital(device)) {
4155 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004156 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004157 }
Eric Laurente552edb2014-03-10 17:42:56 -07004158
Eric Laurent3b73df72014-03-11 09:06:29 -07004159 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004160 // first list already open outputs that can be routed to this device
4161 for (size_t i = 0; i < mOutputs.size(); i++) {
4162 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07004163 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004164 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004165 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
4166 outputs.add(mOutputs.keyAt(i));
4167 } else {
4168 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08004169 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004170 }
Eric Laurente552edb2014-03-10 17:42:56 -07004171 }
4172 }
4173 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004174 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004175 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004176 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4177 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004178 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004179 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004180 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004181 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004182 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4183 j, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004184 }
Eric Laurente552edb2014-03-10 17:42:56 -07004185 }
4186 }
4187 }
4188
Eric Laurent7b279bb2015-12-14 10:18:23 -08004189 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004190
Eric Laurente552edb2014-03-10 17:42:56 -07004191 if (profiles.isEmpty() && outputs.isEmpty()) {
4192 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4193 return BAD_VALUE;
4194 }
4195
4196 // open outputs for matching profiles if needed. Direct outputs are also opened to
4197 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4198 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004199 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004200
4201 // nothing to do if one output is already opened for this profile
4202 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004203 for (j = 0; j < outputs.size(); j++) {
4204 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004205 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004206 // matching profile: save the sample rates, format and channel masks supported
4207 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07004208 if (audio_device_is_digital(device)) {
4209 devDesc->importAudioPort(profile);
4210 }
Eric Laurente552edb2014-03-10 17:42:56 -07004211 break;
4212 }
4213 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004214 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004215 continue;
4216 }
4217
Eric Laurent3974e3b2017-12-07 17:58:43 -08004218 if (!profile->canOpenNewIo()) {
4219 ALOGW("Max Output number %u already opened for this profile %s",
4220 profile->maxOpenCount, profile->getTagName().c_str());
4221 continue;
4222 }
4223
Eric Laurent83efe1c2017-07-09 16:51:08 -07004224 ALOGV("opening output for device %08x with params %s profile %p name %s",
4225 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004226 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004227 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004228 status_t status = desc->open(nullptr, device, address,
4229 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004230
Eric Laurentfe231122017-11-17 17:48:06 -08004231 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004232 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004233 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004234 char *param = audio_device_address_to_parameter(device, address);
4235 mpClientInterface->setParameters(output, String8(param));
4236 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004237 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08004238 updateAudioProfiles(devDesc, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004239 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004240 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004241 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004242 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004243 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004244 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004245 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004246 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4247 profile->pickAudioProfile(
4248 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004249 config.offload_info.sample_rate = config.sample_rate;
4250 config.offload_info.channel_mask = config.channel_mask;
4251 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004252
4253 status_t status = desc->open(&config, device, address, AUDIO_STREAM_DEFAULT,
4254 AUDIO_OUTPUT_FLAG_NONE, &output);
4255 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004256 output = AUDIO_IO_HANDLE_NONE;
4257 }
Eric Laurentd4692962014-05-05 18:13:44 -07004258 }
4259
Eric Laurentcf2c0212014-07-25 16:20:43 -07004260 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004261 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01004262 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004263 sp<AudioPolicyMix> policyMix;
4264 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004265 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
4266 address.string());
4267 }
François Gaffie036e1e92015-03-19 10:16:24 +01004268 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07004269 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01004270
Eric Laurent87ffa392015-05-22 10:32:38 -07004271 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4272 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004273 // no duplicated output for direct outputs and
4274 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004275 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004276
Eric Laurentd4692962014-05-05 18:13:44 -07004277 //TODO: configure audio effect output stage here
4278
4279 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004280 sp<SwAudioOutputDescriptor> dupOutputDesc =
4281 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4282 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4283 &duplicatedOutput);
4284 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004285 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004286 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004287 } else {
4288 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004289 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004290 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004291 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004292 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004293 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004294 }
Eric Laurente552edb2014-03-10 17:42:56 -07004295 }
4296 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004297 } else {
4298 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004299 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004300 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004301 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004302 profiles.removeAt(profile_index);
4303 profile_index--;
4304 } else {
4305 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004306 // Load digital format info only for digital devices
4307 if (audio_device_is_digital(device)) {
4308 devDesc->importAudioPort(profile);
4309 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004310
François Gaffie53615e22015-03-19 09:24:12 +01004311 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004312 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4313 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004314 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004315 NULL/*patch handle*/, address.string());
4316 }
Eric Laurente552edb2014-03-10 17:42:56 -07004317 ALOGV("checkOutputsForDevice(): adding output %d", output);
4318 }
4319 }
4320
4321 if (profiles.isEmpty()) {
4322 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4323 return BAD_VALUE;
4324 }
Eric Laurentd4692962014-05-05 18:13:44 -07004325 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004326 // check if one opened output is not needed any more after disconnecting one device
4327 for (size_t i = 0; i < mOutputs.size(); i++) {
4328 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004329 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004330 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004331 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004332 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004333 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004334 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004335 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4336 mOutputs.keyAt(i));
4337 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004338 }
Eric Laurente552edb2014-03-10 17:42:56 -07004339 }
4340 }
Eric Laurentd4692962014-05-05 18:13:44 -07004341 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004342 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004343 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4344 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004345 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004346 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004347 "clearing direct output profile %zu on module %s",
4348 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004349 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004350 }
4351 }
4352 }
4353 }
4354 return NO_ERROR;
4355}
4356
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004357status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004358 audio_policy_dev_state_t state,
4359 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004360 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004361{
Paul McLean9080a4c2015-06-18 08:24:02 -07004362 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004363 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004364
4365 if (audio_device_is_digital(device)) {
4366 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004367 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004368 }
4369
Eric Laurentd4692962014-05-05 18:13:44 -07004370 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4371 // first list already open inputs that can be routed to this device
4372 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4373 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004374 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004375 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4376 inputs.add(mInputs.keyAt(input_index));
4377 }
4378 }
4379
4380 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004381 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004382 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004383 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004384 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004385 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004386 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004387
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004388 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004389 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004390 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004391 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004392 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4393 profile_index, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004394 }
Eric Laurentd4692962014-05-05 18:13:44 -07004395 }
4396 }
4397 }
4398
4399 if (profiles.isEmpty() && inputs.isEmpty()) {
4400 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4401 return BAD_VALUE;
4402 }
4403
4404 // open inputs for matching profiles if needed. Direct inputs are also opened to
4405 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4406 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4407
Eric Laurent1c333e22014-05-20 10:48:17 -07004408 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004409
Eric Laurentd4692962014-05-05 18:13:44 -07004410 // nothing to do if one input is already opened for this profile
4411 size_t input_index;
4412 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4413 desc = mInputs.valueAt(input_index);
4414 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004415 if (audio_device_is_digital(device)) {
4416 devDesc->importAudioPort(profile);
4417 }
Eric Laurentd4692962014-05-05 18:13:44 -07004418 break;
4419 }
4420 }
4421 if (input_index != mInputs.size()) {
4422 continue;
4423 }
4424
Eric Laurent3974e3b2017-12-07 17:58:43 -08004425 if (!profile->canOpenNewIo()) {
4426 ALOGW("Max Input number %u already opened for this profile %s",
4427 profile->maxOpenCount, profile->getTagName().c_str());
4428 continue;
4429 }
4430
Eric Laurentfe231122017-11-17 17:48:06 -08004431 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004432 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004433 status_t status = desc->open(nullptr,
4434 device,
4435 address,
4436 AUDIO_SOURCE_MIC,
4437 AUDIO_INPUT_FLAG_NONE,
4438 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004439
Eric Laurentcf2c0212014-07-25 16:20:43 -07004440 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004441 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004442 char *param = audio_device_address_to_parameter(device, address);
4443 mpClientInterface->setParameters(input, String8(param));
4444 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004445 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08004446 updateAudioProfiles(devDesc, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004447 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004448 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004449 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004450 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004451 }
4452
4453 if (input != 0) {
4454 addInput(input, desc);
4455 }
4456 } // endif input != 0
4457
Eric Laurentcf2c0212014-07-25 16:20:43 -07004458 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004459 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004460 profiles.removeAt(profile_index);
4461 profile_index--;
4462 } else {
4463 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004464 if (audio_device_is_digital(device)) {
4465 devDesc->importAudioPort(profile);
4466 }
Eric Laurentd4692962014-05-05 18:13:44 -07004467 ALOGV("checkInputsForDevice(): adding input %d", input);
4468 }
4469 } // end scan profiles
4470
4471 if (profiles.isEmpty()) {
4472 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4473 return BAD_VALUE;
4474 }
4475 } else {
4476 // Disconnect
4477 // check if one opened input is not needed any more after disconnecting one device
4478 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4479 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004480 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004481 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4482 mInputs.keyAt(input_index));
4483 inputs.add(mInputs.keyAt(input_index));
4484 }
4485 }
4486 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004487 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004488 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004489 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004490 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004491 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004492 if (profile->supportDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004493 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4494 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004495 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004496 }
4497 }
4498 }
4499 } // end disconnect
4500
4501 return NO_ERROR;
4502}
4503
4504
Eric Laurente0720872014-03-11 09:30:41 -07004505void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004506{
4507 ALOGV("closeOutput(%d)", output);
4508
Eric Laurentc75307b2015-03-17 15:29:32 -07004509 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004510 if (outputDesc == NULL) {
4511 ALOGW("closeOutput() unknown output %d", output);
4512 return;
4513 }
François Gaffie036e1e92015-03-19 10:16:24 +01004514 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004515
Eric Laurente552edb2014-03-10 17:42:56 -07004516 // look for duplicated outputs connected to the output being removed.
4517 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004518 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004519 if (dupOutputDesc->isDuplicated() &&
4520 (dupOutputDesc->mOutput1 == outputDesc ||
4521 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004522 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004523 if (dupOutputDesc->mOutput1 == outputDesc) {
4524 outputDesc2 = dupOutputDesc->mOutput2;
4525 } else {
4526 outputDesc2 = dupOutputDesc->mOutput1;
4527 }
4528 // As all active tracks on duplicated output will be deleted,
4529 // and as they were also referenced on the other output, the reference
4530 // count for their stream type must be adjusted accordingly on
4531 // the other output.
Andy Hungaf036da2018-09-21 10:46:21 -07004532 const bool wasActive = outputDesc2->isActive();
4533 for (const auto &clientPair : dupOutputDesc->getActiveClients()) {
4534 outputDesc2->changeStreamActiveCount(clientPair.first, -clientPair.second);
Eric Laurente552edb2014-03-10 17:42:56 -07004535 }
Eric Laurent733ce942017-12-07 12:18:25 -08004536 // stop() will be a no op if the output is still active but is needed in case all
4537 // active streams refcounts where cleared above
4538 if (wasActive) {
4539 outputDesc2->stop();
4540 }
Eric Laurente552edb2014-03-10 17:42:56 -07004541 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4542 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4543
4544 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004545 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004546 }
4547 }
4548
Eric Laurent05b90f82014-08-27 15:32:29 -07004549 nextAudioPortGeneration();
4550
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004551 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004552 if (index >= 0) {
4553 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004554 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004555 mAudioPatches.removeItemsAt(index);
4556 mpClientInterface->onAudioPatchListUpdate();
4557 }
4558
Eric Laurentfe231122017-11-17 17:48:06 -08004559 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004560
François Gaffie53615e22015-03-19 09:24:12 +01004561 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004562 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10004563
4564 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
4565 // no direct outputs are open.
Mikhail Naganov100f0122018-11-29 11:22:16 -08004566 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Dean Wheatley3023b382018-08-09 07:42:40 +10004567 bool directOutputOpen = false;
4568 for (size_t i = 0; i < mOutputs.size(); i++) {
4569 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
4570 directOutputOpen = true;
4571 break;
4572 }
4573 }
4574 if (!directOutputOpen) {
4575 ALOGV("no direct outputs open, reset MSD patch");
4576 setMsdPatch();
4577 }
4578 }
Eric Laurent05b90f82014-08-27 15:32:29 -07004579}
4580
4581void AudioPolicyManager::closeInput(audio_io_handle_t input)
4582{
4583 ALOGV("closeInput(%d)", input);
4584
4585 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4586 if (inputDesc == NULL) {
4587 ALOGW("closeInput() unknown input %d", input);
4588 return;
4589 }
4590
Eric Laurent6a94d692014-05-20 11:18:06 -07004591 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004592
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004593 audio_devices_t device = inputDesc->mDevice;
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004594 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004595 if (index >= 0) {
4596 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004597 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004598 mAudioPatches.removeItemsAt(index);
4599 mpClientInterface->onAudioPatchListUpdate();
4600 }
4601
Eric Laurentfe231122017-11-17 17:48:06 -08004602 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004603 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004604
4605 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
4606 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
4607 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
4608 SoundTrigger::setCaptureState(false);
4609 }
Eric Laurente552edb2014-03-10 17:42:56 -07004610}
4611
Eric Laurentc75307b2015-03-17 15:29:32 -07004612SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4613 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004614 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004615{
4616 SortedVector<audio_io_handle_t> outputs;
4617
4618 ALOGVV("getOutputsForDevice() device %04x", device);
4619 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004620 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004621 i, openOutputs.valueAt(i)->isDuplicated(),
4622 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004623 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4624 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4625 outputs.add(openOutputs.keyAt(i));
4626 }
4627 }
4628 return outputs;
4629}
4630
Mikhail Naganov37977152018-07-11 15:54:44 -07004631void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
4632{
4633 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
4634 // output is suspended before any tracks are moved to it
4635 checkA2dpSuspend();
4636 checkOutputForAllStrategies();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004637 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07004638 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00004639 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004640 setMsdPatch();
4641 }
Mikhail Naganov37977152018-07-11 15:54:44 -07004642}
4643
Eric Laurente0720872014-03-11 09:30:41 -07004644void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004645{
4646 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4647 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4648 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4649 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4650
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004651 // also take into account external policy-related changes: add all outputs which are
4652 // associated with policies in the "before" and "after" output vectors
4653 ALOGVV("checkOutputForStrategy(): policy related outputs");
4654 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004655 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004656 if (desc != 0 && desc->mPolicyMix != NULL) {
4657 srcOutputs.add(desc->mIoHandle);
4658 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4659 }
4660 }
4661 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004662 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004663 if (desc != 0 && desc->mPolicyMix != NULL) {
4664 dstOutputs.add(desc->mIoHandle);
4665 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4666 }
4667 }
4668
Mikhail Naganov9de8bd12018-07-23 16:41:31 -07004669 if (srcOutputs != dstOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004670 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4671 // audio from invalidated tracks will be rendered when unmuting
4672 uint32_t maxLatency = 0;
4673 for (audio_io_handle_t srcOut : srcOutputs) {
4674 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4675 if (desc != 0 && maxLatency < desc->latency()) {
4676 maxLatency = desc->latency();
4677 }
4678 }
Eric Laurente552edb2014-03-10 17:42:56 -07004679 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4680 strategy, srcOutputs[0], dstOutputs[0]);
4681 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004682 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004683 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4684 if (desc != 0 && isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004685 setStrategyMute(strategy, true, desc);
Eric Laurentac3a6902018-05-11 16:39:10 -07004686 setStrategyMute(strategy, false, desc, maxLatency * LATENCY_MUTE_FACTOR, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004687 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004688 sp<SourceClientDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004689 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004690 if (source != 0){
4691 connectAudioSource(source);
4692 }
Eric Laurente552edb2014-03-10 17:42:56 -07004693 }
4694
4695 // Move effects associated to this strategy from previous output to new output
4696 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004697 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004698 }
4699 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004700 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004701 if (getStrategy((audio_stream_type_t)i) == strategy) {
4702 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004703 }
4704 }
4705 }
4706}
4707
Eric Laurente0720872014-03-11 09:30:41 -07004708void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004709{
François Gaffie2110e042015-03-24 08:41:51 +01004710 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004711 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004712 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004713 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004714 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004715 checkOutputForStrategy(STRATEGY_SONIFICATION);
4716 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004717 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004718 checkOutputForStrategy(STRATEGY_MEDIA);
4719 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004720 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004721}
4722
Eric Laurente0720872014-03-11 09:30:41 -07004723void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004724{
François Gaffie53615e22015-03-19 09:24:12 +01004725 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004726 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004727 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004728 return;
4729 }
4730
Eric Laurent3a4311c2014-03-17 12:00:47 -07004731 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004732 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4733 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4734 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004735
4736 // if suspended, restore A2DP output if:
4737 // ((SCO device is NOT connected) ||
4738 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4739 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004740 //
Eric Laurentf732e072016-08-03 19:30:28 -07004741 // if not suspended, suspend A2DP output if:
4742 // (SCO device is connected) &&
4743 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4744 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004745 //
4746 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004747 if (!isScoConnected ||
4748 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4749 AUDIO_POLICY_FORCE_BT_SCO) &&
4750 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4751 AUDIO_POLICY_FORCE_BT_SCO) &&
4752 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004753 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004754
4755 mpClientInterface->restoreOutput(a2dpOutput);
4756 mA2dpSuspended = false;
4757 }
4758 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004759 if (isScoConnected &&
4760 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4761 AUDIO_POLICY_FORCE_BT_SCO) ||
4762 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4763 AUDIO_POLICY_FORCE_BT_SCO) ||
4764 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004765 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004766
4767 mpClientInterface->suspendOutput(a2dpOutput);
4768 mA2dpSuspended = true;
4769 }
4770 }
4771}
4772
Eric Laurent97ac8712018-07-27 18:59:02 -07004773template <class IoDescriptor, class Filter>
4774sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4775 IoDescriptor& desc, Filter filter, bool& active, const DeviceVector& devices)
4776{
4777 auto activeClients = desc->clientsList(true /*activeOnly*/);
4778 auto activeClientsWithRoute =
4779 desc->clientsList(true /*activeOnly*/, filter, true /*preferredDevice*/);
4780 active = activeClients.size() > 0;
4781 if (active && activeClients.size() == activeClientsWithRoute.size()) {
4782 return devices.getDeviceFromId(activeClientsWithRoute[0]->preferredDeviceId());
4783 }
4784 return nullptr;
4785}
4786
4787template <class IoCollection, class Filter>
4788sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4789 IoCollection& ioCollection, Filter filter, const DeviceVector& devices)
4790{
4791 sp<DeviceDescriptor> device;
4792 for (size_t i = 0; i < ioCollection.size(); i++) {
4793 auto desc = ioCollection.valueAt(i);
4794 bool active;
4795 sp<DeviceDescriptor> curDevice = findPreferredDevice(desc, filter, active, devices);
4796 if (active && curDevice == nullptr) {
4797 return nullptr;
4798 } else if (curDevice != nullptr) {
4799 device = curDevice;
4800 }
4801 }
4802 return device;
4803}
4804
Eric Laurentc75307b2015-03-17 15:29:32 -07004805audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4806 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004807{
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004808 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004809 if (index >= 0) {
4810 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4811 if (patchDesc->mUid != mUidCached) {
4812 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004813 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004814 return outputDesc->device();
4815 }
4816 }
4817
Eric Laurent97ac8712018-07-27 18:59:02 -07004818 // Honor explicit routing requests only if no client using default routing is active on this
4819 // input: a specific app can not force routing for other apps by setting a preferred device.
4820 bool active; // unused
4821 sp<DeviceDescriptor> deviceDesc =
4822 findPreferredDevice(outputDesc, STRATEGY_NONE, active, mAvailableOutputDevices);
4823 if (deviceDesc != nullptr) {
4824 return deviceDesc->type();
Eric Laurentf3a5a602018-05-22 18:42:55 -07004825 }
4826
Eric Laurente552edb2014-03-10 17:42:56 -07004827 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004828 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004829 // use device for strategy enforced audible
4830 // 2: we are in call or the strategy phone is active on the output:
4831 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004832 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004833 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004834 // 4: the strategy for enforced audible is active but not enforced on the output:
4835 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004836 // 5: the strategy accessibility is active on the output:
4837 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004838 // 6: the strategy "respectful" sonification is active on the output:
4839 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004840 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004841 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004842 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004843 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004844 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004845 // use device for strategy t-t-s
Eric Laurent484e9272018-06-07 17:29:23 -07004846
4847 // FIXME: extend use of isStrategyActiveOnSameModule() to all strategies
4848 // with a refined rule considering mutually exclusive devices (using same backend)
4849 // as opposed to all streams on the same audio HAL module.
Eric Laurent97ac8712018-07-27 18:59:02 -07004850 audio_devices_t device = AUDIO_DEVICE_NONE;
François Gaffiead3183e2015-03-18 16:55:35 +01004851 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004852 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004853 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4854 } else if (isInCall() ||
Eric Laurent484e9272018-06-07 17:29:23 -07004855 isStrategyActiveOnSameModule(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004856 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
Yung Ti Su3e7eb5e2018-06-13 11:48:42 +08004857 } else if (isStrategyActiveOnSameModule(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004858 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004859 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
4860 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004861 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4862 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004863 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004864 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004865 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004866 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004867 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004868 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004869 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004870 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004871 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004872 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004873 }
4874
Eric Laurent1c333e22014-05-20 10:48:17 -07004875 ALOGV("getNewOutputDevice() selected device %x", device);
4876 return device;
4877}
4878
Eric Laurentfb66dd92016-01-28 18:32:03 -08004879audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004880{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004881 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004882
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004883 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004884 if (index >= 0) {
4885 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4886 if (patchDesc->mUid != mUidCached) {
4887 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004888 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004889 return inputDesc->mDevice;
4890 }
4891 }
4892
Eric Laurent97ac8712018-07-27 18:59:02 -07004893 // Honor explicit routing requests only if no client using default routing is active on this
4894 // input: a specific app can not force routing for other apps by setting a preferred device.
4895 bool active;
4896 sp<DeviceDescriptor> deviceDesc =
4897 findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
4898 if (deviceDesc != nullptr) {
4899 return deviceDesc->type();
4900 }
4901
Eric Laurentdc95a252018-04-12 12:46:56 -07004902 // If we are not in call and no client is active on this input, this methods returns
4903 // AUDIO_DEVICE_NONE, causing the patch on the input stream to be released.
Eric Laurentdf628922018-12-06 21:45:51 +00004904 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
Eric Laurentdc95a252018-04-12 12:46:56 -07004905 if (source == AUDIO_SOURCE_DEFAULT && isInCall()) {
4906 source = AUDIO_SOURCE_VOICE_COMMUNICATION;
4907 }
4908 if (source != AUDIO_SOURCE_DEFAULT) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08004909 device = getDeviceAndMixForInputSource(source);
4910 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004911
Eric Laurente552edb2014-03-10 17:42:56 -07004912 return device;
4913}
4914
Eric Laurent794fde22016-03-11 09:50:45 -08004915bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4916 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004917 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004918}
4919
Eric Laurente0720872014-03-11 09:30:41 -07004920uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004921 return (uint32_t)getStrategy(stream);
4922}
4923
Eric Laurente0720872014-03-11 09:30:41 -07004924audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004925 // By checking the range of stream before calling getStrategy, we avoid
4926 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4927 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004928 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004929 return AUDIO_DEVICE_NONE;
4930 }
Eric Laurentb0688d62018-08-14 15:49:18 -07004931 audio_devices_t activeDevices = AUDIO_DEVICE_NONE;
Eric Laurent28d09f02016-03-08 10:43:05 -08004932 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004933 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4934 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004935 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004936 }
Eric Laurent794fde22016-03-11 09:50:45 -08004937 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004938 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004939 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Eric Laurentb0688d62018-08-14 15:49:18 -07004940 devices |= curDevices;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004941 for (audio_io_handle_t output : getOutputsForDevice(curDevices, mOutputs)) {
4942 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08004943 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurentb0688d62018-08-14 15:49:18 -07004944 activeDevices |= outputDesc->device();
Eric Laurent28d09f02016-03-08 10:43:05 -08004945 }
4946 }
Eric Laurente552edb2014-03-10 17:42:56 -07004947 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004948
Eric Laurentb0688d62018-08-14 15:49:18 -07004949 // Favor devices selected on active streams if any to report correct device in case of
4950 // explicit device selection
4951 if (activeDevices != AUDIO_DEVICE_NONE) {
4952 devices = activeDevices;
4953 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004954 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4955 and doesn't really need to.*/
4956 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4957 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4958 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4959 }
Eric Laurente552edb2014-03-10 17:42:56 -07004960 return devices;
4961}
4962
François Gaffie2110e042015-03-24 08:41:51 +01004963routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4964{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004965 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004966 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004967}
4968
Eric Laurent97ac8712018-07-27 18:59:02 -07004969routing_strategy AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004970 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004971 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004972 return STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004973 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004974 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004975 return STRATEGY_ENFORCED_AUDIBLE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004976 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004977 // usage to strategy mapping
Eric Laurent97ac8712018-07-27 18:59:02 -07004978 return mEngine->getStrategyForUsage(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004979}
4980
Eric Laurente0720872014-03-11 09:30:41 -07004981void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004982 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004983 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004984 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4985 updateDevicesAndOutputs();
4986 break;
4987 default:
4988 break;
4989 }
4990}
4991
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004992uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004993
4994 // skip beacon mute management if a dedicated TTS output is available
4995 if (mTtsOutputAvailable) {
4996 return 0;
4997 }
4998
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004999 switch(event) {
5000 case STARTING_OUTPUT:
5001 mBeaconMuteRefCount++;
5002 break;
5003 case STOPPING_OUTPUT:
5004 if (mBeaconMuteRefCount > 0) {
5005 mBeaconMuteRefCount--;
5006 }
5007 break;
5008 case STARTING_BEACON:
5009 mBeaconPlayingRefCount++;
5010 break;
5011 case STOPPING_BEACON:
5012 if (mBeaconPlayingRefCount > 0) {
5013 mBeaconPlayingRefCount--;
5014 }
5015 break;
5016 }
5017
5018 if (mBeaconMuteRefCount > 0) {
5019 // any playback causes beacon to be muted
5020 return setBeaconMute(true);
5021 } else {
5022 // no other playback: unmute when beacon starts playing, mute when it stops
5023 return setBeaconMute(mBeaconPlayingRefCount == 0);
5024 }
5025}
5026
5027uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5028 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5029 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5030 // keep track of muted state to avoid repeating mute/unmute operations
5031 if (mBeaconMuted != mute) {
5032 // mute/unmute AUDIO_STREAM_TTS on all outputs
5033 ALOGV("\t muting %d", mute);
5034 uint32_t maxLatency = 0;
5035 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005036 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005037 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07005038 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005039 0 /*delay*/, AUDIO_DEVICE_NONE);
5040 const uint32_t latency = desc->latency() * 2;
5041 if (latency > maxLatency) {
5042 maxLatency = latency;
5043 }
5044 }
5045 mBeaconMuted = mute;
5046 return maxLatency;
5047 }
5048 return 0;
5049}
5050
Eric Laurente0720872014-03-11 09:30:41 -07005051audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01005052 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005053{
Eric Laurent97ac8712018-07-27 18:59:02 -07005054 // Honor explicit routing requests only if all active clients have a preferred route in which
5055 // case the last active client route is used
5056 sp<DeviceDescriptor> deviceDesc = findPreferredDevice(mOutputs, strategy, mAvailableOutputDevices);
5057 if (deviceDesc != nullptr) {
5058 return deviceDesc->type();
Paul McLeanaa981192015-03-21 09:55:15 -07005059 }
5060
Eric Laurente552edb2014-03-10 17:42:56 -07005061 if (fromCache) {
5062 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
5063 strategy, mDeviceForStrategy[strategy]);
5064 return mDeviceForStrategy[strategy];
5065 }
François Gaffie2110e042015-03-24 08:41:51 +01005066 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07005067}
5068
Eric Laurente0720872014-03-11 09:30:41 -07005069void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005070{
5071 for (int i = 0; i < NUM_STRATEGIES; i++) {
5072 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
5073 }
5074 mPreviousOutputs = mOutputs;
5075}
5076
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005077uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005078 audio_devices_t prevDevice,
5079 uint32_t delayMs)
5080{
5081 // mute/unmute strategies using an incompatible device combination
5082 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5083 // if unmuting, unmute only after the specified delay
5084 if (outputDesc->isDuplicated()) {
5085 return 0;
5086 }
5087
5088 uint32_t muteWaitMs = 0;
5089 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07005090 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005091
5092 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
5093 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07005094 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07005095 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
5096 bool doMute = false;
5097
5098 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
5099 doMute = true;
5100 outputDesc->mStrategyMutedByDevice[i] = true;
5101 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
5102 doMute = true;
5103 outputDesc->mStrategyMutedByDevice[i] = false;
5104 }
Eric Laurent99401132014-05-07 19:48:15 -07005105 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005106 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005107 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005108 // skip output if it does not share any device with current output
5109 if ((desc->supportedDevices() & outputDesc->supportedDevices())
5110 == AUDIO_DEVICE_NONE) {
5111 continue;
5112 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005113 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07005114 mute ? "muting" : "unmuting", i, curDevice);
5115 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005116 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005117 if (mute) {
5118 // FIXME: should not need to double latency if volume could be applied
5119 // immediately by the audioflinger mixer. We must account for the delay
5120 // between now and the next time the audioflinger thread for this output
5121 // will process a buffer (which corresponds to one buffer size,
5122 // usually 1/2 or 1/4 of the latency).
5123 if (muteWaitMs < desc->latency() * 2) {
5124 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005125 }
5126 }
5127 }
5128 }
5129 }
5130 }
5131
Eric Laurent99401132014-05-07 19:48:15 -07005132 // temporary mute output if device selection changes to avoid volume bursts due to
5133 // different per device volumes
5134 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005135 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5136 // temporary mute duration is conservatively set to 4 times the reported latency
5137 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5138 if (muteWaitMs < tempMuteWaitMs) {
5139 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005140 }
Eric Laurentdc462862016-07-19 12:29:53 -07005141
Eric Laurent99401132014-05-07 19:48:15 -07005142 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005143 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005144 // make sure that we do not start the temporary mute period too early in case of
5145 // delayed device change
5146 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005147 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07005148 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07005149 }
5150 }
5151 }
5152
Eric Laurente552edb2014-03-10 17:42:56 -07005153 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5154 if (muteWaitMs > delayMs) {
5155 muteWaitMs -= delayMs;
5156 usleep(muteWaitMs * 1000);
5157 return muteWaitMs;
5158 }
5159 return 0;
5160}
5161
Eric Laurentc75307b2015-03-17 15:29:32 -07005162uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005163 audio_devices_t device,
5164 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07005165 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005166 audio_patch_handle_t *patchHandle,
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005167 const char *address,
5168 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005169{
Eric Laurentc75307b2015-03-17 15:29:32 -07005170 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005171 AudioParameter param;
5172 uint32_t muteWaitMs;
5173
5174 if (outputDesc->isDuplicated()) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005175 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs,
5176 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
5177 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs,
5178 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005179 return muteWaitMs;
5180 }
5181 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5182 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07005183 if ((device != AUDIO_DEVICE_NONE) &&
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005184 ((device & outputDesc->supportedDevices()) == AUDIO_DEVICE_NONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005185 return 0;
5186 }
5187
5188 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07005189 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07005190
5191 audio_devices_t prevDevice = outputDesc->mDevice;
5192
Paul McLeanaa981192015-03-21 09:55:15 -07005193 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005194
5195 if (device != AUDIO_DEVICE_NONE) {
5196 outputDesc->mDevice = device;
5197 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005198
5199 // if the outputs are not materially active, there is no need to mute.
5200 if (requiresMuteCheck) {
5201 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
5202 } else {
5203 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5204 muteWaitMs = 0;
5205 }
Eric Laurente552edb2014-03-10 17:42:56 -07005206
5207 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005208 // the requested device is AUDIO_DEVICE_NONE
5209 // OR the requested device is the same as current device
5210 // AND force is not specified
5211 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07005212 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07005213 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
5214 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005215 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005216 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005217 return muteWaitMs;
5218 }
5219
5220 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07005221
Eric Laurente552edb2014-03-10 17:42:56 -07005222 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07005223 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005224 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005225 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07005226 DeviceVector deviceList;
5227 if ((address == NULL) || (strlen(address) == 0)) {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005228 deviceList = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurentc40d9692016-04-13 19:14:13 -07005229 } else {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005230 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
5231 device, String8(address));
5232 if (deviceDesc) deviceList.add(deviceDesc);
Eric Laurentc40d9692016-04-13 19:14:13 -07005233 }
5234
Eric Laurent1c333e22014-05-20 10:48:17 -07005235 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005236 PatchBuilder patchBuilder;
5237 patchBuilder.addSource(outputDesc);
Eric Laurent1c333e22014-05-20 10:48:17 -07005238 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005239 patchBuilder.addSink(deviceList.itemAt(i));
Eric Laurent1c333e22014-05-20 10:48:17 -07005240 }
Mikhail Naganovdc769682018-05-04 15:34:08 -07005241 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005242 }
Eric Laurentdf628922018-12-06 21:45:51 +00005243
5244 // inform all input as well
5245 for (size_t i = 0; i < mInputs.size(); i++) {
5246 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
5247 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
5248 AudioParameter inputCmd = AudioParameter();
5249 ALOGV("%s: inform input %d of device:%d", __func__,
5250 inputDescriptor->mIoHandle, device);
5251 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
5252 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
5253 inputCmd.toString(),
5254 delayMs);
5255 }
5256 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005257 }
Eric Laurente552edb2014-03-10 17:42:56 -07005258
5259 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07005260 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005261
5262 return muteWaitMs;
5263}
5264
Eric Laurentc75307b2015-03-17 15:29:32 -07005265status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005266 int delayMs,
5267 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005268{
Eric Laurent6a94d692014-05-20 11:18:06 -07005269 ssize_t index;
5270 if (patchHandle) {
5271 index = mAudioPatches.indexOfKey(*patchHandle);
5272 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005273 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005274 }
5275 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005276 return INVALID_OPERATION;
5277 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005278 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5279 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005280 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005281 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005282 removeAudioPatch(patchDesc->mHandle);
5283 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005284 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005285 return status;
5286}
5287
5288status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5289 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005290 bool force,
5291 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005292{
5293 status_t status = NO_ERROR;
5294
Eric Laurent1f2f2232014-06-02 12:01:23 -07005295 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005296 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5297 inputDesc->mDevice = device;
5298
Mikhail Naganov708e0382018-05-30 09:53:04 -07005299 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005300 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005301 PatchBuilder patchBuilder;
5302 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005303 // AUDIO_SOURCE_HOTWORD is for internal use only:
5304 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07005305 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5306 auto result = usecase;
5307 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5308 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5309 }
5310 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07005311 //only one input device for now
Mikhail Naganovdc769682018-05-04 15:34:08 -07005312 addSource(deviceList.itemAt(0));
5313 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005314 }
5315 }
5316 return status;
5317}
5318
Eric Laurent6a94d692014-05-20 11:18:06 -07005319status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5320 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005321{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005322 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005323 ssize_t index;
5324 if (patchHandle) {
5325 index = mAudioPatches.indexOfKey(*patchHandle);
5326 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005327 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005328 }
5329 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005330 return INVALID_OPERATION;
5331 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005332 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5333 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005334 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005335 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005336 removeAudioPatch(patchDesc->mHandle);
5337 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005338 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005339 return status;
5340}
5341
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005342sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005343 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005344 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005345 audio_format_t& format,
5346 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005347 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005348{
5349 // Choose an input profile based on the requested capture parameters: select the first available
5350 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005351 //
5352 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5353 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005354
Glenn Kasten730b9262018-03-29 15:01:26 -07005355 sp<IOProfile> firstInexact;
5356 uint32_t updatedSamplingRate = 0;
5357 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5358 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005359 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005360 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005361 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005362 //updatedFormat = format;
Eric Laurent275e8e92014-11-30 15:14:47 -08005363 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005364 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005365 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005366 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005367 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005368 &channelMask /*updatedChannelMask*/,
5369 // FIXME ugly cast
5370 (audio_output_flags_t) flags,
5371 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005372 return profile;
5373 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005374 if (firstInexact == nullptr && profile->isCompatibleProfile(device, address,
5375 samplingRate,
5376 &updatedSamplingRate,
5377 format,
5378 &updatedFormat,
5379 channelMask,
5380 &updatedChannelMask,
5381 // FIXME ugly cast
5382 (audio_output_flags_t) flags,
5383 false /*exactMatchRequiredForInputFlags*/)) {
5384 firstInexact = profile;
5385 }
5386
Eric Laurente552edb2014-03-10 17:42:56 -07005387 }
5388 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005389 if (firstInexact != nullptr) {
5390 samplingRate = updatedSamplingRate;
5391 format = updatedFormat;
5392 channelMask = updatedChannelMask;
5393 return firstInexact;
5394 }
Eric Laurente552edb2014-03-10 17:42:56 -07005395 return NULL;
5396}
5397
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005398
5399audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005400 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005401{
Eric Laurent97ac8712018-07-27 18:59:02 -07005402 // Honor explicit routing requests only if all active clients have a preferred route in which
5403 // case the last active client route is used
5404 sp<DeviceDescriptor> deviceDesc =
5405 findPreferredDevice(mInputs, inputSource, mAvailableInputDevices);
5406 if (deviceDesc != nullptr) {
5407 return deviceDesc->type();
5408 }
5409
5410
François Gaffie036e1e92015-03-19 10:16:24 +01005411 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5412 audio_devices_t selectedDeviceFromMix =
5413 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005414
François Gaffie036e1e92015-03-19 10:16:24 +01005415 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5416 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005417 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005418 return getDeviceForInputSource(inputSource);
5419}
5420
5421audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5422{
Eric Laurent97ac8712018-07-27 18:59:02 -07005423 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005424}
5425
Eric Laurente0720872014-03-11 09:30:41 -07005426float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005427 int index,
5428 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005429{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005430 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005431
5432 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5433 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5434 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5435 // the ringtone volume
5436 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5437 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5438 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5439 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5440 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5441 }
5442
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005443 // in-call: always cap volume by voice volume + some low headroom
5444 if ((stream != AUDIO_STREAM_VOICE_CALL) &&
Eric Laurent7731b5a2018-04-06 15:47:22 -07005445 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005446 switch (stream) {
5447 case AUDIO_STREAM_SYSTEM:
5448 case AUDIO_STREAM_RING:
5449 case AUDIO_STREAM_MUSIC:
5450 case AUDIO_STREAM_ALARM:
5451 case AUDIO_STREAM_NOTIFICATION:
5452 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5453 case AUDIO_STREAM_DTMF:
5454 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005455 int voiceVolumeIndex =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005456 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, device);
Eric Laurent7731b5a2018-04-06 15:47:22 -07005457 const float maxVoiceVolDb =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005458 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, device)
Eric Laurent7731b5a2018-04-06 15:47:22 -07005459 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005460 if (volumeDB > maxVoiceVolDb) {
5461 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5462 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5463 volumeDB = maxVoiceVolDb;
5464 }
5465 } break;
5466 default:
5467 break;
5468 }
5469 }
5470
Eric Laurente552edb2014-03-10 17:42:56 -07005471 // if a headset is connected, apply the following rules to ring tones and notifications
5472 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005473 // - always attenuate notifications volume by 6dB
5474 // - attenuate ring tones volume by 6dB unless music is not playing and
5475 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005476 // - if music is playing, always limit the volume to current music volume,
5477 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005478 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005479 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5480 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5481 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005482 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005483 AUDIO_DEVICE_OUT_USB_HEADSET |
5484 AUDIO_DEVICE_OUT_HEARING_AID)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005485 ((stream_strategy == STRATEGY_SONIFICATION)
5486 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005487 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005488 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005489 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005490 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005491 // when the phone is ringing we must consider that music could have been paused just before
5492 // by the music application and behave as if music was active if the last music track was
5493 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005494 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005495 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005496 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005497 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005498 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005499 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5500 musicDevice),
5501 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005502 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5503 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005504 if (volumeDB > minVolDB) {
5505 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005506 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005507 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005508 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5509 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5510 // on A2DP, also ensure notification volume is not too low compared to media when
5511 // intended to be played
5512 if ((volumeDB > -96.0f) &&
5513 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5514 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5515 stream, device,
5516 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5517 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5518 }
5519 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005520 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5521 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005522 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005523 }
5524 }
5525
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005526 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005527}
5528
Eric Laurent3839bc02018-07-10 18:33:34 -07005529int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
5530 audio_stream_type_t srcStream,
5531 audio_stream_type_t dstStream)
5532{
5533 if (srcStream == dstStream) {
5534 return srcIndex;
5535 }
5536 float minSrc = (float)mVolumeCurves->getVolumeIndexMin(srcStream);
5537 float maxSrc = (float)mVolumeCurves->getVolumeIndexMax(srcStream);
5538 float minDst = (float)mVolumeCurves->getVolumeIndexMin(dstStream);
5539 float maxDst = (float)mVolumeCurves->getVolumeIndexMax(dstStream);
5540
5541 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
5542}
5543
Eric Laurente0720872014-03-11 09:30:41 -07005544status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005545 int index,
5546 const sp<AudioOutputDescriptor>& outputDesc,
5547 audio_devices_t device,
5548 int delayMs,
5549 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005550{
Eric Laurente552edb2014-03-10 17:42:56 -07005551 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005552 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005553 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005554 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005555 return NO_ERROR;
5556 }
François Gaffie2110e042015-03-24 08:41:51 +01005557 audio_policy_forced_cfg_t forceUseForComm =
5558 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005559 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005560 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5561 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005562 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005563 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005564 return INVALID_OPERATION;
5565 }
5566
Eric Laurentc75307b2015-03-17 15:29:32 -07005567 if (device == AUDIO_DEVICE_NONE) {
5568 device = outputDesc->device();
5569 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005570
Eric Laurentffbc80f2015-03-18 18:30:19 -07005571 float volumeDb = computeVolume(stream, index, device);
HW Leeda7581e2018-05-22 18:31:34 +08005572 if (outputDesc->isFixedVolume(device) ||
5573 // Force VoIP volume to max for bluetooth SCO
5574 ((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
5575 (device & AUDIO_DEVICE_OUT_ALL_SCO) != 0)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005576 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005577 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005578
Eric Laurentffbc80f2015-03-18 18:30:19 -07005579 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005580
Eric Laurent3b73df72014-03-11 09:06:29 -07005581 if (stream == AUDIO_STREAM_VOICE_CALL ||
5582 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005583 float voiceVolume;
5584 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005585 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurent3839bc02018-07-10 18:33:34 -07005586 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005587 } else {
5588 voiceVolume = 1.0;
5589 }
5590
Eric Laurent18fba842016-03-31 14:41:26 -07005591 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005592 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5593 mLastVoiceVolume = voiceVolume;
5594 }
5595 }
5596
5597 return NO_ERROR;
5598}
5599
Eric Laurentc75307b2015-03-17 15:29:32 -07005600void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5601 audio_devices_t device,
5602 int delayMs,
5603 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005604{
Eric Laurentc75307b2015-03-17 15:29:32 -07005605 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005606
Eric Laurent794fde22016-03-11 09:50:45 -08005607 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005608 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005609 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005610 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005611 device,
5612 delayMs,
5613 force);
5614 }
5615}
5616
Eric Laurente0720872014-03-11 09:30:41 -07005617void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005618 bool on,
5619 const sp<AudioOutputDescriptor>& outputDesc,
5620 int delayMs,
5621 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005622{
Eric Laurent72249d52015-06-08 11:12:15 -07005623 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5624 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005625 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005626 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005627 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005628 }
5629 }
5630}
5631
Eric Laurente0720872014-03-11 09:30:41 -07005632void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005633 bool on,
5634 const sp<AudioOutputDescriptor>& outputDesc,
5635 int delayMs,
5636 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005637{
Eric Laurente552edb2014-03-10 17:42:56 -07005638 if (device == AUDIO_DEVICE_NONE) {
5639 device = outputDesc->device();
5640 }
5641
Eric Laurentc75307b2015-03-17 15:29:32 -07005642 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5643 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005644
5645 if (on) {
5646 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005647 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005648 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005649 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005650 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005651 }
5652 }
5653 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5654 outputDesc->mMuteCount[stream]++;
5655 } else {
5656 if (outputDesc->mMuteCount[stream] == 0) {
5657 ALOGV("setStreamMute() unmuting non muted stream!");
5658 return;
5659 }
5660 if (--outputDesc->mMuteCount[stream] == 0) {
5661 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005662 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005663 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005664 device,
5665 delayMs);
5666 }
5667 }
5668}
5669
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005670audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5671{
5672 // flags to stream type mapping
5673 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5674 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5675 }
5676 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5677 return AUDIO_STREAM_BLUETOOTH_SCO;
5678 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005679 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5680 return AUDIO_STREAM_TTS;
5681 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005682
Ari Hausman-Cohen5c00d012018-06-26 17:09:11 -07005683 return audio_usage_to_stream_type(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005684}
Eric Laurente83b55d2014-11-14 10:06:21 -08005685
François Gaffie53615e22015-03-19 09:24:12 +01005686bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5687{
Eric Laurente83b55d2014-11-14 10:06:21 -08005688 // has flags that map to a strategy?
5689 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5690 return true;
5691 }
5692
5693 // has known usage?
5694 switch (paa->usage) {
5695 case AUDIO_USAGE_UNKNOWN:
5696 case AUDIO_USAGE_MEDIA:
5697 case AUDIO_USAGE_VOICE_COMMUNICATION:
5698 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5699 case AUDIO_USAGE_ALARM:
5700 case AUDIO_USAGE_NOTIFICATION:
5701 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5702 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5703 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5704 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5705 case AUDIO_USAGE_NOTIFICATION_EVENT:
5706 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5707 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5708 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5709 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005710 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005711 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005712 break;
5713 default:
5714 return false;
5715 }
5716 return true;
5717}
5718
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005719bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005720 routing_strategy strategy, uint32_t inPastMs,
5721 nsecs_t sysTime) const
5722{
5723 if ((sysTime == 0) && (inPastMs != 0)) {
5724 sysTime = systemTime();
5725 }
Eric Laurent794fde22016-03-11 09:50:45 -08005726 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005727 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurent97ac8712018-07-27 18:59:02 -07005728 (STRATEGY_NONE == strategy)) &&
François Gaffiead3183e2015-03-18 16:55:35 +01005729 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5730 return true;
5731 }
5732 }
5733 return false;
5734}
5735
Eric Laurent484e9272018-06-07 17:29:23 -07005736bool AudioPolicyManager::isStrategyActiveOnSameModule(const sp<AudioOutputDescriptor>& outputDesc,
5737 routing_strategy strategy, uint32_t inPastMs,
5738 nsecs_t sysTime) const
5739{
5740 for (size_t i = 0; i < mOutputs.size(); i++) {
5741 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5742 if (outputDesc->sharesHwModuleWith(desc)
5743 && isStrategyActive(desc, strategy, inPastMs, sysTime)) {
5744 return true;
5745 }
5746 }
5747 return false;
5748}
5749
François Gaffie2110e042015-03-24 08:41:51 +01005750audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5751{
5752 return mEngine->getForceUse(usage);
5753}
5754
5755bool AudioPolicyManager::isInCall()
5756{
5757 return isStateInCall(mEngine->getPhoneState());
5758}
5759
5760bool AudioPolicyManager::isStateInCall(int state)
5761{
5762 return is_state_in_call(state);
5763}
5764
Eric Laurentd60560a2015-04-10 11:31:20 -07005765void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5766{
5767 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005768 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5769 if (sourceDesc->srcDevice()->equals(deviceDesc)) {
5770 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->portId());
5771 stopAudioSource(sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005772 }
5773 }
5774
5775 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5776 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5777 bool release = false;
5778 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5779 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5780 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5781 source->ext.device.type == deviceDesc->type()) {
5782 release = true;
5783 }
5784 }
5785 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5786 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5787 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5788 sink->ext.device.type == deviceDesc->type()) {
5789 release = true;
5790 }
5791 }
5792 if (release) {
5793 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5794 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5795 }
5796 }
5797}
5798
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005799void AudioPolicyManager::modifySurroundFormats(
5800 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005801 std::unordered_set<audio_format_t> enforcedSurround(
5802 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08005803 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
5804 for (const auto& pair : mConfig.getSurroundFormats()) {
5805 allSurround.insert(pair.first);
5806 for (const auto& subformat : pair.second) allSurround.insert(subformat);
5807 }
Phil Burk09bc4612016-02-24 15:58:15 -08005808
5809 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5810 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005811 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005812 // This is the resulting set of formats depending on the surround mode:
5813 // 'all surround' = allSurround
5814 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
5815 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
5816 // 'manual surround' = mManualSurroundFormats
5817 // AUTO: formats v 'enforced surround'
5818 // ALWAYS: formats v 'all surround' v 'enforced surround'
5819 // NEVER: formats ^ 'non-surround'
5820 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08005821
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005822 std::unordered_set<audio_format_t> formatSet;
5823 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
5824 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005825 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005826 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005827 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005828 formatSet.insert(*formatIter);
5829 }
5830 }
5831 } else {
5832 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
5833 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005834 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005835
jiabin81772902018-04-02 17:52:27 -07005836 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005837 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005838 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
5839 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
5840 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08005841 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005842 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
5843 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5844 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07005845 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005846 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08005847 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005848 for (const auto& format : formatSet) {
5849 formatsPtr->push(format);
5850 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005851}
5852
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005853void AudioPolicyManager::modifySurroundChannelMasks(ChannelsVector *channelMasksPtr) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005854 ChannelsVector &channelMasks = *channelMasksPtr;
5855 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5856 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5857
5858 // If NEVER, then remove support for channelMasks > stereo.
5859 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5860 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5861 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5862 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5863 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5864 channelMasks.removeAt(maskIndex);
5865 } else {
5866 maskIndex++;
5867 }
5868 }
jiabin81772902018-04-02 17:52:27 -07005869 // If ALWAYS or MANUAL, then make sure we at least support 5.1
5870 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
5871 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005872 bool supports5dot1 = false;
5873 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005874 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005875 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5876 supports5dot1 = true;
5877 break;
5878 }
5879 }
5880 // If not then add 5.1 support.
5881 if (!supports5dot1) {
5882 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005883 ALOGI("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07005884 }
Phil Burk09bc4612016-02-24 15:58:15 -08005885 }
5886}
5887
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005888void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07005889 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005890 AudioProfileVector &profiles)
5891{
5892 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005893 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07005894
François Gaffie112b0af2015-11-19 16:13:25 +01005895 // Format MUST be checked first to update the list of AudioProfile
5896 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005897 reply = mpClientInterface->getParameters(
5898 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07005899 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005900 AudioParameter repliedParameters(reply);
5901 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005902 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005903 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5904 return;
5905 }
Phil Burk09bc4612016-02-24 15:58:15 -08005906 FormatVector formats = formatsFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08005907 if (device == AUDIO_DEVICE_OUT_HDMI
5908 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005909 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005910 }
Phil Burk09bc4612016-02-24 15:58:15 -08005911 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005912 }
François Gaffie112b0af2015-11-19 16:13:25 +01005913
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005914 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08005915 ChannelsVector channelMasks;
5916 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005917 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07005918 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01005919
5920 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005921 reply = mpClientInterface->getParameters(
5922 ioHandle,
5923 requestedParameters.toString() + ";" +
5924 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01005925 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005926 AudioParameter repliedParameters(reply);
5927 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005928 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005929 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005930 }
5931 }
5932 if (profiles.hasDynamicChannelsFor(format)) {
5933 reply = mpClientInterface->getParameters(ioHandle,
5934 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07005935 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01005936 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005937 AudioParameter repliedParameters(reply);
5938 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005939 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005940 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08005941 if (device == AUDIO_DEVICE_OUT_HDMI
5942 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005943 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07005944 }
François Gaffie112b0af2015-11-19 16:13:25 +01005945 }
5946 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08005947 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01005948 }
5949}
Eric Laurentd60560a2015-04-10 11:31:20 -07005950
Mikhail Naganovdc769682018-05-04 15:34:08 -07005951status_t AudioPolicyManager::installPatch(const char *caller,
5952 audio_patch_handle_t *patchHandle,
5953 AudioIODescriptorInterface *ioDescriptor,
5954 const struct audio_patch *patch,
5955 int delayMs)
5956{
5957 ssize_t index = mAudioPatches.indexOfKey(
5958 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
5959 *patchHandle : ioDescriptor->getPatchHandle());
5960 sp<AudioPatch> patchDesc;
5961 status_t status = installPatch(
5962 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
5963 if (status == NO_ERROR) {
5964 ioDescriptor->setPatchHandle(patchDesc->mHandle);
5965 }
5966 return status;
5967}
5968
5969status_t AudioPolicyManager::installPatch(const char *caller,
5970 ssize_t index,
5971 audio_patch_handle_t *patchHandle,
5972 const struct audio_patch *patch,
5973 int delayMs,
5974 uid_t uid,
5975 sp<AudioPatch> *patchDescPtr)
5976{
5977 sp<AudioPatch> patchDesc;
5978 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
5979 if (index >= 0) {
5980 patchDesc = mAudioPatches.valueAt(index);
5981 afPatchHandle = patchDesc->mAfPatchHandle;
5982 }
5983
5984 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
5985 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
5986 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
5987 if (status == NO_ERROR) {
5988 if (index < 0) {
5989 patchDesc = new AudioPatch(patch, uid);
5990 addAudioPatch(patchDesc->mHandle, patchDesc);
5991 } else {
5992 patchDesc->mPatch = *patch;
5993 }
5994 patchDesc->mAfPatchHandle = afPatchHandle;
5995 if (patchHandle) {
5996 *patchHandle = patchDesc->mHandle;
5997 }
5998 nextAudioPortGeneration();
5999 mpClientInterface->onAudioPatchListUpdate();
6000 }
6001 if (patchDescPtr) *patchDescPtr = patchDesc;
6002 return status;
6003}
6004
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006005} // namespace android