blob: 004157096ddf4582136778ff834250cdefcfee71 [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 Naganov15be9d22017-11-08 14:18:13 +1100220 const audio_devices_t msdOutDevice = getMsdAudioOutDeviceTypes();
Eric Laurente552edb2014-03-10 17:42:56 -0700221 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700222 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
223 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
224 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700225 // do not force device change on duplicated output because if device is 0, it will
226 // also force a device 0 for the two outputs it is duplicated to which may override
227 // a valid device selection on those outputs.
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100228 bool force = (msdOutDevice == AUDIO_DEVICE_NONE || msdOutDevice != desc->device())
229 && !desc->isDuplicated()
François Gaffie53615e22015-03-19 09:24:12 +0100230 && (!device_distinguishes_on_address(device)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700231 // always force when disconnecting (a non-duplicated device)
232 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
Eric Laurentc75307b2015-03-17 15:29:32 -0700233 setOutputDevice(desc, newDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700234 }
Eric Laurente552edb2014-03-10 17:42:56 -0700235 }
236
Eric Laurentd60560a2015-04-10 11:31:20 -0700237 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
238 cleanUpForDevice(devDesc);
239 }
240
Eric Laurent72aa32f2014-05-30 18:51:48 -0700241 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700242 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700243 } // end if is output device
244
Eric Laurente552edb2014-03-10 17:42:56 -0700245 // handle input devices
246 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700247 SortedVector <audio_io_handle_t> inputs;
248
Eric Laurent3a4311c2014-03-17 12:00:47 -0700249 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700250 switch (state)
251 {
252 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700253 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700254 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700255 ALOGW("setDeviceConnectionState() device already connected: %d", device);
256 return INVALID_OPERATION;
257 }
François Gaffie53615e22015-03-19 09:24:12 +0100258 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700259 if (module == NULL) {
260 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
261 device);
262 return INVALID_OPERATION;
263 }
François Gaffie44481e72016-04-20 07:49:57 +0200264
265 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
266 // parameters on newly connected devices (instead of opening the inputs...)
267 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
268
Paul McLean9080a4c2015-06-18 08:24:02 -0700269 if (checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress) != NO_ERROR) {
François Gaffie44481e72016-04-20 07:49:57 +0200270 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
271 devDesc->mAddress);
Eric Laurentd4692962014-05-05 18:13:44 -0700272 return INVALID_OPERATION;
273 }
274
Eric Laurent3a4311c2014-03-17 12:00:47 -0700275 index = mAvailableInputDevices.add(devDesc);
276 if (index >= 0) {
Paul McLeane743a472015-01-28 11:07:31 -0800277 mAvailableInputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700278 } else {
279 return NO_MEMORY;
280 }
Eric Laurent3ae5f312015-02-03 17:12:08 -0800281
François Gaffie2110e042015-03-24 08:41:51 +0100282 // Propagate device availability to Engine
283 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700284 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700285
286 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700287 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700288 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700289 ALOGW("setDeviceConnectionState() device not connected: %d", device);
290 return INVALID_OPERATION;
291 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700292
293 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
294
295 // Set Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200296 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700297
Paul McLean9080a4c2015-06-18 08:24:02 -0700298 checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700299 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700300
François Gaffie2110e042015-03-24 08:41:51 +0100301 // Propagate device availability to Engine
302 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700303 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700304
305 default:
306 ALOGE("setDeviceConnectionState() invalid state: %x", state);
307 return BAD_VALUE;
308 }
309
Eric Laurentd4692962014-05-05 18:13:44 -0700310 closeAllInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700311 // As the input device list can impact the output device selection, update
312 // getDeviceForStrategy() cache
313 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700314
Eric Laurent87ffa392015-05-22 10:32:38 -0700315 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700316 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
317 updateCallRouting(newDevice);
318 }
319
Eric Laurentd60560a2015-04-10 11:31:20 -0700320 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
321 cleanUpForDevice(devDesc);
322 }
323
Eric Laurentb52c1522014-05-20 11:27:36 -0700324 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700325 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700326 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700327
328 ALOGW("setDeviceConnectionState() invalid device: %x", device);
329 return BAD_VALUE;
330}
331
Eric Laurente0720872014-03-11 09:30:41 -0700332audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100333 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700334{
Eric Laurent634b7142016-04-20 13:48:02 -0700335 sp<DeviceDescriptor> devDesc =
336 mHwModules.getDeviceDescriptor(device, device_address, "",
337 (strlen(device_address) != 0)/*matchAddress*/);
338
339 if (devDesc == 0) {
340 ALOGW("getDeviceConnectionState() undeclared device, type %08x, address: %s",
341 device, device_address);
342 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
343 }
François Gaffie53615e22015-03-19 09:24:12 +0100344
Eric Laurent3a4311c2014-03-17 12:00:47 -0700345 DeviceVector *deviceVector;
346
Eric Laurente552edb2014-03-10 17:42:56 -0700347 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700348 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700349 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700350 deviceVector = &mAvailableInputDevices;
351 } else {
352 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
353 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700354 }
Eric Laurent634b7142016-04-20 13:48:02 -0700355
356 return (deviceVector->getDevice(device, String8(device_address)) != 0) ?
357 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800358}
359
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800360status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
361 const char *device_address,
362 const char *device_name)
363{
364 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700365 String8 reply;
366 AudioParameter param;
367 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800368
369 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s",
370 device, device_address, device_name);
371
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800372 // connect/disconnect only 1 device at a time
373 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
374
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800375 // Check if the device is currently connected
376 sp<DeviceDescriptor> devDesc =
377 mHwModules.getDeviceDescriptor(device, device_address, device_name);
378 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
379 if (index < 0) {
380 // Nothing to do: device is not connected
381 return NO_ERROR;
382 }
383
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700384 // For offloaded A2DP, Hw modules may have the capability to
385 // configure codecs. Check if any of the loaded hw modules
386 // supports this.
387 // If supported, send a set parameter to configure A2DP codecs
388 // and return. No need to toggle device state.
389 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
390 reply = mpClientInterface->getParameters(
391 AUDIO_IO_HANDLE_NONE,
392 String8(AudioParameter::keyReconfigA2dpSupported));
393 AudioParameter repliedParameters(reply);
394 repliedParameters.getInt(
395 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
396 if (isReconfigA2dpSupported) {
397 const String8 key(AudioParameter::keyReconfigA2dp);
398 param.add(key, String8("true"));
399 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
400 return NO_ERROR;
401 }
402 }
403
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800404 // Toggle the device state: UNAVAILABLE -> AVAILABLE
405 // This will force reading again the device configuration
406 status = setDeviceConnectionState(device,
407 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
408 device_address, device_name);
409 if (status != NO_ERROR) {
410 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
411 status);
412 return status;
413 }
414
415 status = setDeviceConnectionState(device,
416 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
417 device_address, device_name);
418 if (status != NO_ERROR) {
419 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
420 status);
421 return status;
422 }
423
424 return NO_ERROR;
425}
426
Eric Laurentdc462862016-07-19 12:29:53 -0700427uint32_t AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700428{
429 bool createTxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700430 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700431
Andy Hunga76c7de2016-12-13 19:14:31 -0800432 if(!hasPrimaryOutput() || mPrimaryOutput->device() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurentdc462862016-07-19 12:29:53 -0700433 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700434 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800435 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700436 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
437
438 // release existing RX patch if any
439 if (mCallRxPatch != 0) {
440 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
441 mCallRxPatch.clear();
442 }
443 // release TX patch if any
444 if (mCallTxPatch != 0) {
445 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
446 mCallTxPatch.clear();
447 }
448
449 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
450 // via setOutputDevice() on primary output.
451 // Otherwise, create two audio patches for TX and RX path.
452 if (availablePrimaryOutputDevices() & rxDevice) {
Eric Laurentdc462862016-07-19 12:29:53 -0700453 muteWaitMs = setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700454 // If the TX device is also on the primary HW module, setOutputDevice() will take care
455 // of it due to legacy implementation. If not, create a patch.
456 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
457 == AUDIO_DEVICE_NONE) {
458 createTxPatch = true;
459 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700460 } else { // create RX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800461 mCallRxPatch = createTelephonyPatch(true /*isRx*/, rxDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700462 createTxPatch = true;
463 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700464 if (createTxPatch) { // create TX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800465 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txDevice, delayMs);
466 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700467
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800468 return muteWaitMs;
469}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700470
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800471sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
472 bool isRx, audio_devices_t device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700473 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700474
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800475 sp<DeviceDescriptor> txSourceDeviceDesc;
476 if (isRx) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700477 patchBuilder.addSink(findDevice(mAvailableOutputDevices, device)).
478 addSource(findDevice(mAvailableInputDevices, AUDIO_DEVICE_IN_TELEPHONY_RX));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800479 } else {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700480 patchBuilder.addSource(txSourceDeviceDesc = findDevice(mAvailableInputDevices, device)).
481 addSink(findDevice(mAvailableOutputDevices, AUDIO_DEVICE_OUT_TELEPHONY_TX));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800482 }
483
484 audio_devices_t outputDevice = isRx ? device : AUDIO_DEVICE_OUT_TELEPHONY_TX;
485 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(outputDevice, mOutputs);
486 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
487 // request to reuse existing output stream if one is already opened to reach the target device
488 if (output != AUDIO_IO_HANDLE_NONE) {
489 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
490 ALOG_ASSERT(!outputDesc->isDuplicated(),
491 "%s() %#x device output %d is duplicated", __func__, outputDevice, output);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700492 patchBuilder.addSource(outputDesc, { .stream = AUDIO_STREAM_PATCH });
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800493 }
494
495 if (!isRx) {
Eric Laurentc0a889f2015-10-14 14:36:34 -0700496 // terminate active capture if on the same HW module as the call TX source device
497 // FIXME: would be better to refine to only inputs whose profile connects to the
498 // call TX device but this information is not in the audio patch and logic here must be
499 // symmetric to the one in startInput()
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800500 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800501 if (activeDesc->hasSameHwModuleAs(txSourceDeviceDesc)) {
Eric Laurent8f42ea12018-08-08 09:08:25 -0700502 closeActiveClients(activeDesc);
Eric Laurentc0a889f2015-10-14 14:36:34 -0700503 }
504 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700505 }
Eric Laurentdc462862016-07-19 12:29:53 -0700506
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800507 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Mikhail Naganovdc769682018-05-04 15:34:08 -0700508 status_t status = mpClientInterface->createAudioPatch(
509 patchBuilder.patch(), &afPatchHandle, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800510 ALOGW_IF(status != NO_ERROR,
511 "%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
512 sp<AudioPatch> audioPatch;
513 if (status == NO_ERROR) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700514 audioPatch = new AudioPatch(patchBuilder.patch(), mUidCached);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800515 audioPatch->mAfPatchHandle = afPatchHandle;
516 audioPatch->mUid = mUidCached;
517 }
518 return audioPatch;
519}
520
Mikhail Naganovdc769682018-05-04 15:34:08 -0700521sp<DeviceDescriptor> AudioPolicyManager::findDevice(
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100522 const DeviceVector& devices, audio_devices_t device) const {
Mikhail Naganov708e0382018-05-30 09:53:04 -0700523 DeviceVector deviceList = devices.getDevicesFromTypeMask(device);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800524 ALOG_ASSERT(!deviceList.isEmpty(),
525 "%s() selected device type %#x is not in devices list", __func__, device);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700526 return deviceList.itemAt(0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700527}
528
Eric Laurente0720872014-03-11 09:30:41 -0700529void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700530{
531 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100532 // store previous phone state for management of sonification strategy below
533 int oldState = mEngine->getPhoneState();
534
535 if (mEngine->setPhoneState(state) != NO_ERROR) {
536 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700537 return;
538 }
François Gaffie2110e042015-03-24 08:41:51 +0100539 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700540 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700541 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700542 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800543 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700544 }
545
François Gaffie2110e042015-03-24 08:41:51 +0100546 /**
547 * Switching to or from incall state or switching between telephony and VoIP lead to force
548 * routing command.
549 */
550 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
551 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700552
553 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700554 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700555
Eric Laurente552edb2014-03-10 17:42:56 -0700556 int delayMs = 0;
557 if (isStateInCall(state)) {
558 nsecs_t sysTime = systemTime();
559 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700560 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700561 // mute media and sonification strategies and delay device switch by the largest
562 // latency of any output where either strategy is active.
563 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100564 if ((isStrategyActive(desc, STRATEGY_MEDIA,
565 SONIFICATION_HEADSET_MUSIC_DELAY,
566 sysTime) ||
567 isStrategyActive(desc, STRATEGY_SONIFICATION,
568 SONIFICATION_HEADSET_MUSIC_DELAY,
569 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700570 (delayMs < (int)desc->latency()*2)) {
571 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700572 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700573 setStrategyMute(STRATEGY_MEDIA, true, desc);
574 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700575 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700576 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
577 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700578 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
579 }
580 }
581
Eric Laurent87ffa392015-05-22 10:32:38 -0700582 if (hasPrimaryOutput()) {
583 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
584 // the device returned is not necessarily reachable via this output
585 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
586 // force routing command to audio hardware when ending call
587 // even if no device change is needed
588 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
589 rxDevice = mPrimaryOutput->device();
590 }
Eric Laurente552edb2014-03-10 17:42:56 -0700591
Eric Laurent87ffa392015-05-22 10:32:38 -0700592 if (state == AUDIO_MODE_IN_CALL) {
593 updateCallRouting(rxDevice, delayMs);
594 } else if (oldState == AUDIO_MODE_IN_CALL) {
595 if (mCallRxPatch != 0) {
596 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
597 mCallRxPatch.clear();
598 }
599 if (mCallTxPatch != 0) {
600 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
601 mCallTxPatch.clear();
602 }
603 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
604 } else {
605 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700606 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700607 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700608
609 // reevaluate routing on all outputs in case tracks have been started during the call
610 for (size_t i = 0; i < mOutputs.size(); i++) {
611 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
612 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
613 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
Yung Ti Suf60c8242018-05-10 18:07:26 +0800614 setOutputDevice(desc, newDevice, (newDevice != AUDIO_DEVICE_NONE), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700615 }
616 }
617
Eric Laurente552edb2014-03-10 17:42:56 -0700618 if (isStateInCall(state)) {
619 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700620 // force reevaluating accessibility routing when call starts
621 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700622 }
623
624 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700625 if (state == AUDIO_MODE_RINGTONE &&
626 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700627 mLimitRingtoneVolume = true;
628 } else {
629 mLimitRingtoneVolume = false;
630 }
631}
632
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700633audio_mode_t AudioPolicyManager::getPhoneState() {
634 return mEngine->getPhoneState();
635}
636
Eric Laurente0720872014-03-11 09:30:41 -0700637void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700638 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700639{
François Gaffie2110e042015-03-24 08:41:51 +0100640 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700641 if (config == mEngine->getForceUse(usage)) {
642 return;
643 }
Eric Laurente552edb2014-03-10 17:42:56 -0700644
François Gaffie2110e042015-03-24 08:41:51 +0100645 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
646 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
647 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700648 }
François Gaffie2110e042015-03-24 08:41:51 +0100649 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
650 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
651 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700652
653 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700654 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800655
Eric Laurentdc462862016-07-19 12:29:53 -0700656 //FIXME: workaround for truncated touch sounds
657 // to be removed when the problem is handled by system UI
658 uint32_t delayMs = 0;
659 uint32_t waitMs = 0;
660 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
661 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
662 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700663 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700664 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
Eric Laurentdc462862016-07-19 12:29:53 -0700665 waitMs = updateCallRouting(newDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700666 }
Eric Laurente552edb2014-03-10 17:42:56 -0700667 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700668 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
669 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
670 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700671 waitMs = setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE),
672 delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700673 }
Eric Laurente552edb2014-03-10 17:42:56 -0700674 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700675 applyStreamVolumes(outputDesc, newDevice, waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700676 }
677 }
678
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800679 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800680 audio_devices_t newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700681 // Force new input selection if the new device can not be reached via current input
Eric Laurentfb66dd92016-01-28 18:32:03 -0800682 if (activeDesc->mProfile->getSupportedDevices().types() &
683 (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
684 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700685 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800686 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700687 }
Eric Laurente552edb2014-03-10 17:42:56 -0700688 }
Eric Laurente552edb2014-03-10 17:42:56 -0700689}
690
Eric Laurente0720872014-03-11 09:30:41 -0700691void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700692{
693 ALOGV("setSystemProperty() property %s, value %s", property, value);
694}
695
696// Find a direct output profile compatible with the parameters passed, even if the input flags do
697// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800698sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700699 audio_devices_t device,
700 uint32_t samplingRate,
701 audio_format_t format,
702 audio_channel_mask_t channelMask,
703 audio_output_flags_t flags)
704{
Eric Laurent861a6282015-05-18 15:40:16 -0700705 // only retain flags that will drive the direct output profile selection
706 // if explicitly requested
707 static const uint32_t kRelevantFlags =
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700708 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
709 AUDIO_OUTPUT_FLAG_VOIP_RX);
Eric Laurent861a6282015-05-18 15:40:16 -0700710 flags =
711 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
712
713 sp<IOProfile> profile;
714
Mikhail Naganovd4120142017-12-06 15:49:22 -0800715 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800716 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent861a6282015-05-18 15:40:16 -0700717 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700718 samplingRate, NULL /*updatedSamplingRate*/,
719 format, NULL /*updatedFormat*/,
720 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700721 flags)) {
722 continue;
723 }
724 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100725 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700726 continue;
727 }
728 // if several profiles are compatible, give priority to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100729 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700730 continue;
731 }
732 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100733 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700734 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700735 }
Eric Laurente552edb2014-03-10 17:42:56 -0700736 }
737 }
Eric Laurent861a6282015-05-18 15:40:16 -0700738 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700739}
740
Eric Laurentf4e63452017-11-06 19:31:46 +0000741audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700742{
Eric Laurent3b73df72014-03-11 09:06:29 -0700743 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700744 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800745
746 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
747 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
748 // format, flags, etc. This may result in some discrepancy for functions that utilize
749 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
750 // and AudioSystem::getOutputSamplingRate().
751
Eric Laurentf4e63452017-11-06 19:31:46 +0000752 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
753 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
Eric Laurente552edb2014-03-10 17:42:56 -0700754
Eric Laurentf4e63452017-11-06 19:31:46 +0000755 ALOGV("getOutput() stream %d selected device %08x, output %d", stream, device, output);
756 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700757}
758
Eric Laurente83b55d2014-11-14 10:06:21 -0800759status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
760 audio_io_handle_t *output,
761 audio_session_t session,
762 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700763 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800764 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200765 audio_output_flags_t *flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700766 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800767 audio_port_handle_t *portId)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700768{
Eric Laurente83b55d2014-11-14 10:06:21 -0800769 audio_attributes_t attributes;
Eric Laurent8fc147b2018-07-22 19:13:55 -0700770 DeviceVector outputDevices;
771 routing_strategy strategy;
772 audio_devices_t device;
Eric Laurent97ac8712018-07-27 18:59:02 -0700773 const audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100774 audio_devices_t msdDevice = getMsdAudioOutDeviceTypes();
Eric Laurent8fc147b2018-07-22 19:13:55 -0700775
Eric Laurent8f42ea12018-08-08 09:08:25 -0700776 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
777 if (*portId != AUDIO_PORT_HANDLE_NONE) {
778 return INVALID_OPERATION;
779 }
780
Eric Laurente83b55d2014-11-14 10:06:21 -0800781 if (attr != NULL) {
782 if (!isValidAttributes(attr)) {
783 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
784 attr->usage, attr->content_type, attr->flags,
785 attr->tags);
786 return BAD_VALUE;
787 }
788 attributes = *attr;
789 } else {
790 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
791 ALOGE("getOutputForAttr(): invalid stream type");
792 return BAD_VALUE;
793 }
794 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700795 }
Eric Laurent20b9ef02016-12-05 11:03:16 -0800796
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700797 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
Eric Laurent97ac8712018-07-27 18:59:02 -0700798 " session %d selectedDeviceId %d",
799 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
800 session, requestedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700801
Eric Laurent97ac8712018-07-27 18:59:02 -0700802 *stream = streamTypefromAttributesInt(&attributes);
803
804 strategy = getStrategyForAttr(&attributes);
805
Scott Randolph7b1fd232018-06-18 15:33:03 -0700806 // First check for explicit routing (eg. setPreferredDevice)
Eric Laurent97ac8712018-07-27 18:59:02 -0700807 if (requestedDeviceId != AUDIO_PORT_HANDLE_NONE) {
808 sp<DeviceDescriptor> deviceDesc =
809 mAvailableOutputDevices.getDeviceFromId(requestedDeviceId);
810 device = deviceDesc->type();
Scott Randolph7b1fd232018-06-18 15:33:03 -0700811 } else {
812 // If no explict route, is there a matching dynamic policy that applies?
813 sp<SwAudioOutputDescriptor> desc;
814 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
815 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
816 if (!audio_has_proportional_frames(config->format)) {
817 return BAD_VALUE;
818 }
819 *stream = streamTypefromAttributesInt(&attributes);
820 *output = desc->mIoHandle;
Eric Laurent97ac8712018-07-27 18:59:02 -0700821 AudioMix *mix = desc->mPolicyMix;
822 sp<DeviceDescriptor> deviceDesc =
823 mAvailableOutputDevices.getDevice(mix->mDeviceType, mix->mDeviceAddress);
824 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Scott Randolph7b1fd232018-06-18 15:33:03 -0700825 ALOGV("getOutputForAttr() returns output %d", *output);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700826 goto exit;
Scott Randolph7b1fd232018-06-18 15:33:03 -0700827 }
828
829 // Virtual sources must always be dynamicaly or explicitly routed
830 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
831 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
832 return BAD_VALUE;
833 }
Eric Laurent97ac8712018-07-27 18:59:02 -0700834 device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700835 }
Scott Randolph7b1fd232018-06-18 15:33:03 -0700836
Eric Laurente83b55d2014-11-14 10:06:21 -0800837 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200838 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -0700839 }
840
Nadav Barb2f18162018-07-18 13:01:53 +0300841 // Set incall music only if device was explicitly set, and fallback to the device which is
842 // chosen by the engine if not.
843 // FIXME: provide a more generic approach which is not device specific and move this back
844 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +0200845 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
Nadav Barb2f18162018-07-18 13:01:53 +0300846 if (device == AUDIO_DEVICE_OUT_TELEPHONY_TX &&
Nadav Bar20919492018-11-20 10:20:51 +0200847 (*stream == AUDIO_STREAM_MUSIC || attributes.usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +0300848 audio_is_linear_pcm(config->format) &&
849 isInCall()) {
Eric Laurent97ac8712018-07-27 18:59:02 -0700850 if (requestedDeviceId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +0300851 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
852 } else {
Eric Laurent97ac8712018-07-27 18:59:02 -0700853 // Get the devce type directly from the engine to bypass preferred route logic
Nadav Barb2f18162018-07-18 13:01:53 +0300854 device = mEngine->getDeviceForStrategy(strategy);
855 }
856 }
857
Glenn Kasten49f36ba2017-12-06 13:02:02 -0800858 ALOGV("getOutputForAttr() device 0x%x, sampling rate %d, format %#x, channel mask %#x, "
859 "flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +0200860 device, config->sample_rate, config->format, config->channel_mask, *flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700861
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100862 *output = AUDIO_IO_HANDLE_NONE;
863 if (msdDevice != AUDIO_DEVICE_NONE) {
864 *output = getOutputForDevice(msdDevice, session, *stream, config, flags);
865 if (*output != AUDIO_IO_HANDLE_NONE && setMsdPatch(device) == NO_ERROR) {
866 ALOGV("%s() Using MSD device 0x%x instead of device 0x%x",
867 __func__, msdDevice, device);
868 device = msdDevice;
869 } else {
870 *output = AUDIO_IO_HANDLE_NONE;
871 }
872 }
873 if (*output == AUDIO_IO_HANDLE_NONE) {
874 *output = getOutputForDevice(device, session, *stream, config, flags);
875 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800876 if (*output == AUDIO_IO_HANDLE_NONE) {
877 return INVALID_OPERATION;
878 }
Paul McLeanaa981192015-03-21 09:55:15 -0700879
Eric Laurent8fc147b2018-07-22 19:13:55 -0700880 outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -0700881 *selectedDeviceId = outputDevices.size() > 0 ? outputDevices.itemAt(0)->getId()
882 : AUDIO_PORT_HANDLE_NONE;
883
Eric Laurent8fc147b2018-07-22 19:13:55 -0700884exit:
885 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
886 .format = config->format,
887 .channel_mask = config->channel_mask };
Eric Laurent8f42ea12018-08-08 09:08:25 -0700888 *portId = AudioPort::getNextUniqueId();
889
Eric Laurent8fc147b2018-07-22 19:13:55 -0700890 sp<TrackClientDescriptor> clientDesc =
Eric Laurent97ac8712018-07-27 18:59:02 -0700891 new TrackClientDescriptor(*portId, uid, session, attributes, clientConfig,
892 requestedDeviceId, *stream,
893 getStrategyForAttr(&attributes),
894 *flags);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700895 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Andy Hung39efb7a2018-09-26 15:39:28 -0700896 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700897
898 ALOGV(" getOutputForAttr() returns output %d selectedDeviceId %d for port ID %d",
899 *output, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -0700900
Eric Laurente83b55d2014-11-14 10:06:21 -0800901 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700902}
903
904audio_io_handle_t AudioPolicyManager::getOutputForDevice(
905 audio_devices_t device,
Kevin Rocard169753c2017-03-06 14:18:23 -0800906 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700907 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -0800908 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200909 audio_output_flags_t *flags)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700910{
Andy Hungc88b0642018-04-27 15:42:35 -0700911 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700912 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700913
Eric Laurente552edb2014-03-10 17:42:56 -0700914 // open a direct output if required by specified parameters
915 //force direct flag if offload flag is set: offloading implies a direct output stream
916 // and all common behaviors are driven by checking only the direct flag
917 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +0200918 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
919 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700920 }
Nadav Bar766fb022018-01-07 12:18:03 +0200921 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
922 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -0700923 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800924 // only allow deep buffering for music stream type
925 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +0200926 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700927 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +0200928 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700929 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
930 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +0200931 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800932 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700933 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +0200934 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700935 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +0200936 audio_is_linear_pcm(config->format) &&
937 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200938 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700939 AUDIO_OUTPUT_FLAG_DIRECT);
940 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700941 }
Eric Laurente552edb2014-03-10 17:42:56 -0700942
Nadav Bar766fb022018-01-07 12:18:03 +0200943
Eric Laurentb732cf52014-09-24 19:08:21 -0700944 sp<IOProfile> profile;
945
946 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700947 // and not explicitly requested
Nadav Bar766fb022018-01-07 12:18:03 +0200948 if (((*flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Eric Laurentfe231122017-11-17 17:48:06 -0800949 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
950 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
Eric Laurentb732cf52014-09-24 19:08:21 -0700951 goto non_direct_output;
952 }
953
Andy Hung2ddee192015-12-18 17:34:44 -0800954 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
955 // This prevents creating an offloaded track and tearing it down immediately after start
956 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700957 // FIXME: We should check the audio session here but we do not have it in this context.
958 // This may prevent offloading in rare situations where effects are left active by apps
959 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700960
Nadav Bar766fb022018-01-07 12:18:03 +0200961 if (((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800962 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700963 profile = getProfileForDirectOutput(device,
Eric Laurentfe231122017-11-17 17:48:06 -0800964 config->sample_rate,
965 config->format,
966 config->channel_mask,
Nadav Bar766fb022018-01-07 12:18:03 +0200967 (audio_output_flags_t)*flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700968 }
969
Eric Laurent1c333e22014-05-20 10:48:17 -0700970 if (profile != 0) {
Andy Hungc88b0642018-04-27 15:42:35 -0700971 // exclusive outputs for MMAP and Offload are enforced by different session ids.
972 for (size_t i = 0; i < mOutputs.size(); i++) {
973 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
974 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
975 // reuse direct output if currently open by the same client
976 // and configured with same parameters
977 if ((config->sample_rate == desc->mSamplingRate) &&
Andy Hung5659ed52018-04-30 10:31:26 -0700978 (config->format == desc->mFormat) &&
Andy Hungc88b0642018-04-27 15:42:35 -0700979 (config->channel_mask == desc->mChannelMask) &&
980 (session == desc->mDirectClientSession)) {
981 desc->mDirectOpenCount++;
982 ALOGI("getOutputForDevice() reusing direct output %d for session %d",
983 mOutputs.keyAt(i), session);
984 return mOutputs.keyAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700985 }
986 }
987 }
Eric Laurent3974e3b2017-12-07 17:58:43 -0800988
989 if (!profile->canOpenNewIo()) {
990 goto non_direct_output;
Eric Laurente552edb2014-03-10 17:42:56 -0700991 }
Eric Laurent861a6282015-05-18 15:40:16 -0700992
Eric Laurent3974e3b2017-12-07 17:58:43 -0800993 sp<SwAudioOutputDescriptor> outputDesc =
994 new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurent53b810e2017-12-10 17:25:10 -0800995
Mikhail Naganov708e0382018-05-30 09:53:04 -0700996 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -0800997 String8 address = outputDevices.size() > 0 ? outputDevices.itemAt(0)->mAddress
998 : String8("");
999
Dean Wheatley3023b382018-08-09 07:42:40 +10001000 // MSD patch may be using the only output stream that can service this request. Release
1001 // MSD patch to prioritize this request over any active output on MSD.
1002 AudioPatchCollection msdPatches = getMsdPatches();
1003 for (size_t i = 0; i < msdPatches.size(); i++) {
1004 const auto& patch = msdPatches[i];
1005 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1006 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1007 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
1008 (sink->ext.device.type & device) != AUDIO_DEVICE_NONE &&
1009 (address.isEmpty() || strncmp(sink->ext.device.address, address.string(),
1010 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
1011 releaseAudioPatch(patch->mHandle, mUidCached);
1012 break;
1013 }
1014 }
1015 }
1016
Nadav Bar766fb022018-01-07 12:18:03 +02001017 status = outputDesc->open(config, device, address, stream, *flags, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07001018
1019 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001020 if (status != NO_ERROR ||
Eric Laurentfe231122017-11-17 17:48:06 -08001021 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
Andy Hung5659ed52018-04-30 10:31:26 -07001022 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->mFormat) ||
Eric Laurentfe231122017-11-17 17:48:06 -08001023 (config->channel_mask != 0 && config->channel_mask != outputDesc->mChannelMask)) {
1024 ALOGV("getOutputForDevice() failed opening direct output: output %d sample rate %d %d,"
1025 "format %d %d, channel mask %04x %04x", output, config->sample_rate,
1026 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
1027 config->channel_mask, outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001028 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001029 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07001030 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001031 // fall back to mixer output if possible when the direct output could not be open
Eric Laurentfe231122017-11-17 17:48:06 -08001032 if (audio_is_linear_pcm(config->format) &&
1033 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -08001034 goto non_direct_output;
1035 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001036 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001037 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001038 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -08001039 outputDesc->mDirectClientSession = session;
1040
Eric Laurente552edb2014-03-10 17:42:56 -07001041 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001042 mPreviousOutputs = mOutputs;
Eric Laurentf4e63452017-11-06 19:31:46 +00001043 ALOGV("getOutputForDevice() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001044 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001045 return output;
1046 }
1047
Eric Laurentb732cf52014-09-24 19:08:21 -07001048non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001049
1050 // A request for HW A/V sync cannot fallback to a mixed output because time
1051 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001052 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001053 return AUDIO_IO_HANDLE_NONE;
1054 }
1055
Eric Laurente552edb2014-03-10 17:42:56 -07001056 // ignoring channel mask due to downmix capability in mixer
1057
1058 // open a non direct output
1059
1060 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001061 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001062 // get which output is suitable for the specified stream. The actual
1063 // routing change will happen when startOutput() will be called
1064 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1065
Eric Laurent8838a382014-09-08 16:44:28 -07001066 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001067 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1068 output = selectOutput(outputs, *flags, config->format);
Eric Laurente552edb2014-03-10 17:42:56 -07001069 }
Eric Laurentf4e63452017-11-06 19:31:46 +00001070 ALOGW_IF((output == 0), "getOutputForDevice() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001071 "sampling rate %d, format %#x, channels %#x, flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +02001072 stream, config->sample_rate, config->format, config->channel_mask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001073
Eric Laurente552edb2014-03-10 17:42:56 -07001074 return output;
1075}
1076
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001077sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001078 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001079 if (msdModule != 0) {
1080 DeviceVector msdInputDevices = mAvailableInputDevices.getDevicesFromHwModule(
1081 msdModule->getHandle());
1082 if (!msdInputDevices.isEmpty()) return msdInputDevices.itemAt(0);
1083 }
1084 return 0;
1085}
1086
1087audio_devices_t AudioPolicyManager::getMsdAudioOutDeviceTypes() const {
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001088 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001089 if (msdModule != 0) {
1090 return mAvailableOutputDevices.getDeviceTypesFromHwModule(msdModule->getHandle());
1091 }
1092 return AUDIO_DEVICE_NONE;
1093}
1094
1095const AudioPatchCollection AudioPolicyManager::getMsdPatches() const {
1096 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001097 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1098 if (msdModule != 0) {
1099 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1100 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1101 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1102 const struct audio_port_config *source = &patch->mPatch.sources[j];
1103 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1104 source->ext.device.hw_module == msdModule->getHandle()) {
1105 msdPatches.addAudioPatch(patch->mHandle, patch);
1106 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001107 }
1108 }
1109 }
1110 return msdPatches;
1111}
1112
1113status_t AudioPolicyManager::getBestMsdAudioProfileFor(audio_devices_t outputDevice,
1114 bool hwAvSync, audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1115{
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001116 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001117 if (msdModule == nullptr) {
1118 ALOGE("%s() unable to get MSD module", __func__);
1119 return NO_INIT;
1120 }
1121 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(outputDevice);
1122 if (deviceModule == nullptr) {
1123 ALOGE("%s() unable to get module for %#x", __func__, outputDevice);
1124 return NO_INIT;
1125 }
1126 const InputProfileCollection &inputProfiles = msdModule->getInputProfiles();
1127 if (inputProfiles.isEmpty()) {
1128 ALOGE("%s() no input profiles for MSD module", __func__);
1129 return NO_INIT;
1130 }
1131 const OutputProfileCollection &outputProfiles = deviceModule->getOutputProfiles();
1132 if (outputProfiles.isEmpty()) {
1133 ALOGE("%s() no output profiles for device %#x", __func__, outputDevice);
1134 return NO_INIT;
1135 }
1136 AudioProfileVector msdProfiles;
1137 // Each IOProfile represents a MixPort from audio_policy_configuration.xml
1138 for (const auto &inProfile : inputProfiles) {
1139 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0)) {
1140 msdProfiles.appendVector(inProfile->getAudioProfiles());
1141 }
1142 }
1143 AudioProfileVector deviceProfiles;
1144 for (const auto &outProfile : outputProfiles) {
1145 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0)) {
1146 deviceProfiles.appendVector(outProfile->getAudioProfiles());
1147 }
1148 }
1149 struct audio_config_base bestSinkConfig;
1150 status_t result = msdProfiles.findBestMatchingOutputConfig(deviceProfiles,
1151 compressedFormatsOrder, surroundChannelMasksOrder, true /*preferHigherSamplingRates*/,
1152 &bestSinkConfig);
1153 if (result != NO_ERROR) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001154 ALOGD("%s() no matching profiles found for device: %#x, hwAvSync: %d",
1155 __func__, outputDevice, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001156 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001157 }
1158 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1159 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1160 sinkConfig->format = bestSinkConfig.format;
1161 // For encoded streams force direct flag to prevent downstream mixing.
1162 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1163 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
1164 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1165 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1166 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1167 sourceConfig->format = bestSinkConfig.format;
1168 // Copy input stream directly without any processing (e.g. resampling).
1169 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1170 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1171 if (hwAvSync) {
1172 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1173 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1174 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1175 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1176 }
1177 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1178 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1179 sinkConfig->config_mask |= config_mask;
1180 sourceConfig->config_mask |= config_mask;
1181 return NO_ERROR;
1182}
1183
1184PatchBuilder AudioPolicyManager::buildMsdPatch(audio_devices_t outputDevice) const
1185{
1186 PatchBuilder patchBuilder;
1187 patchBuilder.addSource(getMsdAudioInDevice()).
1188 addSink(findDevice(mAvailableOutputDevices, outputDevice));
1189 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1190 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
1191 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1192 // For now, we just forcefully try with HwAvSync first.
1193 status_t res = getBestMsdAudioProfileFor(outputDevice, true /*hwAvSync*/,
1194 &sourceConfig, &sinkConfig) == NO_ERROR ? NO_ERROR :
1195 getBestMsdAudioProfileFor(
1196 outputDevice, false /*hwAvSync*/, &sourceConfig, &sinkConfig);
1197 if (res == NO_ERROR) {
1198 // Found a matching profile for encoded audio. Re-create PatchBuilder with this config.
1199 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1200 }
1201 ALOGV("%s() no matching profile found. Fall through to default PCM patch"
1202 " supporting PCM format conversion.", __func__);
1203 return patchBuilder;
1204}
1205
1206status_t AudioPolicyManager::setMsdPatch(audio_devices_t outputDevice) {
1207 ALOGV("%s() for outputDevice %#x", __func__, outputDevice);
1208 if (outputDevice == AUDIO_DEVICE_NONE) {
1209 // Use media strategy for unspecified output device. This should only
1210 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1211 // therefore invalidate explicit routing requests.
1212 outputDevice = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
1213 }
1214 PatchBuilder patchBuilder = buildMsdPatch(outputDevice);
1215 const struct audio_patch* patch = patchBuilder.patch();
1216 const AudioPatchCollection msdPatches = getMsdPatches();
1217 if (!msdPatches.isEmpty()) {
1218 LOG_ALWAYS_FATAL_IF(msdPatches.size() > 1,
1219 "The current MSD prototype only supports one output patch");
1220 sp<AudioPatch> currentPatch = msdPatches.valueAt(0);
1221 if (audio_patches_are_equal(&currentPatch->mPatch, patch)) {
1222 return NO_ERROR;
1223 }
1224 releaseAudioPatch(currentPatch->mHandle, mUidCached);
1225 }
1226 status_t status = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1227 patch, 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1228 ALOGE_IF(status != NO_ERROR, "%s() error %d creating MSD audio patch", __func__, status);
1229 ALOGI_IF(status == NO_ERROR, "%s() Patch created from MSD_IN to "
1230 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__, outputDevice,
1231 patch->sources[0].format, patch->sources[0].channel_mask, patch->sources[0].sample_rate);
1232 return status;
1233}
1234
Eric Laurente0720872014-03-11 09:30:41 -07001235audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001236 audio_output_flags_t flags,
1237 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001238{
1239 // select one output among several that provide a path to a particular device or set of
1240 // devices (the list was previously build by getOutputsForDevice()).
1241 // The priority is as follows:
1242 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001243 // 2: the output with the bit depth the closest to the requested one
1244 // 3: the primary output
1245 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001246
1247 if (outputs.size() == 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001248 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001249 }
1250 if (outputs.size() == 1) {
1251 return outputs[0];
1252 }
1253
1254 int maxCommonFlags = 0;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001255 audio_io_handle_t outputForFlags = AUDIO_IO_HANDLE_NONE;
1256 audio_io_handle_t outputForPrimary = AUDIO_IO_HANDLE_NONE;
1257 audio_io_handle_t outputForFormat = AUDIO_IO_HANDLE_NONE;
Eric Laurente6930022016-02-11 10:20:40 -08001258 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1259 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001260
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001261 for (audio_io_handle_t output : outputs) {
1262 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001263 if (!outputDesc->isDuplicated()) {
chenhg1794d712018-10-09 15:20:37 -07001264 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1265 continue;
1266 }
Eric Laurent8838a382014-09-08 16:44:28 -07001267 // if a valid format is specified, skip output if not compatible
1268 if (format != AUDIO_FORMAT_INVALID) {
chenhg1794d712018-10-09 15:20:37 -07001269 if (!audio_is_linear_pcm(format)) {
Eric Laurent8838a382014-09-08 16:44:28 -07001270 continue;
1271 }
Eric Laurente6930022016-02-11 10:20:40 -08001272 if (AudioPort::isBetterFormatMatch(
1273 outputDesc->mFormat, bestFormat, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001274 outputForFormat = output;
Eric Laurente6930022016-02-11 10:20:40 -08001275 bestFormat = outputDesc->mFormat;
1276 }
Eric Laurent8838a382014-09-08 16:44:28 -07001277 }
1278
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001279 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001280 if (commonFlags >= maxCommonFlags) {
1281 if (commonFlags == maxCommonFlags) {
Andy Hungc9901522017-11-10 20:07:54 -08001282 if (format != AUDIO_FORMAT_INVALID
1283 && AudioPort::isBetterFormatMatch(
1284 outputDesc->mFormat, bestFormatForFlags, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001285 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001286 bestFormatForFlags = outputDesc->mFormat;
1287 }
1288 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001289 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001290 maxCommonFlags = commonFlags;
1291 bestFormatForFlags = outputDesc->mFormat;
1292 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001293 ALOGV("selectOutput() commonFlags for output %d, %04x", output, commonFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001294 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001295 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001296 outputForPrimary = output;
Eric Laurente552edb2014-03-10 17:42:56 -07001297 }
1298 }
1299 }
1300
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001301 if (outputForFlags != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001302 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001303 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001304 if (outputForFormat != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001305 return outputForFormat;
1306 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001307 if (outputForPrimary != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001308 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001309 }
1310
1311 return outputs[0];
1312}
1313
Eric Laurent8fc147b2018-07-22 19:13:55 -07001314status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001315{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001316 ALOGV("%s portId %d", __FUNCTION__, portId);
1317
1318 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1319 if (outputDesc == 0) {
1320 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001321 return BAD_VALUE;
1322 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001323 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001324
Eric Laurent8fc147b2018-07-22 19:13:55 -07001325 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001326 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001327
Eric Laurent733ce942017-12-07 12:18:25 -08001328 status_t status = outputDesc->start();
1329 if (status != NO_ERROR) {
1330 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001331 }
1332
Eric Laurent97ac8712018-07-27 18:59:02 -07001333 uint32_t delayMs;
1334 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001335
1336 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001337 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001338 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001339 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001340 if (delayMs != 0) {
1341 usleep(delayMs * 1000);
1342 }
1343
1344 return status;
1345}
1346
Eric Laurent97ac8712018-07-27 18:59:02 -07001347status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1348 const sp<TrackClientDescriptor>& client,
1349 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001350{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001351 // cannot start playback of STREAM_TTS if any other output is being used
1352 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001353
1354 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001355 audio_stream_type_t stream = client->stream();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001356 if (stream == AUDIO_STREAM_TTS) {
1357 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001358 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001359 return INVALID_OPERATION;
1360 } else {
1361 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1362 }
1363 } else {
1364 // some playback other than beacon starts
1365 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1366 }
1367
Eric Laurent77305a62016-07-25 16:39:22 -07001368 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001369 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001370 bool force = !outputDesc->isActive() &&
1371 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001372
Eric Laurent97ac8712018-07-27 18:59:02 -07001373 audio_devices_t device = AUDIO_DEVICE_NONE;
1374 AudioMix *policyMix = NULL;
1375 const char *address = NULL;
1376 if (outputDesc->mPolicyMix != NULL) {
1377 policyMix = outputDesc->mPolicyMix;
1378 address = policyMix->mDeviceAddress.string();
1379 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1380 device = policyMix->mDeviceType;
1381 } else {
1382 device = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1383 }
1384 }
1385
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001386 // requiresMuteCheck is false when we can bypass mute strategy.
1387 // It covers a common case when there is no materially active audio
1388 // and muting would result in unnecessary delay and dropped audio.
1389 const uint32_t outputLatencyMs = outputDesc->latency();
1390 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1391
Eric Laurente552edb2014-03-10 17:42:56 -07001392 // increment usage count for this stream on the requested output:
1393 // NOTE that the usage count is the same for duplicated output and hardware output which is
1394 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001395 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001396
1397 if (client->hasPreferredDevice(true)) {
1398 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
1399 if (device != outputDesc->device()) {
1400 checkStrategyRoute(getStrategy(stream), outputDesc->mIoHandle);
1401 }
1402 }
Eric Laurente552edb2014-03-10 17:42:56 -07001403
Eric Laurent36829f92017-04-07 19:04:42 -07001404 if (stream == AUDIO_STREAM_MUSIC) {
1405 selectOutputForMusicEffects();
1406 }
1407
Eric Laurent592dd7b2018-08-05 18:58:48 -07001408 if (outputDesc->streamActiveCount(stream) == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001409 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001410 if (device == AUDIO_DEVICE_NONE) {
1411 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001412 }
Eric Laurent36829f92017-04-07 19:04:42 -07001413
Eric Laurente552edb2014-03-10 17:42:56 -07001414 routing_strategy strategy = getStrategy(stream);
1415 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001416 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1417 (beaconMuteLatency > 0);
1418 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001419 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001420 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001421 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001422 // An output has a shared device if
1423 // - managed by the same hw module
1424 // - supports the currently selected device
1425 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
1426 && (desc->supportedDevices() & device) != AUDIO_DEVICE_NONE;
1427
Eric Laurent77305a62016-07-25 16:39:22 -07001428 // force a device change if any other output is:
1429 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001430 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001431 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001432 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001433 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001434 // change the device currently selected by the other output.
1435 if (sharedDevice &&
Eric Laurent77305a62016-07-25 16:39:22 -07001436 desc->device() != device &&
Eric Laurent77305a62016-07-25 16:39:22 -07001437 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001438 force = true;
1439 }
1440 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001441 // a notification so that audio focus effect can propagate, or that a mute/unmute
1442 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001443 const uint32_t latencyMs = desc->latency();
1444 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1445
1446 if (shouldWait && isActive && (waitMs < latencyMs)) {
1447 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001448 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001449
1450 // Require mute check if another output is on a shared device
1451 // and currently active to have proper drain and avoid pops.
1452 // Note restoring AudioTracks onto this output needs to invoke
1453 // a volume ramp if there is no mute.
1454 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001455 }
1456 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001457
1458 const uint32_t muteWaitMs =
1459 setOutputDevice(outputDesc, device, force, 0, NULL, address, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001460
Eric Laurente552edb2014-03-10 17:42:56 -07001461 // apply volume rules for current stream and device if necessary
1462 checkAndSetVolume(stream,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001463 mVolumeCurves->getVolumeIndex(stream, outputDesc->device()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001464 outputDesc,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001465 outputDesc->device());
Eric Laurente552edb2014-03-10 17:42:56 -07001466
1467 // update the outputs if starting an output with a stream that can affect notification
1468 // routing
1469 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001470
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001471 // force reevaluating accessibility routing when ringtone or alarm starts
1472 if (strategy == STRATEGY_SONIFICATION) {
1473 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1474 }
Eric Laurentdc462862016-07-19 12:29:53 -07001475
1476 if (waitMs > muteWaitMs) {
1477 *delayMs = waitMs - muteWaitMs;
1478 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001479
1480 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1481 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1482 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1483 // change occurs after the MixerThread starts and causes a stream volume
1484 // glitch.
1485 //
1486 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001487 }
Eric Laurentdc462862016-07-19 12:29:53 -07001488
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001489 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1490 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1491 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1492 }
1493
Eric Laurent97ac8712018-07-27 18:59:02 -07001494 // Automatically enable the remote submix input when output is started on a re routing mix
1495 // of type MIX_TYPE_RECORDERS
1496 if (audio_is_remote_submix_device(device) && policyMix != NULL &&
1497 policyMix->mMixType == MIX_TYPE_RECORDERS) {
1498 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1499 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1500 address,
1501 "remote-submix");
1502 }
1503
Eric Laurente552edb2014-03-10 17:42:56 -07001504 return NO_ERROR;
1505}
1506
Eric Laurent8fc147b2018-07-22 19:13:55 -07001507status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001508{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001509 ALOGV("%s portId %d", __FUNCTION__, portId);
1510
1511 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1512 if (outputDesc == 0) {
1513 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001514 return BAD_VALUE;
1515 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001516 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001517
Eric Laurent97ac8712018-07-27 18:59:02 -07001518 ALOGV("stopOutput() output %d, stream %d, session %d",
1519 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07001520
Eric Laurent97ac8712018-07-27 18:59:02 -07001521 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08001522
Eric Laurent733ce942017-12-07 12:18:25 -08001523 if (status == NO_ERROR ) {
1524 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001525 }
1526 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001527}
1528
Eric Laurent97ac8712018-07-27 18:59:02 -07001529status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1530 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07001531{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001532 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07001533 audio_stream_type_t stream = client->stream();
1534
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001535 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1536
Eric Laurent592dd7b2018-08-05 18:58:48 -07001537 if (outputDesc->streamActiveCount(stream) > 0) {
1538 if (outputDesc->streamActiveCount(stream) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001539 // Automatically disable the remote submix input when output is stopped on a
1540 // re routing mix of type MIX_TYPE_RECORDERS
1541 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1542 outputDesc->mPolicyMix != NULL &&
1543 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1544 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1545 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1546 outputDesc->mPolicyMix->mDeviceAddress,
1547 "remote-submix");
1548 }
1549 }
1550 bool forceDeviceUpdate = false;
1551 if (client->hasPreferredDevice(true)) {
1552 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1553 forceDeviceUpdate = true;
1554 }
1555
Eric Laurente552edb2014-03-10 17:42:56 -07001556 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07001557 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07001558
Eric Laurente552edb2014-03-10 17:42:56 -07001559 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001560 if (outputDesc->streamActiveCount(stream) == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001561 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001562 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001563 // delay the device switch by twice the latency because stopOutput() is executed when
1564 // the track stop() command is received and at that time the audio track buffer can
1565 // still contain data that needs to be drained. The latency only covers the audio HAL
1566 // and kernel buffers. Also the latency does not always include additional delay in the
1567 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001568 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001569
1570 // force restoring the device selection on other active outputs if it differs from the
1571 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001572 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001573 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001574 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001575 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001576 desc->isActive() &&
1577 outputDesc->sharesHwModuleWith(desc) &&
1578 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001579 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1580 bool force = desc->device() != newDevice2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001581
Eric Laurentc75307b2015-03-17 15:29:32 -07001582 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001583 newDevice2,
1584 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001585 delayMs);
1586 // re-apply device specific volume if not done by setOutputDevice()
1587 if (!force) {
1588 applyStreamVolumes(desc, newDevice2, delayMs);
1589 }
Eric Laurente552edb2014-03-10 17:42:56 -07001590 }
1591 }
1592 // update the outputs if stopping one with a stream that can affect notification routing
1593 handleNotificationRoutingForStream(stream);
1594 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001595
1596 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1597 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1598 setStrategyMute(STRATEGY_SONIFICATION, false, outputDesc);
1599 }
1600
Eric Laurent36829f92017-04-07 19:04:42 -07001601 if (stream == AUDIO_STREAM_MUSIC) {
1602 selectOutputForMusicEffects();
1603 }
Eric Laurente552edb2014-03-10 17:42:56 -07001604 return NO_ERROR;
1605 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001606 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001607 return INVALID_OPERATION;
1608 }
1609}
1610
Eric Laurent8fc147b2018-07-22 19:13:55 -07001611void AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001612{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001613 ALOGV("%s portId %d", __FUNCTION__, portId);
1614
1615 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1616 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07001617 // If an output descriptor is closed due to a device routing change,
1618 // then there are race conditions with releaseOutput from tracks
1619 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
1620 // destroyed shortly thereafter.
1621 //
1622 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07001623 ALOGW("releaseOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001624 return;
1625 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001626
1627 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001628
Eric Laurent8fc147b2018-07-22 19:13:55 -07001629 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1630 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001631 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07001632 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001633 return;
1634 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001635 if (--outputDesc->mDirectOpenCount == 0) {
1636 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07001637 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001638 }
1639 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001640 // stopOutput() needs to be successfully called before releaseOutput()
1641 // otherwise there may be inaccurate stream reference counts.
1642 // This is checked in outputDesc->removeClient below.
1643 outputDesc->removeClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001644}
1645
Eric Laurentcaf7f482014-11-25 17:50:47 -08001646status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1647 audio_io_handle_t *input,
1648 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001649 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001650 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001651 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001652 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001653 input_type_t *inputType,
1654 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001655{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001656 ALOGV("getInputForAttr() source %d, sampling rate %d, format %#x, channel mask %#x,"
Eric Laurentcaf7f482014-11-25 17:50:47 -08001657 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001658 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001659
Eric Laurentad2e7b92017-09-14 20:06:42 -07001660 status_t status = NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -08001661 // handle legacy remote submix case where the address was not always specified
1662 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001663 audio_source_t halInputSource;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001664 audio_source_t inputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001665 AudioMix *policyMix = NULL;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001666 DeviceVector inputDevices;
Eric Laurent8fc147b2018-07-22 19:13:55 -07001667 sp<AudioInputDescriptor> inputDesc;
1668 sp<RecordClientDescriptor> clientDesc;
1669 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001670 bool isSoundTrigger;
1671 audio_devices_t device;
1672
1673 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1674 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1675 return INVALID_OPERATION;
1676 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001677
Eric Laurentfe231122017-11-17 17:48:06 -08001678 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1679 inputSource = AUDIO_SOURCE_MIC;
1680 }
1681
Paul McLean466dc8e2015-04-17 13:15:36 -06001682 // Explicit routing?
1683 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -07001684 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
jiabinc0c831a2018-01-29 17:55:15 -08001685 deviceDesc = mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001686 }
Paul McLean466dc8e2015-04-17 13:15:36 -06001687
Eric Laurentad2e7b92017-09-14 20:06:42 -07001688 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1689 // possible
1690 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1691 *input != AUDIO_IO_HANDLE_NONE) {
1692 ssize_t index = mInputs.indexOfKey(*input);
1693 if (index < 0) {
1694 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1695 status = BAD_VALUE;
1696 goto error;
1697 }
1698 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001699 RecordClientVector clients = inputDesc->getClientsForSession(session);
1700 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001701 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1702 status = BAD_VALUE;
1703 goto error;
1704 }
1705 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1706 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001707 // corresponds to a new client and is only permitted from the same UID.
1708 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07001709 if (clients.size() > 1) {
1710 for (const auto& client : clients) {
1711 // The client map is ordered by key values (portId) and portIds are allocated
1712 // incrementaly. So the first client in this list is the one opened by audio flinger
1713 // when the mmap stream is created and should be ignored as it does not correspond
1714 // to an actual client
1715 if (client == *clients.cbegin()) {
1716 continue;
1717 }
1718 if (uid != client->uid() && !client->isSilenced()) {
1719 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
1720 uid, client->portId(), client->uid());
1721 status = INVALID_OPERATION;
1722 goto error;
1723 }
Eric Laurent331679c2018-04-16 17:03:16 -07001724 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001725 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001726 *inputType = API_INPUT_LEGACY;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001727 device = inputDesc->mDevice;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001728
Eric Laurent8f42ea12018-08-08 09:08:25 -07001729 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001730 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001731 }
1732
1733 *input = AUDIO_IO_HANDLE_NONE;
1734 *inputType = API_INPUT_INVALID;
1735
Eric Laurentad2e7b92017-09-14 20:06:42 -07001736 halInputSource = inputSource;
1737
Eric Laurentc447ded2015-01-06 08:47:05 -08001738 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001739 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001740 status = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
1741 if (status != NO_ERROR) {
1742 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001743 }
1744 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001745 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1746 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001747 } else {
Eric Laurent97ac8712018-07-27 18:59:02 -07001748 if (deviceDesc != 0) {
1749 device = deviceDesc->type();
1750 } else {
1751 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
1752 }
Eric Laurent275e8e92014-11-30 15:14:47 -08001753 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001754 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001755 status = BAD_VALUE;
1756 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001757 }
Eric Laurentc722f302014-12-10 11:21:49 -08001758 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001759 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001760 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1761 // there is an external policy, but this input is attached to a mix of recorders,
1762 // meaning it receives audio injected into the framework, so the recorder doesn't
1763 // know about it and is therefore considered "legacy"
1764 *inputType = API_INPUT_LEGACY;
1765 } else {
1766 // recording a mix of players defined by an external policy, we're rerouting for
1767 // an external policy
1768 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1769 }
Eric Laurentc722f302014-12-10 11:21:49 -08001770 } else if (audio_is_remote_submix_device(device)) {
1771 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001772 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001773 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1774 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001775 } else {
1776 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001777 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001778
Eric Laurent599c7582015-12-07 18:05:55 -08001779 }
1780
Eric Laurent8f42ea12018-08-08 09:08:25 -07001781 *input = getInputForDevice(device, address, session, inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001782 config, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001783 policyMix);
1784 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001785 status = INVALID_OPERATION;
1786 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001787 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001788
Eric Laurent8f42ea12018-08-08 09:08:25 -07001789exit:
1790
Mikhail Naganov708e0382018-05-30 09:53:04 -07001791 inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -07001792 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
Eric Laurent8f42ea12018-08-08 09:08:25 -07001793 : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07001794
Eric Laurent8f42ea12018-08-08 09:08:25 -07001795 isSoundTrigger = inputSource == AUDIO_SOURCE_HOTWORD &&
1796 mSoundTriggerSessions.indexOfKey(session) > 0;
1797 *portId = AudioPort::getNextUniqueId();
1798
Eric Laurent8fc147b2018-07-22 19:13:55 -07001799 clientDesc = new RecordClientDescriptor(*portId, uid, session,
Eric Laurent8f42ea12018-08-08 09:08:25 -07001800 *attr, *config, requestedDeviceId,
1801 inputSource,flags, isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001802 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07001803 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001804
1805 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
1806 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001807
Eric Laurent599c7582015-12-07 18:05:55 -08001808 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001809
1810error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07001811 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001812}
1813
1814
1815audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1816 String8 address,
1817 audio_session_t session,
Eric Laurent599c7582015-12-07 18:05:55 -08001818 audio_source_t inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001819 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08001820 audio_input_flags_t flags,
1821 AudioMix *policyMix)
1822{
1823 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1824 audio_source_t halInputSource = inputSource;
1825 bool isSoundTrigger = false;
1826
1827 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1828 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1829 if (index >= 0) {
1830 input = mSoundTriggerSessions.valueFor(session);
1831 isSoundTrigger = true;
1832 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1833 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1834 } else {
1835 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001836 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001837 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08001838 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001839 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001840 }
1841
Andy Hungf129b032015-04-07 13:45:50 -07001842 // find a compatible input profile (not necessarily identical in parameters)
1843 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08001844 // sampling rate and flags may be updated by getInputProfile
1845 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
1846 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07001847 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08001848 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07001849 audio_input_flags_t profileFlags = flags;
1850 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07001851 profileFormat = config->format; // reset each time through loop, in case it is updated
Eric Laurent275e8e92014-11-30 15:14:47 -08001852 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001853 profileSamplingRate, profileFormat, profileChannelMask,
1854 profileFlags);
1855 if (profile != 0) {
1856 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001857 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1858 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001859 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1860 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1861 } else { // fail
Glenn Kastenfaa10a62017-05-25 15:52:05 -07001862 ALOGW("getInputForDevice() could not find profile for device 0x%X, "
Eric Laurentfe231122017-11-17 17:48:06 -08001863 "sampling rate %u, format %#x, channel mask 0x%X, flags %#x",
1864 device, config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001865 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001866 }
Eric Laurente552edb2014-03-10 17:42:56 -07001867 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001868 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08001869 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08001870 if (samplingRate == 0) {
1871 samplingRate = profileSamplingRate;
1872 }
Eric Laurente552edb2014-03-10 17:42:56 -07001873
Eric Laurent322b4d22015-04-03 15:57:54 -07001874 if (profile->getModuleHandle() == 0) {
1875 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001876 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001877 }
1878
Eric Laurent3974e3b2017-12-07 17:58:43 -08001879 if (!profile->canOpenNewIo()) {
Eric Laurentdf628922018-12-06 21:45:51 +00001880 return AUDIO_IO_HANDLE_NONE;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001881 }
1882
Eric Laurentfe231122017-11-17 17:48:06 -08001883 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001884
Eric Laurentfe231122017-11-17 17:48:06 -08001885 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
1886 lConfig.sample_rate = profileSamplingRate;
1887 lConfig.channel_mask = profileChannelMask;
1888 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07001889
Eric Laurent53b810e2017-12-10 17:25:10 -08001890 if (address == "") {
Mikhail Naganov708e0382018-05-30 09:53:04 -07001891 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -08001892 // the inputs vector must be of size >= 1, but we don't want to crash here
1893 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress : String8("");
1894 }
1895
Eric Laurentfe231122017-11-17 17:48:06 -08001896 status_t status = inputDesc->open(&lConfig, device, address,
1897 halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001898
1899 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001900 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08001901 (profileSamplingRate != lConfig.sample_rate) ||
1902 !audio_formats_match(profileFormat, lConfig.format) ||
1903 (profileChannelMask != lConfig.channel_mask)) {
1904 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001905 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08001906 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001907 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001908 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07001909 }
Eric Laurent599c7582015-12-07 18:05:55 -08001910 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001911 }
1912
Eric Laurentc722f302014-12-10 11:21:49 -08001913 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001914
Eric Laurent599c7582015-12-07 18:05:55 -08001915 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001916 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001917
Eric Laurent599c7582015-12-07 18:05:55 -08001918 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001919}
1920
Eric Laurentdf628922018-12-06 21:45:51 +00001921//static
1922bool AudioPolicyManager::isConcurrentSource(audio_source_t source)
Eric Laurentbb948092017-01-23 18:33:30 -08001923{
Eric Laurentdf628922018-12-06 21:45:51 +00001924 return (source == AUDIO_SOURCE_HOTWORD) ||
1925 (source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
1926 (source == AUDIO_SOURCE_FM_TUNER);
1927}
1928
1929// FIXME: remove when concurrent capture is ready. This is a hack to work around bug b/63083537.
1930bool AudioPolicyManager::soundTriggerSupportsConcurrentCapture() {
1931 if (!mHasComputedSoundTriggerSupportsConcurrentCapture) {
1932 bool soundTriggerSupportsConcurrentCapture = false;
1933 unsigned int numModules = 0;
1934 struct sound_trigger_module_descriptor* nModules = NULL;
1935
1936 status_t status = SoundTrigger::listModules(nModules, &numModules);
1937 if (status == NO_ERROR && numModules != 0) {
1938 nModules = (struct sound_trigger_module_descriptor*) calloc(
1939 numModules, sizeof(struct sound_trigger_module_descriptor));
1940 if (nModules == NULL) {
1941 // We failed to malloc the buffer, so just say no for now, and hope that we have more
1942 // ram the next time this function is called.
1943 ALOGE("Failed to allocate buffer for module descriptors");
1944 return false;
1945 }
1946
1947 status = SoundTrigger::listModules(nModules, &numModules);
1948 if (status == NO_ERROR) {
1949 soundTriggerSupportsConcurrentCapture = true;
1950 for (size_t i = 0; i < numModules; ++i) {
1951 soundTriggerSupportsConcurrentCapture &=
1952 nModules[i].properties.concurrent_capture;
1953 }
1954 }
1955 free(nModules);
1956 }
1957 mSoundTriggerSupportsConcurrentCapture = soundTriggerSupportsConcurrentCapture;
1958 mHasComputedSoundTriggerSupportsConcurrentCapture = true;
1959 }
1960 return mSoundTriggerSupportsConcurrentCapture;
1961}
1962
1963
1964status_t AudioPolicyManager::startInput(audio_port_handle_t portId,
1965 bool silenced,
1966 concurrency_type__mask_t *concurrency)
1967{
1968 *concurrency = API_INPUT_CONCURRENCY_NONE;
1969
Eric Laurent8fc147b2018-07-22 19:13:55 -07001970 ALOGV("%s portId %d", __FUNCTION__, portId);
1971
1972 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
1973 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07001974 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001975 return BAD_VALUE;
1976 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001977 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07001978 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001979 if (client->active()) {
1980 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
1981 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07001982 }
1983
Eric Laurent8f42ea12018-08-08 09:08:25 -07001984 audio_session_t session = client->session();
1985
Eric Laurentdf628922018-12-06 21:45:51 +00001986 ALOGV("%s input:%d, session:%d, silenced:%d, concurrency:%d)",
1987 __FUNCTION__, input, session, silenced, *concurrency);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001988
Eric Laurentdf628922018-12-06 21:45:51 +00001989 if (!is_virtual_input_device(inputDesc->mDevice)) {
1990 if (mCallTxPatch != 0 &&
1991 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1992 ALOGW("startInput(%d) failed: call in progress", input);
1993 *concurrency |= API_INPUT_CONCURRENCY_CALL;
1994 return INVALID_OPERATION;
1995 }
Eric Laurent74708e72017-04-07 17:13:42 -07001996
Eric Laurentdf628922018-12-06 21:45:51 +00001997 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
1998
1999 // If a UID is idle and records silence and another not silenced recording starts
2000 // from another UID (idle or active) we stop the current idle UID recording in
2001 // favor of the new one - "There can be only one" TM
2002 if (!silenced) {
2003 for (const auto& activeDesc : activeInputs) {
2004 if ((activeDesc->getAudioPort()->getFlags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
2005 activeDesc->getId() == inputDesc->getId()) {
2006 continue;
2007 }
2008
2009 RecordClientVector activeClients = activeDesc->clientsList(true /*activeOnly*/);
2010 for (const auto& activeClient : activeClients) {
2011 if (activeClient->isSilenced()) {
2012 closeClient(activeClient->portId());
2013 ALOGV("%s client %d stopping silenced client %d", __FUNCTION__,
2014 portId, activeClient->portId());
2015 activeInputs = mInputs.getActiveInputs();
2016 }
2017 }
2018 }
2019 }
2020
2021 for (const auto& activeDesc : activeInputs) {
2022 if ((client->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
2023 activeDesc->getId() == inputDesc->getId()) {
2024 continue;
2025 }
2026
2027 audio_source_t activeSource = activeDesc->inputSource(true);
2028 if (client->source() == AUDIO_SOURCE_HOTWORD) {
2029 if (activeSource == AUDIO_SOURCE_HOTWORD) {
2030 if (activeDesc->hasPreemptedSession(session)) {
2031 ALOGW("%s input %d failed for HOTWORD: "
2032 "other input %d already started for HOTWORD", __FUNCTION__,
2033 input, activeDesc->mIoHandle);
2034 *concurrency |= API_INPUT_CONCURRENCY_HOTWORD;
2035 return INVALID_OPERATION;
2036 }
2037 } else {
2038 ALOGV("%s input %d failed for HOTWORD: other input %d already started",
2039 __FUNCTION__, input, activeDesc->mIoHandle);
2040 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
2041 return INVALID_OPERATION;
2042 }
2043 } else {
2044 if (activeSource != AUDIO_SOURCE_HOTWORD) {
2045 ALOGW("%s input %d failed: other input %d already started", __FUNCTION__,
2046 input, activeDesc->mIoHandle);
2047 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
2048 return INVALID_OPERATION;
2049 }
2050 }
2051 }
2052
2053 // We only need to check if the sound trigger session supports concurrent capture if the
2054 // input is also a sound trigger input. Otherwise, we should preempt any hotword stream
2055 // that's running.
2056 const bool allowConcurrentWithSoundTrigger =
2057 inputDesc->isSoundTrigger() ? soundTriggerSupportsConcurrentCapture() : false;
2058
2059 // if capture is allowed, preempt currently active HOTWORD captures
2060 for (const auto& activeDesc : activeInputs) {
2061 if (allowConcurrentWithSoundTrigger && activeDesc->isSoundTrigger()) {
2062 continue;
2063 }
2064 RecordClientVector activeHotwordClients =
2065 activeDesc->clientsList(true, AUDIO_SOURCE_HOTWORD);
2066 if (activeHotwordClients.size() > 0) {
2067 SortedVector<audio_session_t> sessions = activeDesc->getPreemptedSessions();
2068
2069 for (const auto& activeClient : activeHotwordClients) {
2070 *concurrency |= API_INPUT_CONCURRENCY_PREEMPT;
2071 sessions.add(activeClient->session());
2072 closeClient(activeClient->portId());
2073 ALOGV("%s input %d for HOTWORD preempting HOTWORD input %d", __FUNCTION__,
2074 input, activeDesc->mIoHandle);
2075 }
2076
2077 inputDesc->setPreemptedSessions(sessions);
2078 }
2079 }
Eric Laurent74708e72017-04-07 17:13:42 -07002080 }
Eric Laurente552edb2014-03-10 17:42:56 -07002081
Eric Laurentdf628922018-12-06 21:45:51 +00002082 // Make sure we start with the correct silence state
2083 client->setSilenced(silenced);
2084
2085 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002086 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002087 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002088
Eric Laurent8f42ea12018-08-08 09:08:25 -07002089 // indicate active capture to sound trigger service if starting capture from a mic on
2090 // primary HW module
2091 audio_devices_t device = getNewInputDevice(inputDesc);
2092 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002093
Eric Laurentdf628922018-12-06 21:45:51 +00002094 status_t status = inputDesc->start();
2095 if (status != NO_ERROR) {
2096 inputDesc->setClientActive(client, false);
2097 return status;
2098 }
2099
Eric Laurent8f42ea12018-08-08 09:08:25 -07002100 if (inputDesc->activeCount() == 1) {
2101 // if input maps to a dynamic policy with an activity listener, notify of state change
2102 if ((inputDesc->mPolicyMix != NULL)
2103 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2104 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2105 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002106 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002107
Eric Laurent8f42ea12018-08-08 09:08:25 -07002108 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2109 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2110 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
2111 SoundTrigger::setCaptureState(true);
2112 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002113
Eric Laurent8f42ea12018-08-08 09:08:25 -07002114 // automatically enable the remote submix output when input is started if not
2115 // used by a policy mix of type MIX_TYPE_RECORDERS
2116 // For remote submix (a virtual device), we open only one input per capture request.
2117 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2118 String8 address = String8("");
2119 if (inputDesc->mPolicyMix == NULL) {
2120 address = String8("0");
2121 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2122 address = inputDesc->mPolicyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002123 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002124 if (address != "") {
2125 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2126 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2127 address, "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08002128 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002129 }
Eric Laurente552edb2014-03-10 17:42:56 -07002130 }
2131
Eric Laurent8f42ea12018-08-08 09:08:25 -07002132 ALOGV("%s input %d source = %d exit", __FUNCTION__, input, client->source());
Eric Laurente552edb2014-03-10 17:42:56 -07002133
Eric Laurente552edb2014-03-10 17:42:56 -07002134 return NO_ERROR;
2135}
2136
Eric Laurent8fc147b2018-07-22 19:13:55 -07002137status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002138{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002139 ALOGV("%s portId %d", __FUNCTION__, portId);
2140
2141 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2142 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002143 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002144 return BAD_VALUE;
2145 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002146 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002147 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002148 if (!client->active()) {
2149 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002150 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002151 }
2152
Eric Laurent8f42ea12018-08-08 09:08:25 -07002153 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002154
Eric Laurent8f42ea12018-08-08 09:08:25 -07002155 inputDesc->stop();
2156 if (inputDesc->isActive()) {
2157 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2158 } else {
2159 // if input maps to a dynamic policy with an activity listener, notify of state change
2160 if ((inputDesc->mPolicyMix != NULL)
2161 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2162 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2163 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002164 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002165
2166 // automatically disable the remote submix output when input is stopped if not
2167 // used by a policy mix of type MIX_TYPE_RECORDERS
2168 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2169 String8 address = String8("");
2170 if (inputDesc->mPolicyMix == NULL) {
2171 address = String8("0");
2172 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2173 address = inputDesc->mPolicyMix->mDeviceAddress;
2174 }
2175 if (address != "") {
2176 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2177 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2178 address, "remote-submix");
2179 }
2180 }
2181
2182 audio_devices_t device = inputDesc->mDevice;
2183 resetInputDevice(input);
2184
2185 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2186 // primary HW module
2187 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2188 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2189 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
2190 SoundTrigger::setCaptureState(false);
2191 }
2192 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002193 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002194 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002195}
2196
Eric Laurent8fc147b2018-07-22 19:13:55 -07002197void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002198{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002199 ALOGV("%s portId %d", __FUNCTION__, portId);
2200
2201 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2202 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002203 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002204 return;
2205 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002206 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002207 audio_io_handle_t input = inputDesc->mIoHandle;
2208
Eric Laurent8f42ea12018-08-08 09:08:25 -07002209 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002210
Andy Hung39efb7a2018-09-26 15:39:28 -07002211 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002212
Andy Hung39efb7a2018-09-26 15:39:28 -07002213 if (inputDesc->getClientCount() > 0) {
2214 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002215 return;
2216 }
2217
Eric Laurent05b90f82014-08-27 15:32:29 -07002218 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002219 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002220 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002221}
2222
Eric Laurent8f42ea12018-08-08 09:08:25 -07002223void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002224{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002225 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002226
2227 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002228 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002229 }
2230}
2231
Eric Laurent8f42ea12018-08-08 09:08:25 -07002232void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2233{
2234 stopInput(portId);
2235 releaseInput(portId);
2236}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002237
Eric Laurentd4692962014-05-05 18:13:44 -07002238void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002239 bool patchRemoved = false;
2240
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002241 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002242 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002243 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002244 if (patch_index >= 0) {
2245 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002246 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002247 mAudioPatches.removeItemsAt(patch_index);
2248 patchRemoved = true;
2249 }
Eric Laurentfe231122017-11-17 17:48:06 -08002250 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002251 }
2252 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002253 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002254 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002255
2256 if (patchRemoved) {
2257 mpClientInterface->onAudioPatchListUpdate();
2258 }
Eric Laurentd4692962014-05-05 18:13:44 -07002259}
2260
Eric Laurente0720872014-03-11 09:30:41 -07002261void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002262 int indexMin,
2263 int indexMax)
2264{
2265 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002266 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002267
2268 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002269 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2270 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002271 continue;
2272 }
2273 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002274 }
Eric Laurente552edb2014-03-10 17:42:56 -07002275}
2276
Eric Laurente0720872014-03-11 09:30:41 -07002277status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002278 int index,
2279 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002280{
2281
Nadav Bar7c605f62017-12-25 00:01:52 +02002282 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2283 // app that has MODIFY_PHONE_STATE permission.
2284 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
2285 !(stream == AUDIO_STREAM_VOICE_CALL && index == 0)) ||
François Gaffied1ab2bd2015-12-02 18:20:06 +01002286 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002287 return BAD_VALUE;
2288 }
2289 if (!audio_is_output_device(device)) {
2290 return BAD_VALUE;
2291 }
2292
2293 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002294 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002295
Eric Laurent1fd372e2016-04-06 14:23:53 -07002296 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002297 stream, device, index);
2298
Eric Laurent28d09f02016-03-08 10:43:05 -08002299 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002300 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2301 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002302 continue;
2303 }
2304 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2305 }
Eric Laurente552edb2014-03-10 17:42:56 -07002306
Eric Laurent1fd372e2016-04-06 14:23:53 -07002307 // update volume on all outputs and streams matching the following:
2308 // - The requested stream (or a stream matching for volume control) is active on the output
2309 // - The device (or devices) selected by the strategy corresponding to this stream includes
2310 // the requested device
2311 // - For non default requested device, currently selected device on the output is either the
2312 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002313 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2314 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002315 status_t status = NO_ERROR;
2316 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002317 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2318 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08002319 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
Eric Laurent3839bc02018-07-10 18:33:34 -07002320 if (!(streamsMatchForvolume(stream, (audio_stream_type_t)curStream))) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002321 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002322 }
Eric Laurentdcd4ab12018-06-29 17:45:13 -07002323 if (!(desc->isStreamActive((audio_stream_type_t)curStream) || isInCall())) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002324 continue;
2325 }
Eric Laurent794fde22016-03-11 09:50:45 -08002326 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002327 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2328 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002329 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2330 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002331 continue;
2332 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002333 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002334 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002335 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07002336 applyVolume = (curDevice & curStreamDevice) != 0;
2337 } else {
2338 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002339 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002340 }
Eric Laurent3839bc02018-07-10 18:33:34 -07002341 // rescale index before applying to curStream as ranges may be different for
2342 // stream and curStream
2343 int idx = rescaleVolumeIndex(index, stream, (audio_stream_type_t)curStream);
Eric Laurente76f29c2016-09-14 17:17:53 -07002344 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002345 //FIXME: workaround for truncated touch sounds
2346 // delayed volume change for system stream to be removed when the problem is
2347 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002348 status_t volStatus =
Eric Laurent3839bc02018-07-10 18:33:34 -07002349 checkAndSetVolume((audio_stream_type_t)curStream, idx, desc, curDevice,
Eric Laurentdc462862016-07-19 12:29:53 -07002350 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002351 if (volStatus != NO_ERROR) {
2352 status = volStatus;
2353 }
2354 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002355 }
Eric Laurente552edb2014-03-10 17:42:56 -07002356 }
2357 return status;
2358}
2359
Eric Laurente0720872014-03-11 09:30:41 -07002360status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002361 int *index,
2362 audio_devices_t device)
2363{
2364 if (index == NULL) {
2365 return BAD_VALUE;
2366 }
2367 if (!audio_is_output_device(device)) {
2368 return BAD_VALUE;
2369 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002370 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002371 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002372 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002373 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2374 }
François Gaffiedfd74092015-03-19 12:10:59 +01002375 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002376
François Gaffied1ab2bd2015-12-02 18:20:06 +01002377 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002378 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2379 return NO_ERROR;
2380}
2381
Eric Laurent36829f92017-04-07 19:04:42 -07002382audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002383{
2384 // select one output among several suitable for global effects.
2385 // The priority is as follows:
2386 // 1: An offloaded output. If the effect ends up not being offloadable,
2387 // AudioFlinger will invalidate the track and the offloaded output
2388 // will be closed causing the effect to be moved to a PCM output.
2389 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002390 // 3: The primary output
2391 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002392
Eric Laurent3b73df72014-03-11 09:06:29 -07002393 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002394 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent36829f92017-04-07 19:04:42 -07002395 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002396
Eric Laurent36829f92017-04-07 19:04:42 -07002397 if (outputs.size() == 0) {
2398 return AUDIO_IO_HANDLE_NONE;
2399 }
Eric Laurente552edb2014-03-10 17:42:56 -07002400
Eric Laurent36829f92017-04-07 19:04:42 -07002401 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2402 bool activeOnly = true;
2403
2404 while (output == AUDIO_IO_HANDLE_NONE) {
2405 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2406 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2407 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2408
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002409 for (audio_io_handle_t output : outputs) {
2410 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002411 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2412 continue;
2413 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002414 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2415 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002416 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002417 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002418 }
2419 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002420 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002421 }
2422 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002423 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002424 }
2425 }
2426 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2427 output = outputOffloaded;
2428 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2429 output = outputDeepBuffer;
2430 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2431 output = outputPrimary;
2432 } else {
2433 output = outputs[0];
2434 }
2435 activeOnly = false;
2436 }
2437
2438 if (output != mMusicEffectOutput) {
2439 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2440 mMusicEffectOutput = output;
2441 }
2442
2443 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002444 return output;
2445}
2446
Eric Laurent36829f92017-04-07 19:04:42 -07002447audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2448{
2449 return selectOutputForMusicEffects();
2450}
2451
Eric Laurente0720872014-03-11 09:30:41 -07002452status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002453 audio_io_handle_t io,
2454 uint32_t strategy,
2455 int session,
2456 int id)
2457{
2458 ssize_t index = mOutputs.indexOfKey(io);
2459 if (index < 0) {
2460 index = mInputs.indexOfKey(io);
2461 if (index < 0) {
2462 ALOGW("registerEffect() unknown io %d", io);
2463 return INVALID_OPERATION;
2464 }
2465 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002466 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002467}
2468
Eric Laurentc75307b2015-03-17 15:29:32 -07002469bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2470{
Eric Laurent28d09f02016-03-08 10:43:05 -08002471 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002472 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2473 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002474 continue;
2475 }
2476 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2477 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002478 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002479}
2480
2481bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2482{
2483 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2484}
2485
Eric Laurente0720872014-03-11 09:30:41 -07002486bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002487{
2488 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002489 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002490 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002491 return true;
2492 }
2493 }
2494 return false;
2495}
2496
Eric Laurent275e8e92014-11-30 15:14:47 -08002497// Register a list of custom mixes with their attributes and format.
2498// When a mix is registered, corresponding input and output profiles are
2499// added to the remote submix hw module. The profile contains only the
2500// parameters (sampling rate, format...) specified by the mix.
2501// The corresponding input remote submix device is also connected.
2502//
2503// When a remote submix device is connected, the address is checked to select the
2504// appropriate profile and the corresponding input or output stream is opened.
2505//
2506// When capture starts, getInputForAttr() will:
2507// - 1 look for a mix matching the address passed in attribtutes tags if any
2508// - 2 if none found, getDeviceForInputSource() will:
2509// - 2.1 look for a mix matching the attributes source
2510// - 2.2 if none found, default to device selection by policy rules
2511// At this time, the corresponding output remote submix device is also connected
2512// and active playback use cases can be transferred to this mix if needed when reconnecting
2513// after AudioTracks are invalidated
2514//
2515// When playback starts, getOutputForAttr() will:
2516// - 1 look for a mix matching the address passed in attribtutes tags if any
2517// - 2 if none found, look for a mix matching the attributes usage
2518// - 3 if none found, default to device and output selection by policy rules.
2519
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002520status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002521{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002522 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2523 status_t res = NO_ERROR;
2524
2525 sp<HwModule> rSubmixModule;
2526 // examine each mix's route type
2527 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002528 AudioMix mix = mixes[i];
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002529 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
Eric Laurent97ac8712018-07-27 18:59:02 -07002530 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002531 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002532 break;
2533 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002534 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002535 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002536 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002537 rSubmixModule = mHwModules.getModuleFromName(
2538 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2539 if (rSubmixModule == 0) {
2540 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2541 i);
2542 res = INVALID_OPERATION;
2543 break;
2544 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002545 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002546
Eric Laurent97ac8712018-07-27 18:59:02 -07002547 String8 address = mix.mDeviceAddress;
2548 if (mix.mMixType == MIX_TYPE_PLAYERS) {
2549 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2550 } else {
2551 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
2552 }
François Gaffie036e1e92015-03-19 10:16:24 +01002553
Eric Laurent97ac8712018-07-27 18:59:02 -07002554 if (mPolicyMixes.registerMix(address, mix, 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002555 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002556 res = INVALID_OPERATION;
2557 break;
2558 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002559 audio_config_t outputConfig = mix.mFormat;
2560 audio_config_t inputConfig = mix.mFormat;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002561 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2562 // stereo and let audio flinger do the channel conversion if needed.
2563 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2564 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2565 rSubmixModule->addOutputProfile(address, &outputConfig,
2566 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2567 rSubmixModule->addInputProfile(address, &inputConfig,
2568 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002569
Eric Laurent97ac8712018-07-27 18:59:02 -07002570 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002571 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2572 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2573 address.string(), "remote-submix");
2574 } else {
2575 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2576 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2577 address.string(), "remote-submix");
2578 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002579 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2580 String8 address = mix.mDeviceAddress;
2581 audio_devices_t device = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002582 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2583 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002584
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002585 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002586 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2587 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2588 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2589 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2590 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2591 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002592 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2593 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002594 if (mPolicyMixes.registerMix(address, mix, desc) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002595 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002596 } else {
2597 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002598 }
2599 break;
2600 }
2601 }
2602
2603 if (res != NO_ERROR) {
2604 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002605 i, device, address.string());
2606 res = INVALID_OPERATION;
2607 break;
2608 } else if (!foundOutput) {
2609 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2610 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002611 res = INVALID_OPERATION;
2612 break;
2613 }
Eric Laurentc722f302014-12-10 11:21:49 -08002614 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002615 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002616 if (res != NO_ERROR) {
2617 unregisterPolicyMixes(mixes);
2618 }
2619 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002620}
2621
2622status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2623{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002624 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002625 status_t res = NO_ERROR;
2626 sp<HwModule> rSubmixModule;
2627 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002628 for (const auto& mix : mixes) {
2629 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002630
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002631 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002632 rSubmixModule = mHwModules.getModuleFromName(
2633 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2634 if (rSubmixModule == 0) {
2635 res = INVALID_OPERATION;
2636 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002637 }
2638 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002639
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002640 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002641
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002642 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2643 res = INVALID_OPERATION;
2644 continue;
2645 }
2646
2647 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2648 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2649 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2650 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2651 address.string(), "remote-submix");
2652 }
2653 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2654 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2655 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2656 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2657 address.string(), "remote-submix");
2658 }
2659 rSubmixModule->removeOutputProfile(address);
2660 rSubmixModule->removeInputProfile(address);
2661
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002662 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2663 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002664 res = INVALID_OPERATION;
2665 continue;
2666 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002667 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002668 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002669 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002670}
2671
Andy Hungc29d82b2018-10-05 12:23:17 -07002672void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07002673{
Andy Hungc29d82b2018-10-05 12:23:17 -07002674 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
2675 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07002676 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002677 std::string stateLiteral;
2678 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07002679 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002680 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
2681 "communications", "media", "record", "dock", "system",
2682 "HDMI system audio", "encoded surround output", "vibrate ringing" };
2683 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
2684 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Andy Hungc29d82b2018-10-05 12:23:17 -07002685 dst->appendFormat(" Force use for %s: %d\n",
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002686 forceUses[i], mEngine->getForceUse(i));
2687 }
Andy Hungc29d82b2018-10-05 12:23:17 -07002688 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
2689 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
2690 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
2691 mAvailableOutputDevices.dump(dst, String8("Available output"));
2692 mAvailableInputDevices.dump(dst, String8("Available input"));
2693 mHwModulesAll.dump(dst);
2694 mOutputs.dump(dst);
2695 mInputs.dump(dst);
2696 mVolumeCurves->dump(dst);
2697 mEffects.dump(dst);
2698 mAudioPatches.dump(dst);
2699 mPolicyMixes.dump(dst);
2700 mAudioSources.dump(dst);
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002701 if (!mSurroundFormats.empty()) {
Andy Hungc29d82b2018-10-05 12:23:17 -07002702 dst->append("\nEnabled Surround Formats:\n");
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002703 size_t i = 0;
2704 for (const auto& fmt : mSurroundFormats) {
Andy Hungc29d82b2018-10-05 12:23:17 -07002705 dst->append(i++ == 0 ? " " : ", ");
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002706 std::string sfmt;
2707 FormatConverter::toString(fmt, sfmt);
Andy Hungc29d82b2018-10-05 12:23:17 -07002708 dst->append(sfmt.c_str());
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002709 }
Andy Hungc29d82b2018-10-05 12:23:17 -07002710 dst->append("\n");
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002711 }
Andy Hungc29d82b2018-10-05 12:23:17 -07002712}
2713
2714status_t AudioPolicyManager::dump(int fd)
2715{
2716 String8 result;
2717 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07002718 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002719 return NO_ERROR;
2720}
2721
2722// This function checks for the parameters which can be offloaded.
2723// This can be enhanced depending on the capability of the DSP and policy
2724// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002725bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002726{
2727 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002728 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002729 offloadInfo.sample_rate, offloadInfo.channel_mask,
2730 offloadInfo.format,
2731 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2732 offloadInfo.has_video);
2733
Andy Hung2ddee192015-12-18 17:34:44 -08002734 if (mMasterMono) {
2735 return false; // no offloading if mono is set.
2736 }
2737
Eric Laurente552edb2014-03-10 17:42:56 -07002738 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07002739 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
2740 ALOGV("offload disabled by audio.offload.disable");
2741 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002742 }
2743
2744 // Check if stream type is music, then only allow offload as of now.
2745 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2746 {
2747 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2748 return false;
2749 }
2750
2751 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002752 const bool allowOffloadWithVideo =
2753 property_get_bool("audio.offload.video", false /* default_value */);
2754 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002755 ALOGV("isOffloadSupported: has_video == true, returning false");
2756 return false;
2757 }
2758
2759 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07002760 const int min_duration_secs = property_get_int32(
2761 "audio.offload.min.duration.secs", -1 /* default_value */);
2762 if (min_duration_secs >= 0) {
2763 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
2764 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%d)",
2765 min_duration_secs);
Eric Laurente552edb2014-03-10 17:42:56 -07002766 return false;
2767 }
2768 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2769 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2770 return false;
2771 }
2772
2773 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2774 // creating an offloaded track and tearing it down immediately after start when audioflinger
2775 // detects there is an active non offloadable effect.
2776 // FIXME: We should check the audio session here but we do not have it in this context.
2777 // This may prevent offloading in rare situations where effects are left active by apps
2778 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002779 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002780 return false;
2781 }
2782
2783 // See if there is a profile to support this.
2784 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002785 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002786 offloadInfo.sample_rate,
2787 offloadInfo.format,
2788 offloadInfo.channel_mask,
2789 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002790 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2791 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002792}
2793
Eric Laurent6a94d692014-05-20 11:18:06 -07002794status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2795 audio_port_type_t type,
2796 unsigned int *num_ports,
2797 struct audio_port *ports,
2798 unsigned int *generation)
2799{
2800 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2801 generation == NULL) {
2802 return BAD_VALUE;
2803 }
2804 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2805 if (ports == NULL) {
2806 *num_ports = 0;
2807 }
2808
2809 size_t portsWritten = 0;
2810 size_t portsMax = *num_ports;
2811 *num_ports = 0;
2812 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002813 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2814 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002815 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002816 for (const auto& dev : mAvailableOutputDevices) {
2817 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002818 continue;
2819 }
2820 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002821 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002822 }
2823 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002824 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002825 }
2826 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002827 for (const auto& dev : mAvailableInputDevices) {
2828 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002829 continue;
2830 }
2831 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002832 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002833 }
2834 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002835 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002836 }
2837 }
2838 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2839 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2840 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2841 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2842 }
2843 *num_ports += mInputs.size();
2844 }
2845 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002846 size_t numOutputs = 0;
2847 for (size_t i = 0; i < mOutputs.size(); i++) {
2848 if (!mOutputs[i]->isDuplicated()) {
2849 numOutputs++;
2850 if (portsWritten < portsMax) {
2851 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2852 }
2853 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002854 }
Eric Laurent84c70242014-06-23 08:46:27 -07002855 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002856 }
2857 }
2858 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002859 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002860 return NO_ERROR;
2861}
2862
Eric Laurent99fcae42018-05-17 16:59:18 -07002863status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07002864{
Eric Laurent99fcae42018-05-17 16:59:18 -07002865 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
2866 return BAD_VALUE;
2867 }
2868 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
2869 if (dev != 0) {
2870 dev->toAudioPort(port);
2871 return NO_ERROR;
2872 }
2873 dev = mAvailableInputDevices.getDeviceFromId(port->id);
2874 if (dev != 0) {
2875 dev->toAudioPort(port);
2876 return NO_ERROR;
2877 }
2878 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
2879 if (out != 0) {
2880 out->toAudioPort(port);
2881 return NO_ERROR;
2882 }
2883 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
2884 if (in != 0) {
2885 in->toAudioPort(port);
2886 return NO_ERROR;
2887 }
2888 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002889}
2890
Eric Laurent6a94d692014-05-20 11:18:06 -07002891status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2892 audio_patch_handle_t *handle,
2893 uid_t uid)
2894{
2895 ALOGV("createAudioPatch()");
2896
2897 if (handle == NULL || patch == NULL) {
2898 return BAD_VALUE;
2899 }
2900 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2901
Mikhail Naganovac9858b2018-06-15 13:12:37 -07002902 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07002903 return BAD_VALUE;
2904 }
2905 // only one source per audio patch supported for now
2906 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002907 return INVALID_OPERATION;
2908 }
Eric Laurent874c42872014-08-08 15:13:39 -07002909
2910 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002911 return INVALID_OPERATION;
2912 }
Eric Laurent874c42872014-08-08 15:13:39 -07002913 for (size_t i = 0; i < patch->num_sinks; i++) {
2914 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2915 return INVALID_OPERATION;
2916 }
2917 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002918
2919 sp<AudioPatch> patchDesc;
2920 ssize_t index = mAudioPatches.indexOfKey(*handle);
2921
Eric Laurent6a94d692014-05-20 11:18:06 -07002922 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2923 patch->sources[0].role,
2924 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002925#if LOG_NDEBUG == 0
2926 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002927 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002928 patch->sinks[i].role,
2929 patch->sinks[i].type);
2930 }
2931#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002932
2933 if (index >= 0) {
2934 patchDesc = mAudioPatches.valueAt(index);
2935 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2936 mUidCached, patchDesc->mUid, uid);
2937 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2938 return INVALID_OPERATION;
2939 }
2940 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002941 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002942 }
2943
2944 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002945 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002946 if (outputDesc == NULL) {
2947 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2948 return BAD_VALUE;
2949 }
Eric Laurent84c70242014-06-23 08:46:27 -07002950 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2951 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002952 if (patchDesc != 0) {
2953 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2954 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2955 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2956 return BAD_VALUE;
2957 }
2958 }
Eric Laurent874c42872014-08-08 15:13:39 -07002959 DeviceVector devices;
2960 for (size_t i = 0; i < patch->num_sinks; i++) {
2961 // Only support mix to devices connection
2962 // TODO add support for mix to mix connection
2963 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2964 ALOGV("createAudioPatch() source mix but sink is not a device");
2965 return INVALID_OPERATION;
2966 }
2967 sp<DeviceDescriptor> devDesc =
2968 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2969 if (devDesc == 0) {
2970 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2971 return BAD_VALUE;
2972 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002973
François Gaffie53615e22015-03-19 09:24:12 +01002974 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002975 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002976 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002977 NULL, // updatedSamplingRate
2978 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002979 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002980 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002981 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002982 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002983 ALOGV("createAudioPatch() profile not supported for device %08x",
2984 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002985 return INVALID_OPERATION;
2986 }
2987 devices.add(devDesc);
2988 }
2989 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002990 return INVALID_OPERATION;
2991 }
Eric Laurent874c42872014-08-08 15:13:39 -07002992
Eric Laurent6a94d692014-05-20 11:18:06 -07002993 // TODO: reconfigure output format and channels here
2994 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002995 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002996 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002997 index = mAudioPatches.indexOfKey(*handle);
2998 if (index >= 0) {
2999 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3000 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
3001 }
3002 patchDesc = mAudioPatches.valueAt(index);
3003 patchDesc->mUid = uid;
3004 ALOGV("createAudioPatch() success");
3005 } else {
3006 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
3007 return INVALID_OPERATION;
3008 }
3009 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3010 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3011 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003012 // only one sink supported when connecting an input device to a mix
3013 if (patch->num_sinks > 1) {
3014 return INVALID_OPERATION;
3015 }
François Gaffie53615e22015-03-19 09:24:12 +01003016 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003017 if (inputDesc == NULL) {
3018 return BAD_VALUE;
3019 }
3020 if (patchDesc != 0) {
3021 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3022 return BAD_VALUE;
3023 }
3024 }
3025 sp<DeviceDescriptor> devDesc =
3026 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
3027 if (devDesc == 0) {
3028 return BAD_VALUE;
3029 }
3030
François Gaffie53615e22015-03-19 09:24:12 +01003031 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08003032 devDesc->mAddress,
3033 patch->sinks[0].sample_rate,
3034 NULL, /*updatedSampleRate*/
3035 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003036 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003037 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003038 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003039 // FIXME for the parameter type,
3040 // and the NONE
3041 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003042 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003043 return INVALID_OPERATION;
3044 }
3045 // TODO: reconfigure output format and channels here
3046 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01003047 devDesc->type(), inputDesc->mIoHandle);
3048 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003049 index = mAudioPatches.indexOfKey(*handle);
3050 if (index >= 0) {
3051 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3052 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
3053 }
3054 patchDesc = mAudioPatches.valueAt(index);
3055 patchDesc->mUid = uid;
3056 ALOGV("createAudioPatch() success");
3057 } else {
3058 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
3059 return INVALID_OPERATION;
3060 }
3061 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3062 // device to device connection
3063 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003064 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003065 return BAD_VALUE;
3066 }
3067 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003068 sp<DeviceDescriptor> srcDeviceDesc =
3069 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07003070 if (srcDeviceDesc == 0) {
3071 return BAD_VALUE;
3072 }
Eric Laurent874c42872014-08-08 15:13:39 -07003073
Eric Laurent6a94d692014-05-20 11:18:06 -07003074 //update source and sink with our own data as the data passed in the patch may
3075 // be incomplete.
3076 struct audio_patch newPatch = *patch;
3077 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003078
Eric Laurent874c42872014-08-08 15:13:39 -07003079 for (size_t i = 0; i < patch->num_sinks; i++) {
3080 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3081 ALOGV("createAudioPatch() source device but one sink is not a device");
3082 return INVALID_OPERATION;
3083 }
3084
3085 sp<DeviceDescriptor> sinkDeviceDesc =
3086 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3087 if (sinkDeviceDesc == 0) {
3088 return BAD_VALUE;
3089 }
3090 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
3091
Eric Laurent3bcf8592015-04-03 12:13:24 -07003092 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003093 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003094 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08003095 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003096 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003097 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003098 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003099 return INVALID_OPERATION;
3100 }
Eric Laurent874c42872014-08-08 15:13:39 -07003101 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01003102 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003103 // if the sink device is reachable via an opened output stream, request to go via
3104 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07003105 audio_io_handle_t output = selectOutput(outputs,
3106 AUDIO_OUTPUT_FLAG_NONE,
3107 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07003108 if (output != AUDIO_IO_HANDLE_NONE) {
3109 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3110 if (outputDesc->isDuplicated()) {
3111 return INVALID_OPERATION;
3112 }
3113 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003114 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003115 newPatch.num_sources = 2;
3116 }
Eric Laurent83b88082014-06-20 18:31:16 -07003117 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003118 }
3119 // TODO: check from routing capabilities in config file and other conflicting patches
3120
Mikhail Naganovdc769682018-05-04 15:34:08 -07003121 status_t status = installPatch(__func__, index, handle, &newPatch, 0, uid, &patchDesc);
3122 if (status != NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003123 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3124 status);
3125 return INVALID_OPERATION;
3126 }
3127 } else {
3128 return BAD_VALUE;
3129 }
3130 } else {
3131 return BAD_VALUE;
3132 }
3133 return NO_ERROR;
3134}
3135
3136status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3137 uid_t uid)
3138{
3139 ALOGV("releaseAudioPatch() patch %d", handle);
3140
3141 ssize_t index = mAudioPatches.indexOfKey(handle);
3142
3143 if (index < 0) {
3144 return BAD_VALUE;
3145 }
3146 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3147 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3148 mUidCached, patchDesc->mUid, uid);
3149 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3150 return INVALID_OPERATION;
3151 }
3152
3153 struct audio_patch *patch = &patchDesc->mPatch;
3154 patchDesc->mUid = mUidCached;
3155 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003156 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003157 if (outputDesc == NULL) {
3158 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3159 return BAD_VALUE;
3160 }
3161
Eric Laurentc75307b2015-03-17 15:29:32 -07003162 setOutputDevice(outputDesc,
3163 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07003164 true,
3165 0,
3166 NULL);
3167 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3168 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003169 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003170 if (inputDesc == NULL) {
3171 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3172 return BAD_VALUE;
3173 }
3174 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003175 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003176 true,
3177 NULL);
3178 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003179 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3180 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3181 status, patchDesc->mAfPatchHandle);
3182 removeAudioPatch(patchDesc->mHandle);
3183 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003184 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003185 } else {
3186 return BAD_VALUE;
3187 }
3188 } else {
3189 return BAD_VALUE;
3190 }
3191 return NO_ERROR;
3192}
3193
3194status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3195 struct audio_patch *patches,
3196 unsigned int *generation)
3197{
François Gaffie53615e22015-03-19 09:24:12 +01003198 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003199 return BAD_VALUE;
3200 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003201 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003202 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003203}
3204
Eric Laurente1715a42014-05-20 11:30:42 -07003205status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003206{
Eric Laurente1715a42014-05-20 11:30:42 -07003207 ALOGV("setAudioPortConfig()");
3208
3209 if (config == NULL) {
3210 return BAD_VALUE;
3211 }
3212 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3213 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003214 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3215 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003216 }
3217
Eric Laurenta121f902014-06-03 13:32:54 -07003218 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003219 if (config->type == AUDIO_PORT_TYPE_MIX) {
3220 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003221 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003222 if (outputDesc == NULL) {
3223 return BAD_VALUE;
3224 }
Eric Laurent84c70242014-06-23 08:46:27 -07003225 ALOG_ASSERT(!outputDesc->isDuplicated(),
3226 "setAudioPortConfig() called on duplicated output %d",
3227 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003228 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003229 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003230 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003231 if (inputDesc == NULL) {
3232 return BAD_VALUE;
3233 }
Eric Laurenta121f902014-06-03 13:32:54 -07003234 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003235 } else {
3236 return BAD_VALUE;
3237 }
3238 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3239 sp<DeviceDescriptor> deviceDesc;
3240 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3241 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3242 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3243 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3244 } else {
3245 return BAD_VALUE;
3246 }
3247 if (deviceDesc == NULL) {
3248 return BAD_VALUE;
3249 }
Eric Laurenta121f902014-06-03 13:32:54 -07003250 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003251 } else {
3252 return BAD_VALUE;
3253 }
3254
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003255 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003256 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3257 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003258 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003259 audioPortConfig->toAudioPortConfig(&newConfig, config);
3260 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003261 }
Eric Laurenta121f902014-06-03 13:32:54 -07003262 if (status != NO_ERROR) {
3263 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003264 }
Eric Laurente1715a42014-05-20 11:30:42 -07003265
3266 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003267}
3268
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003269void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3270{
Eric Laurentd60560a2015-04-10 11:31:20 -07003271 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003272 clearAudioPatches(uid);
3273 clearSessionRoutes(uid);
3274}
3275
Eric Laurent6a94d692014-05-20 11:18:06 -07003276void AudioPolicyManager::clearAudioPatches(uid_t uid)
3277{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003278 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003279 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3280 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003281 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003282 }
3283 }
3284}
3285
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003286void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3287 audio_io_handle_t ouptutToSkip)
3288{
3289 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3290 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3291 for (size_t j = 0; j < mOutputs.size(); j++) {
3292 if (mOutputs.keyAt(j) == ouptutToSkip) {
3293 continue;
3294 }
3295 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3296 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3297 continue;
3298 }
3299 // If the default device for this strategy is on another output mix,
3300 // invalidate all tracks in this strategy to force re connection.
3301 // Otherwise select new device on the output mix.
3302 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003303 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003304 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3305 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3306 }
3307 }
3308 } else {
3309 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3310 setOutputDevice(outputDesc, newDevice, false);
3311 }
3312 }
3313}
3314
3315void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3316{
3317 // remove output routes associated with this uid
3318 SortedVector<routing_strategy> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07003319 for (size_t i = 0; i < mOutputs.size(); i++) {
3320 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003321 for (const auto& client : outputDesc->getClientIterable()) {
3322 if (client->hasPreferredDevice() && client->uid() == uid) {
3323 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3324 affectedStrategies.add(getStrategy(client->stream()));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003325 }
3326 }
3327 }
3328 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003329 for (const auto& strategy : affectedStrategies) {
3330 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003331 }
3332
3333 // remove input routes associated with this uid
3334 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07003335 for (size_t i = 0; i < mInputs.size(); i++) {
3336 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003337 for (const auto& client : inputDesc->getClientIterable()) {
3338 if (client->hasPreferredDevice() && client->uid() == uid) {
3339 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3340 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003341 }
3342 }
3343 }
3344 // reroute inputs if necessary
3345 SortedVector<audio_io_handle_t> inputsToClose;
3346 for (size_t i = 0; i < mInputs.size(); i++) {
3347 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurentdf628922018-12-06 21:45:51 +00003348 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003349 inputsToClose.add(inputDesc->mIoHandle);
3350 }
3351 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003352 for (const auto& input : inputsToClose) {
3353 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003354 }
3355}
3356
Eric Laurentd60560a2015-04-10 11:31:20 -07003357void AudioPolicyManager::clearAudioSources(uid_t uid)
3358{
3359 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003360 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3361 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07003362 stopAudioSource(mAudioSources.keyAt(i));
3363 }
3364 }
3365}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003366
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003367status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3368 audio_io_handle_t *ioHandle,
3369 audio_devices_t *device)
3370{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003371 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3372 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003373 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003374
François Gaffiedf372692015-03-19 10:43:27 +01003375 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003376}
3377
Eric Laurentd60560a2015-04-10 11:31:20 -07003378status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003379 const audio_attributes_t *attributes,
3380 audio_port_handle_t *portId,
3381 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003382{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003383 ALOGV("%s", __FUNCTION__);
3384 *portId = AUDIO_PORT_HANDLE_NONE;
3385
3386 if (source == NULL || attributes == NULL || portId == NULL) {
3387 ALOGW("%s invalid argument: source %p attributes %p handle %p",
3388 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003389 return BAD_VALUE;
3390 }
3391
Eric Laurentd60560a2015-04-10 11:31:20 -07003392 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3393 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003394 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
3395 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003396 return INVALID_OPERATION;
3397 }
3398
3399 sp<DeviceDescriptor> srcDeviceDesc =
3400 mAvailableInputDevices.getDevice(source->ext.device.type,
3401 String8(source->ext.device.address));
3402 if (srcDeviceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003403 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003404 return BAD_VALUE;
3405 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003406
3407 *portId = AudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07003408
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003409 struct audio_patch dummyPatch = {};
Eric Laurentd60560a2015-04-10 11:31:20 -07003410 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003411
3412 sp<SourceClientDescriptor> sourceDesc =
3413 new SourceClientDescriptor(*portId, uid, *attributes, patchDesc, srcDeviceDesc,
Eric Laurent97ac8712018-07-27 18:59:02 -07003414 streamTypefromAttributesInt(attributes),
3415 getStrategyForAttr(attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07003416
3417 status_t status = connectAudioSource(sourceDesc);
3418 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003419 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003420 }
3421 return status;
3422}
3423
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003424status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003425{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003426 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003427
3428 // make sure we only have one patch per source.
3429 disconnectAudioSource(sourceDesc);
3430
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003431 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003432 routing_strategy strategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003433 audio_stream_type_t stream = sourceDesc->stream();
3434 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->srcDevice();
Eric Laurentd60560a2015-04-10 11:31:20 -07003435
3436 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3437 sp<DeviceDescriptor> sinkDeviceDesc =
3438 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3439
3440 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003441
3442 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3443 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003444 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003445 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3446 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3447 // create patch between src device and output device
3448 // create Hwoutput and add to mHwOutputs
3449 } else {
3450 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3451 audio_io_handle_t output =
3452 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3453 if (output == AUDIO_IO_HANDLE_NONE) {
3454 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3455 return INVALID_OPERATION;
3456 }
3457 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3458 if (outputDesc->isDuplicated()) {
3459 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3460 return INVALID_OPERATION;
3461 }
Eric Laurent733ce942017-12-07 12:18:25 -08003462 status_t status = outputDesc->start();
3463 if (status != NO_ERROR) {
3464 return status;
3465 }
3466
Eric Laurentd60560a2015-04-10 11:31:20 -07003467 // create a special patch with no sink and two sources:
3468 // - the second source indicates to PatchPanel through which output mix this patch should
3469 // be connected as well as the stream type for volume control
3470 // - the sink is defined by whatever output device is currently selected for the output
3471 // though which this patch is routed.
Mikhail Naganovdc769682018-05-04 15:34:08 -07003472 PatchBuilder patchBuilder;
3473 patchBuilder.addSource(srcDeviceDesc).addSource(outputDesc, { .stream = stream });
3474 status = mpClientInterface->createAudioPatch(patchBuilder.patch(),
Eric Laurentd60560a2015-04-10 11:31:20 -07003475 &afPatchHandle,
3476 0);
3477 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3478 status, afPatchHandle);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003479 sourceDesc->patchDesc()->mPatch = *patchBuilder.patch();
Eric Laurentd60560a2015-04-10 11:31:20 -07003480 if (status != NO_ERROR) {
3481 ALOGW("%s patch panel could not connect device patch, error %d",
3482 __FUNCTION__, status);
3483 return INVALID_OPERATION;
3484 }
3485 uint32_t delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07003486 status = startSource(outputDesc, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003487
3488 if (status != NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003489 mpClientInterface->releaseAudioPatch(sourceDesc->patchDesc()->mAfPatchHandle, 0);
Eric Laurentd60560a2015-04-10 11:31:20 -07003490 return status;
3491 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003492 sourceDesc->setSwOutput(outputDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003493 if (delayMs != 0) {
3494 usleep(delayMs * 1000);
3495 }
3496 }
3497
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003498 sourceDesc->patchDesc()->mAfPatchHandle = afPatchHandle;
3499 addAudioPatch(sourceDesc->patchDesc()->mHandle, sourceDesc->patchDesc());
Eric Laurentd60560a2015-04-10 11:31:20 -07003500
3501 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003502}
3503
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003504status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07003505{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003506 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
3507 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003508 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003509 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003510 return BAD_VALUE;
3511 }
3512 status_t status = disconnectAudioSource(sourceDesc);
3513
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003514 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003515 return status;
3516}
3517
Andy Hung2ddee192015-12-18 17:34:44 -08003518status_t AudioPolicyManager::setMasterMono(bool mono)
3519{
3520 if (mMasterMono == mono) {
3521 return NO_ERROR;
3522 }
3523 mMasterMono = mono;
3524 // if enabling mono we close all offloaded devices, which will invalidate the
3525 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3526 // for recreating the new AudioTrack as non-offloaded PCM.
3527 //
3528 // If disabling mono, we leave all tracks as is: we don't know which clients
3529 // and tracks are able to be recreated as offloaded. The next "song" should
3530 // play back offloaded.
3531 if (mMasterMono) {
3532 Vector<audio_io_handle_t> offloaded;
3533 for (size_t i = 0; i < mOutputs.size(); ++i) {
3534 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3535 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3536 offloaded.push(desc->mIoHandle);
3537 }
3538 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003539 for (const auto& handle : offloaded) {
3540 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003541 }
3542 }
3543 // update master mono for all remaining outputs
3544 for (size_t i = 0; i < mOutputs.size(); ++i) {
3545 updateMono(mOutputs.keyAt(i));
3546 }
3547 return NO_ERROR;
3548}
3549
3550status_t AudioPolicyManager::getMasterMono(bool *mono)
3551{
3552 *mono = mMasterMono;
3553 return NO_ERROR;
3554}
3555
Eric Laurentac9cef52017-06-09 15:46:26 -07003556float AudioPolicyManager::getStreamVolumeDB(
3557 audio_stream_type_t stream, int index, audio_devices_t device)
3558{
3559 return computeVolume(stream, index, device);
3560}
3561
jiabin81772902018-04-02 17:52:27 -07003562status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3563 audio_format_t *surroundFormats,
3564 bool *surroundFormatsEnabled,
3565 bool reported)
3566{
3567 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3568 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3569 return BAD_VALUE;
3570 }
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003571 ALOGV("getSurroundFormats() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p"
3572 " reported %d", *numSurroundFormats, surroundFormats, surroundFormatsEnabled, reported);
jiabin81772902018-04-02 17:52:27 -07003573
3574 // Only return value if there is HDMI output.
3575 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3576 return INVALID_OPERATION;
3577 }
3578
3579 size_t formatsWritten = 0;
3580 size_t formatsMax = *numSurroundFormats;
3581 *numSurroundFormats = 0;
Mikhail Naganov2563f232018-09-27 14:48:01 -07003582 std::unordered_set<audio_format_t> formats;
jiabin81772902018-04-02 17:52:27 -07003583 if (reported) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003584 // Return formats from HDMI profiles, that have already been resolved by
3585 // checkOutputsForDevice().
3586 DeviceVector hdmiOutputDevs = mAvailableOutputDevices.getDevicesFromTypeMask(
3587 AUDIO_DEVICE_OUT_HDMI);
3588 for (size_t i = 0; i < hdmiOutputDevs.size(); i++) {
3589 FormatVector supportedFormats =
3590 hdmiOutputDevs[i]->getAudioPort()->getAudioProfiles().getSupportedFormats();
3591 for (size_t j = 0; j < supportedFormats.size(); j++) {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003592 if (mConfig.getSurroundFormats().count(supportedFormats[j]) != 0) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003593 formats.insert(supportedFormats[j]);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003594 } else {
3595 for (const auto& pair : mConfig.getSurroundFormats()) {
3596 if (pair.second.count(supportedFormats[j]) != 0) {
3597 formats.insert(pair.first);
3598 break;
3599 }
3600 }
Mikhail Naganov2563f232018-09-27 14:48:01 -07003601 }
3602 }
jiabin81772902018-04-02 17:52:27 -07003603 }
3604 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003605 for (const auto& pair : mConfig.getSurroundFormats()) {
3606 formats.insert(pair.first);
jiabin81772902018-04-02 17:52:27 -07003607 }
3608 }
Mikhail Naganov2563f232018-09-27 14:48:01 -07003609 for (const auto& format: formats) {
jiabin81772902018-04-02 17:52:27 -07003610 if (formatsWritten < formatsMax) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003611 surroundFormats[formatsWritten] = format;
jiabin81772902018-04-02 17:52:27 -07003612 bool formatEnabled = false;
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003613 if (mConfig.getSurroundFormats().count(format) == 0) {
3614 // Check sub-formats
3615 for (const auto& pair : mConfig.getSurroundFormats()) {
3616 for (const auto& subformat : pair.second) {
3617 formatEnabled = mSurroundFormats.count(subformat) != 0;
3618 if (formatEnabled) break;
3619 }
3620 if (formatEnabled) break;
jiabin81772902018-04-02 17:52:27 -07003621 }
3622 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003623 formatEnabled = mSurroundFormats.count(format) != 0;
jiabin81772902018-04-02 17:52:27 -07003624 }
3625 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3626 }
3627 (*numSurroundFormats)++;
3628 }
3629 return NO_ERROR;
3630}
3631
3632status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3633{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003634 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
jiabin81772902018-04-02 17:52:27 -07003635 // Check if audio format is a surround formats.
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003636 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
3637 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003638 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07003639 return BAD_VALUE;
3640 }
3641
3642 // Should only be called when MANUAL.
3643 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3644 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
3645 if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003646 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07003647 return INVALID_OPERATION;
3648 }
3649
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003650 if ((mSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07003651 return NO_ERROR;
3652 }
3653
3654 // The operation is valid only when there is HDMI output available.
3655 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003656 ALOGW("%s() no HDMI out devices found", __func__);
jiabin81772902018-04-02 17:52:27 -07003657 return INVALID_OPERATION;
3658 }
3659
Mikhail Naganov2563f232018-09-27 14:48:01 -07003660 std::unordered_set<audio_format_t> surroundFormatsBackup(mSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07003661 if (enabled) {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003662 mSurroundFormats.insert(audioFormat);
3663 for (const auto& subFormat : formatIter->second) {
3664 mSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07003665 }
3666 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003667 mSurroundFormats.erase(audioFormat);
3668 for (const auto& subFormat : formatIter->second) {
3669 mSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07003670 }
3671 }
3672
3673 sp<SwAudioOutputDescriptor> outputDesc;
3674 bool profileUpdated = false;
Mikhail Naganov708e0382018-05-30 09:53:04 -07003675 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003676 AUDIO_DEVICE_OUT_HDMI);
3677 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3678 // Simulate reconnection to update enabled surround sound formats.
3679 String8 address = hdmiOutputDevices[i]->mAddress;
3680 String8 name = hdmiOutputDevices[i]->getName();
3681 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3682 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3683 address.c_str(),
3684 name.c_str());
3685 if (status != NO_ERROR) {
3686 continue;
3687 }
3688 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3689 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3690 address.c_str(),
3691 name.c_str());
3692 profileUpdated |= (status == NO_ERROR);
3693 }
Mikhail Naganov708e0382018-05-30 09:53:04 -07003694 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003695 AUDIO_DEVICE_IN_HDMI);
3696 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3697 // Simulate reconnection to update enabled surround sound formats.
3698 String8 address = hdmiInputDevices[i]->mAddress;
3699 String8 name = hdmiInputDevices[i]->getName();
3700 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3701 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3702 address.c_str(),
3703 name.c_str());
3704 if (status != NO_ERROR) {
3705 continue;
3706 }
3707 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3708 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3709 address.c_str(),
3710 name.c_str());
3711 profileUpdated |= (status == NO_ERROR);
3712 }
3713
jiabin81772902018-04-02 17:52:27 -07003714 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003715 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov2563f232018-09-27 14:48:01 -07003716 mSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07003717 }
3718
3719 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3720}
3721
Eric Laurentf32108e2018-10-04 17:22:04 -07003722void AudioPolicyManager::setAppState(uid_t uid, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003723{
Eric Laurentf32108e2018-10-04 17:22:04 -07003724 Vector<sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
Eric Laurentdf628922018-12-06 21:45:51 +00003725 bool silenced = state == APP_STATE_IDLE;
Eric Laurentf32108e2018-10-04 17:22:04 -07003726
Eric Laurentdf628922018-12-06 21:45:51 +00003727 ALOGV("AudioPolicyManager:setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003728
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003729 for (size_t i = 0; i < activeInputs.size(); i++) {
3730 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
Eric Laurent8f42ea12018-08-08 09:08:25 -07003731 RecordClientVector clients = activeDesc->clientsList(true /*activeOnly*/);
3732 for (const auto& client : clients) {
3733 if (uid == client->uid()) {
Eric Laurentdf628922018-12-06 21:45:51 +00003734 client->setSilenced(silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003735 }
3736 }
3737 }
3738}
3739
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003740status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003741{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003742 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003743
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003744 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003745 if (patchDesc == 0) {
3746 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003747 sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003748 return BAD_VALUE;
3749 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003750 removeAudioPatch(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003751
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003752 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003753 if (swOutputDesc != 0) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003754 status_t status = stopSource(swOutputDesc, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08003755 if (status == NO_ERROR) {
3756 swOutputDesc->stop();
3757 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003758 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3759 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003760 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003761 if (hwOutputDesc != 0) {
3762 // release patch between src device and output device
3763 // close Hwoutput and remove from mHwOutputs
3764 } else {
3765 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3766 }
3767 }
3768 return NO_ERROR;
3769}
3770
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003771sp<SourceClientDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
Eric Laurentd60560a2015-04-10 11:31:20 -07003772 audio_io_handle_t output, routing_strategy strategy)
3773{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003774 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07003775 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003776 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3777 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003778 routing_strategy sourceStrategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003779 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003780 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3781 source = sourceDesc;
3782 break;
3783 }
3784 }
3785 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003786}
3787
Eric Laurente552edb2014-03-10 17:42:56 -07003788// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003789// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003790// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003791uint32_t AudioPolicyManager::nextAudioPortGeneration()
3792{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003793 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003794}
3795
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003796// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3797static const char *kConfigLocationList[] =
3798 {"/odm/etc", "/vendor/etc", "/system/etc"};
3799static const int kConfigLocationListSize =
3800 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3801
3802static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3803 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07003804 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003805 status_t ret;
3806
Petri Gyntherf497f292018-04-17 18:46:10 -07003807 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
3808 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
3809 // A2DP offload supported but disabled: try to use special XML file
3810 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
3811 }
3812 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3813
3814 for (const char* fileName : fileNames) {
3815 for (int i = 0; i < kConfigLocationListSize; i++) {
Petri Gyntherf497f292018-04-17 18:46:10 -07003816 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
3817 "%s/%s", kConfigLocationList[i], fileName);
Mikhail Naganova289aea2018-09-17 15:26:23 -07003818 ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile, &config);
Petri Gyntherf497f292018-04-17 18:46:10 -07003819 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003820 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07003821 return ret;
3822 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003823 }
3824 }
3825 return ret;
3826}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003827
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003828AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
3829 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07003830 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07003831 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003832 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07003833 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003834 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003835 mVolumeCurves(new VolumeCurvesCollection()),
3836 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08003837 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003838 mAudioPortGeneration(1),
3839 mBeaconMuteRefCount(0),
3840 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003841 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003842 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003843 mMasterMono(false),
Eric Laurentdf628922018-12-06 21:45:51 +00003844 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE),
3845 mHasComputedSoundTriggerSupportsConcurrentCapture(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003846{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003847}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003848
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003849AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
3850 : AudioPolicyManager(clientInterface, false /*forTesting*/)
3851{
3852 loadConfig();
3853 initialize();
3854}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003855
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07003856// This check is to catch any legacy platform updating to Q without having
3857// switched to XML since its deprecation on O.
3858// TODO: after Q release, remove this check and flag as XML is now the only
3859// option and all legacy platform should have transitioned to XML.
3860#ifndef USE_XML_AUDIO_POLICY_CONF
3861#error Audio policy no longer supports legacy .conf configuration format
François Gaffied1ab2bd2015-12-02 18:20:06 +01003862#endif
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07003863
3864void AudioPolicyManager::loadConfig() {
3865 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003866 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003867 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01003868 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003869}
3870
3871status_t AudioPolicyManager::initialize() {
3872 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01003873
3874 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003875 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3876 if (!engineInstance) {
3877 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003878 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003879 }
3880 // Retrieve the Policy Manager Interface
3881 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3882 if (mEngine == NULL) {
3883 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003884 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003885 }
3886 mEngine->setObserver(this);
3887 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003888 if (status != NO_ERROR) {
3889 LOG_FATAL("Policy engine not initialized(err=%d)", status);
3890 return status;
3891 }
François Gaffie2110e042015-03-24 08:41:51 +01003892
Eric Laurent3a4311c2014-03-17 12:00:47 -07003893 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003894 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003895 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3896 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Mikhail Naganovd4120142017-12-06 15:49:22 -08003897 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003898 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08003899 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
3900 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003901 continue;
3902 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08003903 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07003904 // open all output streams needed to access attached devices
3905 // except for direct output streams that are only opened when they are actually
3906 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003907 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003908 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003909 if (!outProfile->canOpenNewIo()) {
3910 ALOGE("Invalid Output profile max open count %u for profile %s",
3911 outProfile->maxOpenCount, outProfile->getTagName().c_str());
3912 continue;
3913 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003914 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003915 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003916 continue;
3917 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003918 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003919 mTtsOutputAvailable = true;
3920 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003921
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003922 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003923 continue;
3924 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003925 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003926 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3927 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003928 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003929 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003930 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003931 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003932 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003933 if ((profileType & outputDeviceTypes) == 0) {
3934 continue;
3935 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003936 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3937 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003938 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov708e0382018-05-30 09:53:04 -07003939 const DeviceVector &devicesForType = supportedDevices.getDevicesFromTypeMask(
3940 profileType);
Eric Laurentc40d9692016-04-13 19:14:13 -07003941 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3942 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003943 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08003944 status_t status = outputDesc->open(nullptr, profileType, address,
3945 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07003946
3947 if (status != NO_ERROR) {
3948 ALOGW("Cannot open output stream for device %08x on hw module %s",
3949 outputDesc->mDevice,
Mikhail Naganovd4120142017-12-06 15:49:22 -08003950 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003951 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003952 for (const auto& dev : supportedDevices) {
3953 ssize_t index = mAvailableOutputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07003954 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003955 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003956 mAvailableOutputDevices[index]->attach(hwModule);
Eric Laurentd78f1532014-09-16 16:38:20 -07003957 }
3958 }
3959 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003960 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003961 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003962 }
3963 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003964 setOutputDevice(outputDesc,
Eric Laurentfe231122017-11-17 17:48:06 -08003965 profileType,
Eric Laurentc40d9692016-04-13 19:14:13 -07003966 true,
3967 0,
3968 NULL,
Eric Laurentfe231122017-11-17 17:48:06 -08003969 address);
Eric Laurentd78f1532014-09-16 16:38:20 -07003970 }
Eric Laurente552edb2014-03-10 17:42:56 -07003971 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003972 // open input streams needed to access attached devices to validate
3973 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003974 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003975 if (!inProfile->canOpenNewIo()) {
3976 ALOGE("Invalid Input profile max open count %u for profile %s",
3977 inProfile->maxOpenCount, inProfile->getTagName().c_str());
3978 continue;
3979 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003980 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003981 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003982 continue;
3983 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003984 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003985 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003986 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
3987
Eric Laurentd78f1532014-09-16 16:38:20 -07003988 if ((profileType & inputDeviceTypes) == 0) {
3989 continue;
3990 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08003991 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08003992 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07003993
Mikhail Naganov708e0382018-05-30 09:53:04 -07003994 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(profileType);
Eric Laurent53b810e2017-12-10 17:25:10 -08003995 // the inputs vector must be of size >= 1, but we don't want to crash here
3996 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3997 : String8("");
3998 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
3999 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
4000
Eric Laurentd78f1532014-09-16 16:38:20 -07004001 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004002 status_t status = inputDesc->open(nullptr,
4003 profileType,
Eric Laurent53b810e2017-12-10 17:25:10 -08004004 address,
Eric Laurentfe231122017-11-17 17:48:06 -08004005 AUDIO_SOURCE_MIC,
4006 AUDIO_INPUT_FLAG_NONE,
4007 &input);
Eric Laurentd78f1532014-09-16 16:38:20 -07004008
4009 if (status == NO_ERROR) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004010 for (const auto& dev : inProfile->getSupportedDevices()) {
4011 ssize_t index = mAvailableInputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07004012 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07004013 if (index >= 0) {
4014 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
4015 if (!devDesc->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004016 devDesc->attach(hwModule);
Eric Laurent83efe1c2017-07-09 16:51:08 -07004017 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07004018 }
Eric Laurentd78f1532014-09-16 16:38:20 -07004019 }
4020 }
Eric Laurentfe231122017-11-17 17:48:06 -08004021 inputDesc->close();
Eric Laurentd78f1532014-09-16 16:38:20 -07004022 } else {
4023 ALOGW("Cannot open input stream for device %08x on hw module %s",
Eric Laurentfe231122017-11-17 17:48:06 -08004024 profileType,
Mikhail Naganovd4120142017-12-06 15:49:22 -08004025 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07004026 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004027 }
4028 }
4029 // make sure all attached devices have been allocated a unique ID
4030 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004031 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004032 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004033 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
4034 continue;
4035 }
François Gaffie2110e042015-03-24 08:41:51 +01004036 // The device is now validated and can be appended to the available devices of the engine
4037 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
4038 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004039 i++;
4040 }
4041 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004042 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01004043 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004044 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
4045 continue;
4046 }
François Gaffie2110e042015-03-24 08:41:51 +01004047 // The device is now validated and can be appended to the available devices of the engine
4048 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
4049 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004050 i++;
4051 }
4052 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004053 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01004054 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004055 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004056 }
jiabin9ff780e2018-03-19 18:19:52 -07004057 // If microphones address is empty, set it according to device type
4058 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
4059 if (mAvailableInputDevices[i]->mAddress.isEmpty()) {
4060 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
4061 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
4062 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
4063 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BACK_MICROPHONE_ADDRESS);
4064 }
4065 }
4066 }
Eric Laurente552edb2014-03-10 17:42:56 -07004067
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004068 if (mPrimaryOutput == 0) {
4069 ALOGE("Failed to open primary output");
4070 status = NO_INIT;
4071 }
Eric Laurente552edb2014-03-10 17:42:56 -07004072
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09004073 // Silence ALOGV statements
4074 property_set("log.tag." LOG_TAG, "D");
4075
Eric Laurente552edb2014-03-10 17:42:56 -07004076 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004077 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004078}
4079
Eric Laurente0720872014-03-11 09:30:41 -07004080AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004081{
Eric Laurente552edb2014-03-10 17:42:56 -07004082 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004083 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004084 }
4085 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004086 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004087 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004088 mAvailableOutputDevices.clear();
4089 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004090 mOutputs.clear();
4091 mInputs.clear();
4092 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004093 mHwModulesAll.clear();
jiabin81772902018-04-02 17:52:27 -07004094 mSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004095}
4096
Eric Laurente0720872014-03-11 09:30:41 -07004097status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004098{
Eric Laurent87ffa392015-05-22 10:32:38 -07004099 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004100}
4101
Eric Laurente552edb2014-03-10 17:42:56 -07004102// ---
4103
Eric Laurent98e38192018-02-15 18:31:53 -08004104void AudioPolicyManager::addOutput(audio_io_handle_t output,
4105 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004106{
Eric Laurent1c333e22014-05-20 10:48:17 -07004107 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08004108 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004109 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004110 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004111 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004112}
4113
François Gaffie53615e22015-03-19 09:24:12 +01004114void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4115{
4116 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004117 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004118}
4119
Eric Laurent98e38192018-02-15 18:31:53 -08004120void AudioPolicyManager::addInput(audio_io_handle_t input,
4121 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004122{
Eric Laurent1c333e22014-05-20 10:48:17 -07004123 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004124 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004125}
Eric Laurente552edb2014-03-10 17:42:56 -07004126
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004127void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08004128 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004129 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004130 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08004131 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004132 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08004133 if (devDesc != 0) {
4134 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
4135 desc->mIoHandle, address.string());
4136 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004137 }
4138}
4139
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004140status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004141 audio_policy_dev_state_t state,
4142 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004143 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07004144{
François Gaffie53615e22015-03-19 09:24:12 +01004145 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07004146 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004147
4148 if (audio_device_is_digital(device)) {
4149 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004150 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004151 }
Eric Laurente552edb2014-03-10 17:42:56 -07004152
Eric Laurent3b73df72014-03-11 09:06:29 -07004153 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004154 // first list already open outputs that can be routed to this device
4155 for (size_t i = 0; i < mOutputs.size(); i++) {
4156 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07004157 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004158 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004159 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
4160 outputs.add(mOutputs.keyAt(i));
4161 } else {
4162 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08004163 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004164 }
Eric Laurente552edb2014-03-10 17:42:56 -07004165 }
4166 }
4167 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004168 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004169 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004170 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4171 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004172 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004173 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004174 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004175 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004176 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4177 j, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004178 }
Eric Laurente552edb2014-03-10 17:42:56 -07004179 }
4180 }
4181 }
4182
Eric Laurent7b279bb2015-12-14 10:18:23 -08004183 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004184
Eric Laurente552edb2014-03-10 17:42:56 -07004185 if (profiles.isEmpty() && outputs.isEmpty()) {
4186 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4187 return BAD_VALUE;
4188 }
4189
4190 // open outputs for matching profiles if needed. Direct outputs are also opened to
4191 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4192 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004193 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004194
4195 // nothing to do if one output is already opened for this profile
4196 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004197 for (j = 0; j < outputs.size(); j++) {
4198 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004199 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004200 // matching profile: save the sample rates, format and channel masks supported
4201 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07004202 if (audio_device_is_digital(device)) {
4203 devDesc->importAudioPort(profile);
4204 }
Eric Laurente552edb2014-03-10 17:42:56 -07004205 break;
4206 }
4207 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004208 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004209 continue;
4210 }
4211
Eric Laurent3974e3b2017-12-07 17:58:43 -08004212 if (!profile->canOpenNewIo()) {
4213 ALOGW("Max Output number %u already opened for this profile %s",
4214 profile->maxOpenCount, profile->getTagName().c_str());
4215 continue;
4216 }
4217
Eric Laurent83efe1c2017-07-09 16:51:08 -07004218 ALOGV("opening output for device %08x with params %s profile %p name %s",
4219 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004220 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004221 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004222 status_t status = desc->open(nullptr, device, address,
4223 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004224
Eric Laurentfe231122017-11-17 17:48:06 -08004225 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004226 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004227 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004228 char *param = audio_device_address_to_parameter(device, address);
4229 mpClientInterface->setParameters(output, String8(param));
4230 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004231 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08004232 updateAudioProfiles(devDesc, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004233 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004234 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004235 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004236 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004237 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004238 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004239 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004240 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4241 profile->pickAudioProfile(
4242 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004243 config.offload_info.sample_rate = config.sample_rate;
4244 config.offload_info.channel_mask = config.channel_mask;
4245 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004246
4247 status_t status = desc->open(&config, device, address, AUDIO_STREAM_DEFAULT,
4248 AUDIO_OUTPUT_FLAG_NONE, &output);
4249 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004250 output = AUDIO_IO_HANDLE_NONE;
4251 }
Eric Laurentd4692962014-05-05 18:13:44 -07004252 }
4253
Eric Laurentcf2c0212014-07-25 16:20:43 -07004254 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004255 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01004256 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004257 sp<AudioPolicyMix> policyMix;
4258 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004259 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
4260 address.string());
4261 }
François Gaffie036e1e92015-03-19 10:16:24 +01004262 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07004263 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01004264
Eric Laurent87ffa392015-05-22 10:32:38 -07004265 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4266 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004267 // no duplicated output for direct outputs and
4268 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004269 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004270
Eric Laurentd4692962014-05-05 18:13:44 -07004271 //TODO: configure audio effect output stage here
4272
4273 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004274 sp<SwAudioOutputDescriptor> dupOutputDesc =
4275 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4276 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4277 &duplicatedOutput);
4278 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004279 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004280 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004281 } else {
4282 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004283 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004284 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004285 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004286 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004287 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004288 }
Eric Laurente552edb2014-03-10 17:42:56 -07004289 }
4290 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004291 } else {
4292 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004293 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004294 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004295 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004296 profiles.removeAt(profile_index);
4297 profile_index--;
4298 } else {
4299 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004300 // Load digital format info only for digital devices
4301 if (audio_device_is_digital(device)) {
4302 devDesc->importAudioPort(profile);
4303 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004304
François Gaffie53615e22015-03-19 09:24:12 +01004305 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004306 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4307 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004308 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004309 NULL/*patch handle*/, address.string());
4310 }
Eric Laurente552edb2014-03-10 17:42:56 -07004311 ALOGV("checkOutputsForDevice(): adding output %d", output);
4312 }
4313 }
4314
4315 if (profiles.isEmpty()) {
4316 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4317 return BAD_VALUE;
4318 }
Eric Laurentd4692962014-05-05 18:13:44 -07004319 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004320 // check if one opened output is not needed any more after disconnecting one device
4321 for (size_t i = 0; i < mOutputs.size(); i++) {
4322 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004323 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004324 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004325 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004326 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004327 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004328 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004329 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4330 mOutputs.keyAt(i));
4331 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004332 }
Eric Laurente552edb2014-03-10 17:42:56 -07004333 }
4334 }
Eric Laurentd4692962014-05-05 18:13:44 -07004335 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004336 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004337 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4338 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004339 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004340 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004341 "clearing direct output profile %zu on module %s",
4342 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004343 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004344 }
4345 }
4346 }
4347 }
4348 return NO_ERROR;
4349}
4350
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004351status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004352 audio_policy_dev_state_t state,
4353 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004354 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004355{
Paul McLean9080a4c2015-06-18 08:24:02 -07004356 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004357 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004358
4359 if (audio_device_is_digital(device)) {
4360 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004361 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004362 }
4363
Eric Laurentd4692962014-05-05 18:13:44 -07004364 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4365 // first list already open inputs that can be routed to this device
4366 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4367 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004368 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004369 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4370 inputs.add(mInputs.keyAt(input_index));
4371 }
4372 }
4373
4374 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004375 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004376 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004377 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004378 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004379 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004380 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004381
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004382 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004383 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004384 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004385 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004386 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4387 profile_index, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004388 }
Eric Laurentd4692962014-05-05 18:13:44 -07004389 }
4390 }
4391 }
4392
4393 if (profiles.isEmpty() && inputs.isEmpty()) {
4394 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4395 return BAD_VALUE;
4396 }
4397
4398 // open inputs for matching profiles if needed. Direct inputs are also opened to
4399 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4400 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4401
Eric Laurent1c333e22014-05-20 10:48:17 -07004402 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004403
Eric Laurentd4692962014-05-05 18:13:44 -07004404 // nothing to do if one input is already opened for this profile
4405 size_t input_index;
4406 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4407 desc = mInputs.valueAt(input_index);
4408 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004409 if (audio_device_is_digital(device)) {
4410 devDesc->importAudioPort(profile);
4411 }
Eric Laurentd4692962014-05-05 18:13:44 -07004412 break;
4413 }
4414 }
4415 if (input_index != mInputs.size()) {
4416 continue;
4417 }
4418
Eric Laurent3974e3b2017-12-07 17:58:43 -08004419 if (!profile->canOpenNewIo()) {
4420 ALOGW("Max Input number %u already opened for this profile %s",
4421 profile->maxOpenCount, profile->getTagName().c_str());
4422 continue;
4423 }
4424
Eric Laurentfe231122017-11-17 17:48:06 -08004425 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004426 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004427 status_t status = desc->open(nullptr,
4428 device,
4429 address,
4430 AUDIO_SOURCE_MIC,
4431 AUDIO_INPUT_FLAG_NONE,
4432 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004433
Eric Laurentcf2c0212014-07-25 16:20:43 -07004434 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004435 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004436 char *param = audio_device_address_to_parameter(device, address);
4437 mpClientInterface->setParameters(input, String8(param));
4438 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004439 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08004440 updateAudioProfiles(devDesc, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004441 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004442 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004443 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004444 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004445 }
4446
4447 if (input != 0) {
4448 addInput(input, desc);
4449 }
4450 } // endif input != 0
4451
Eric Laurentcf2c0212014-07-25 16:20:43 -07004452 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004453 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004454 profiles.removeAt(profile_index);
4455 profile_index--;
4456 } else {
4457 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004458 if (audio_device_is_digital(device)) {
4459 devDesc->importAudioPort(profile);
4460 }
Eric Laurentd4692962014-05-05 18:13:44 -07004461 ALOGV("checkInputsForDevice(): adding input %d", input);
4462 }
4463 } // end scan profiles
4464
4465 if (profiles.isEmpty()) {
4466 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4467 return BAD_VALUE;
4468 }
4469 } else {
4470 // Disconnect
4471 // check if one opened input is not needed any more after disconnecting one device
4472 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4473 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004474 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004475 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4476 mInputs.keyAt(input_index));
4477 inputs.add(mInputs.keyAt(input_index));
4478 }
4479 }
4480 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004481 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004482 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004483 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004484 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004485 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004486 if (profile->supportDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004487 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4488 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004489 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004490 }
4491 }
4492 }
4493 } // end disconnect
4494
4495 return NO_ERROR;
4496}
4497
4498
Eric Laurente0720872014-03-11 09:30:41 -07004499void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004500{
4501 ALOGV("closeOutput(%d)", output);
4502
Eric Laurentc75307b2015-03-17 15:29:32 -07004503 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004504 if (outputDesc == NULL) {
4505 ALOGW("closeOutput() unknown output %d", output);
4506 return;
4507 }
François Gaffie036e1e92015-03-19 10:16:24 +01004508 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004509
Eric Laurente552edb2014-03-10 17:42:56 -07004510 // look for duplicated outputs connected to the output being removed.
4511 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004512 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004513 if (dupOutputDesc->isDuplicated() &&
4514 (dupOutputDesc->mOutput1 == outputDesc ||
4515 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004516 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004517 if (dupOutputDesc->mOutput1 == outputDesc) {
4518 outputDesc2 = dupOutputDesc->mOutput2;
4519 } else {
4520 outputDesc2 = dupOutputDesc->mOutput1;
4521 }
4522 // As all active tracks on duplicated output will be deleted,
4523 // and as they were also referenced on the other output, the reference
4524 // count for their stream type must be adjusted accordingly on
4525 // the other output.
Andy Hungaf036da2018-09-21 10:46:21 -07004526 const bool wasActive = outputDesc2->isActive();
4527 for (const auto &clientPair : dupOutputDesc->getActiveClients()) {
4528 outputDesc2->changeStreamActiveCount(clientPair.first, -clientPair.second);
Eric Laurente552edb2014-03-10 17:42:56 -07004529 }
Eric Laurent733ce942017-12-07 12:18:25 -08004530 // stop() will be a no op if the output is still active but is needed in case all
4531 // active streams refcounts where cleared above
4532 if (wasActive) {
4533 outputDesc2->stop();
4534 }
Eric Laurente552edb2014-03-10 17:42:56 -07004535 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4536 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4537
4538 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004539 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004540 }
4541 }
4542
Eric Laurent05b90f82014-08-27 15:32:29 -07004543 nextAudioPortGeneration();
4544
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004545 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004546 if (index >= 0) {
4547 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004548 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004549 mAudioPatches.removeItemsAt(index);
4550 mpClientInterface->onAudioPatchListUpdate();
4551 }
4552
Eric Laurentfe231122017-11-17 17:48:06 -08004553 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004554
François Gaffie53615e22015-03-19 09:24:12 +01004555 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004556 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10004557
4558 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
4559 // no direct outputs are open.
4560 if (getMsdAudioOutDeviceTypes() != AUDIO_DEVICE_NONE) {
4561 bool directOutputOpen = false;
4562 for (size_t i = 0; i < mOutputs.size(); i++) {
4563 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
4564 directOutputOpen = true;
4565 break;
4566 }
4567 }
4568 if (!directOutputOpen) {
4569 ALOGV("no direct outputs open, reset MSD patch");
4570 setMsdPatch();
4571 }
4572 }
Eric Laurent05b90f82014-08-27 15:32:29 -07004573}
4574
4575void AudioPolicyManager::closeInput(audio_io_handle_t input)
4576{
4577 ALOGV("closeInput(%d)", input);
4578
4579 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4580 if (inputDesc == NULL) {
4581 ALOGW("closeInput() unknown input %d", input);
4582 return;
4583 }
4584
Eric Laurent6a94d692014-05-20 11:18:06 -07004585 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004586
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004587 audio_devices_t device = inputDesc->mDevice;
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004588 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004589 if (index >= 0) {
4590 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004591 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004592 mAudioPatches.removeItemsAt(index);
4593 mpClientInterface->onAudioPatchListUpdate();
4594 }
4595
Eric Laurentfe231122017-11-17 17:48:06 -08004596 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004597 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004598
4599 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
4600 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
4601 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
4602 SoundTrigger::setCaptureState(false);
4603 }
Eric Laurente552edb2014-03-10 17:42:56 -07004604}
4605
Eric Laurentc75307b2015-03-17 15:29:32 -07004606SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4607 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004608 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004609{
4610 SortedVector<audio_io_handle_t> outputs;
4611
4612 ALOGVV("getOutputsForDevice() device %04x", device);
4613 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004614 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004615 i, openOutputs.valueAt(i)->isDuplicated(),
4616 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004617 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4618 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4619 outputs.add(openOutputs.keyAt(i));
4620 }
4621 }
4622 return outputs;
4623}
4624
Mikhail Naganov37977152018-07-11 15:54:44 -07004625void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
4626{
4627 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
4628 // output is suspended before any tracks are moved to it
4629 checkA2dpSuspend();
4630 checkOutputForAllStrategies();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004631 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07004632 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00004633 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004634 setMsdPatch();
4635 }
Mikhail Naganov37977152018-07-11 15:54:44 -07004636}
4637
Eric Laurente0720872014-03-11 09:30:41 -07004638void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004639{
4640 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4641 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4642 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4643 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4644
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004645 // also take into account external policy-related changes: add all outputs which are
4646 // associated with policies in the "before" and "after" output vectors
4647 ALOGVV("checkOutputForStrategy(): policy related outputs");
4648 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004649 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004650 if (desc != 0 && desc->mPolicyMix != NULL) {
4651 srcOutputs.add(desc->mIoHandle);
4652 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4653 }
4654 }
4655 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004656 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004657 if (desc != 0 && desc->mPolicyMix != NULL) {
4658 dstOutputs.add(desc->mIoHandle);
4659 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4660 }
4661 }
4662
Mikhail Naganov9de8bd12018-07-23 16:41:31 -07004663 if (srcOutputs != dstOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004664 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4665 // audio from invalidated tracks will be rendered when unmuting
4666 uint32_t maxLatency = 0;
4667 for (audio_io_handle_t srcOut : srcOutputs) {
4668 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4669 if (desc != 0 && maxLatency < desc->latency()) {
4670 maxLatency = desc->latency();
4671 }
4672 }
Eric Laurente552edb2014-03-10 17:42:56 -07004673 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4674 strategy, srcOutputs[0], dstOutputs[0]);
4675 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004676 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004677 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4678 if (desc != 0 && isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004679 setStrategyMute(strategy, true, desc);
Eric Laurentac3a6902018-05-11 16:39:10 -07004680 setStrategyMute(strategy, false, desc, maxLatency * LATENCY_MUTE_FACTOR, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004681 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004682 sp<SourceClientDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004683 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004684 if (source != 0){
4685 connectAudioSource(source);
4686 }
Eric Laurente552edb2014-03-10 17:42:56 -07004687 }
4688
4689 // Move effects associated to this strategy from previous output to new output
4690 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004691 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004692 }
4693 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004694 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004695 if (getStrategy((audio_stream_type_t)i) == strategy) {
4696 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004697 }
4698 }
4699 }
4700}
4701
Eric Laurente0720872014-03-11 09:30:41 -07004702void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004703{
François Gaffie2110e042015-03-24 08:41:51 +01004704 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004705 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004706 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004707 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004708 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004709 checkOutputForStrategy(STRATEGY_SONIFICATION);
4710 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004711 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004712 checkOutputForStrategy(STRATEGY_MEDIA);
4713 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004714 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004715}
4716
Eric Laurente0720872014-03-11 09:30:41 -07004717void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004718{
François Gaffie53615e22015-03-19 09:24:12 +01004719 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004720 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004721 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004722 return;
4723 }
4724
Eric Laurent3a4311c2014-03-17 12:00:47 -07004725 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004726 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4727 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4728 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004729
4730 // if suspended, restore A2DP output if:
4731 // ((SCO device is NOT connected) ||
4732 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4733 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004734 //
Eric Laurentf732e072016-08-03 19:30:28 -07004735 // if not suspended, suspend A2DP output if:
4736 // (SCO device is connected) &&
4737 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4738 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004739 //
4740 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004741 if (!isScoConnected ||
4742 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4743 AUDIO_POLICY_FORCE_BT_SCO) &&
4744 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4745 AUDIO_POLICY_FORCE_BT_SCO) &&
4746 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004747 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004748
4749 mpClientInterface->restoreOutput(a2dpOutput);
4750 mA2dpSuspended = false;
4751 }
4752 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004753 if (isScoConnected &&
4754 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4755 AUDIO_POLICY_FORCE_BT_SCO) ||
4756 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4757 AUDIO_POLICY_FORCE_BT_SCO) ||
4758 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004759 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004760
4761 mpClientInterface->suspendOutput(a2dpOutput);
4762 mA2dpSuspended = true;
4763 }
4764 }
4765}
4766
Eric Laurent97ac8712018-07-27 18:59:02 -07004767template <class IoDescriptor, class Filter>
4768sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4769 IoDescriptor& desc, Filter filter, bool& active, const DeviceVector& devices)
4770{
4771 auto activeClients = desc->clientsList(true /*activeOnly*/);
4772 auto activeClientsWithRoute =
4773 desc->clientsList(true /*activeOnly*/, filter, true /*preferredDevice*/);
4774 active = activeClients.size() > 0;
4775 if (active && activeClients.size() == activeClientsWithRoute.size()) {
4776 return devices.getDeviceFromId(activeClientsWithRoute[0]->preferredDeviceId());
4777 }
4778 return nullptr;
4779}
4780
4781template <class IoCollection, class Filter>
4782sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4783 IoCollection& ioCollection, Filter filter, const DeviceVector& devices)
4784{
4785 sp<DeviceDescriptor> device;
4786 for (size_t i = 0; i < ioCollection.size(); i++) {
4787 auto desc = ioCollection.valueAt(i);
4788 bool active;
4789 sp<DeviceDescriptor> curDevice = findPreferredDevice(desc, filter, active, devices);
4790 if (active && curDevice == nullptr) {
4791 return nullptr;
4792 } else if (curDevice != nullptr) {
4793 device = curDevice;
4794 }
4795 }
4796 return device;
4797}
4798
Eric Laurentc75307b2015-03-17 15:29:32 -07004799audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4800 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004801{
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004802 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004803 if (index >= 0) {
4804 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4805 if (patchDesc->mUid != mUidCached) {
4806 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004807 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004808 return outputDesc->device();
4809 }
4810 }
4811
Eric Laurent97ac8712018-07-27 18:59:02 -07004812 // Honor explicit routing requests only if no client using default routing is active on this
4813 // input: a specific app can not force routing for other apps by setting a preferred device.
4814 bool active; // unused
4815 sp<DeviceDescriptor> deviceDesc =
4816 findPreferredDevice(outputDesc, STRATEGY_NONE, active, mAvailableOutputDevices);
4817 if (deviceDesc != nullptr) {
4818 return deviceDesc->type();
Eric Laurentf3a5a602018-05-22 18:42:55 -07004819 }
4820
Eric Laurente552edb2014-03-10 17:42:56 -07004821 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004822 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004823 // use device for strategy enforced audible
4824 // 2: we are in call or the strategy phone is active on the output:
4825 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004826 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004827 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004828 // 4: the strategy for enforced audible is active but not enforced on the output:
4829 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004830 // 5: the strategy accessibility is active on the output:
4831 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004832 // 6: the strategy "respectful" sonification is active on the output:
4833 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004834 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004835 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004836 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004837 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004838 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004839 // use device for strategy t-t-s
Eric Laurent484e9272018-06-07 17:29:23 -07004840
4841 // FIXME: extend use of isStrategyActiveOnSameModule() to all strategies
4842 // with a refined rule considering mutually exclusive devices (using same backend)
4843 // as opposed to all streams on the same audio HAL module.
Eric Laurent97ac8712018-07-27 18:59:02 -07004844 audio_devices_t device = AUDIO_DEVICE_NONE;
François Gaffiead3183e2015-03-18 16:55:35 +01004845 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004846 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004847 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4848 } else if (isInCall() ||
Eric Laurent484e9272018-06-07 17:29:23 -07004849 isStrategyActiveOnSameModule(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004850 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
Yung Ti Su3e7eb5e2018-06-13 11:48:42 +08004851 } else if (isStrategyActiveOnSameModule(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004852 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004853 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
4854 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004855 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4856 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004857 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004858 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004859 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004860 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004861 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004862 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004863 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004864 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004865 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004866 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004867 }
4868
Eric Laurent1c333e22014-05-20 10:48:17 -07004869 ALOGV("getNewOutputDevice() selected device %x", device);
4870 return device;
4871}
4872
Eric Laurentfb66dd92016-01-28 18:32:03 -08004873audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004874{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004875 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004876
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004877 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004878 if (index >= 0) {
4879 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4880 if (patchDesc->mUid != mUidCached) {
4881 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004882 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004883 return inputDesc->mDevice;
4884 }
4885 }
4886
Eric Laurent97ac8712018-07-27 18:59:02 -07004887 // Honor explicit routing requests only if no client using default routing is active on this
4888 // input: a specific app can not force routing for other apps by setting a preferred device.
4889 bool active;
4890 sp<DeviceDescriptor> deviceDesc =
4891 findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
4892 if (deviceDesc != nullptr) {
4893 return deviceDesc->type();
4894 }
4895
Eric Laurentdc95a252018-04-12 12:46:56 -07004896 // If we are not in call and no client is active on this input, this methods returns
4897 // AUDIO_DEVICE_NONE, causing the patch on the input stream to be released.
Eric Laurentdf628922018-12-06 21:45:51 +00004898 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
Eric Laurentdc95a252018-04-12 12:46:56 -07004899 if (source == AUDIO_SOURCE_DEFAULT && isInCall()) {
4900 source = AUDIO_SOURCE_VOICE_COMMUNICATION;
4901 }
4902 if (source != AUDIO_SOURCE_DEFAULT) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08004903 device = getDeviceAndMixForInputSource(source);
4904 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004905
Eric Laurente552edb2014-03-10 17:42:56 -07004906 return device;
4907}
4908
Eric Laurent794fde22016-03-11 09:50:45 -08004909bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4910 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004911 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004912}
4913
Eric Laurente0720872014-03-11 09:30:41 -07004914uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004915 return (uint32_t)getStrategy(stream);
4916}
4917
Eric Laurente0720872014-03-11 09:30:41 -07004918audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004919 // By checking the range of stream before calling getStrategy, we avoid
4920 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4921 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004922 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004923 return AUDIO_DEVICE_NONE;
4924 }
Eric Laurentb0688d62018-08-14 15:49:18 -07004925 audio_devices_t activeDevices = AUDIO_DEVICE_NONE;
Eric Laurent28d09f02016-03-08 10:43:05 -08004926 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004927 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4928 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004929 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004930 }
Eric Laurent794fde22016-03-11 09:50:45 -08004931 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004932 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004933 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Eric Laurentb0688d62018-08-14 15:49:18 -07004934 devices |= curDevices;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004935 for (audio_io_handle_t output : getOutputsForDevice(curDevices, mOutputs)) {
4936 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08004937 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurentb0688d62018-08-14 15:49:18 -07004938 activeDevices |= outputDesc->device();
Eric Laurent28d09f02016-03-08 10:43:05 -08004939 }
4940 }
Eric Laurente552edb2014-03-10 17:42:56 -07004941 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004942
Eric Laurentb0688d62018-08-14 15:49:18 -07004943 // Favor devices selected on active streams if any to report correct device in case of
4944 // explicit device selection
4945 if (activeDevices != AUDIO_DEVICE_NONE) {
4946 devices = activeDevices;
4947 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004948 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4949 and doesn't really need to.*/
4950 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4951 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4952 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4953 }
Eric Laurente552edb2014-03-10 17:42:56 -07004954 return devices;
4955}
4956
François Gaffie2110e042015-03-24 08:41:51 +01004957routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4958{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004959 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004960 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004961}
4962
Eric Laurent97ac8712018-07-27 18:59:02 -07004963routing_strategy AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004964 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004965 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004966 return STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004967 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004968 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004969 return STRATEGY_ENFORCED_AUDIBLE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004970 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004971 // usage to strategy mapping
Eric Laurent97ac8712018-07-27 18:59:02 -07004972 return mEngine->getStrategyForUsage(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004973}
4974
Eric Laurente0720872014-03-11 09:30:41 -07004975void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004976 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004977 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004978 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4979 updateDevicesAndOutputs();
4980 break;
4981 default:
4982 break;
4983 }
4984}
4985
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004986uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004987
4988 // skip beacon mute management if a dedicated TTS output is available
4989 if (mTtsOutputAvailable) {
4990 return 0;
4991 }
4992
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004993 switch(event) {
4994 case STARTING_OUTPUT:
4995 mBeaconMuteRefCount++;
4996 break;
4997 case STOPPING_OUTPUT:
4998 if (mBeaconMuteRefCount > 0) {
4999 mBeaconMuteRefCount--;
5000 }
5001 break;
5002 case STARTING_BEACON:
5003 mBeaconPlayingRefCount++;
5004 break;
5005 case STOPPING_BEACON:
5006 if (mBeaconPlayingRefCount > 0) {
5007 mBeaconPlayingRefCount--;
5008 }
5009 break;
5010 }
5011
5012 if (mBeaconMuteRefCount > 0) {
5013 // any playback causes beacon to be muted
5014 return setBeaconMute(true);
5015 } else {
5016 // no other playback: unmute when beacon starts playing, mute when it stops
5017 return setBeaconMute(mBeaconPlayingRefCount == 0);
5018 }
5019}
5020
5021uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5022 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5023 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5024 // keep track of muted state to avoid repeating mute/unmute operations
5025 if (mBeaconMuted != mute) {
5026 // mute/unmute AUDIO_STREAM_TTS on all outputs
5027 ALOGV("\t muting %d", mute);
5028 uint32_t maxLatency = 0;
5029 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005030 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005031 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07005032 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005033 0 /*delay*/, AUDIO_DEVICE_NONE);
5034 const uint32_t latency = desc->latency() * 2;
5035 if (latency > maxLatency) {
5036 maxLatency = latency;
5037 }
5038 }
5039 mBeaconMuted = mute;
5040 return maxLatency;
5041 }
5042 return 0;
5043}
5044
Eric Laurente0720872014-03-11 09:30:41 -07005045audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01005046 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005047{
Eric Laurent97ac8712018-07-27 18:59:02 -07005048 // Honor explicit routing requests only if all active clients have a preferred route in which
5049 // case the last active client route is used
5050 sp<DeviceDescriptor> deviceDesc = findPreferredDevice(mOutputs, strategy, mAvailableOutputDevices);
5051 if (deviceDesc != nullptr) {
5052 return deviceDesc->type();
Paul McLeanaa981192015-03-21 09:55:15 -07005053 }
5054
Eric Laurente552edb2014-03-10 17:42:56 -07005055 if (fromCache) {
5056 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
5057 strategy, mDeviceForStrategy[strategy]);
5058 return mDeviceForStrategy[strategy];
5059 }
François Gaffie2110e042015-03-24 08:41:51 +01005060 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07005061}
5062
Eric Laurente0720872014-03-11 09:30:41 -07005063void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005064{
5065 for (int i = 0; i < NUM_STRATEGIES; i++) {
5066 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
5067 }
5068 mPreviousOutputs = mOutputs;
5069}
5070
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005071uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005072 audio_devices_t prevDevice,
5073 uint32_t delayMs)
5074{
5075 // mute/unmute strategies using an incompatible device combination
5076 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5077 // if unmuting, unmute only after the specified delay
5078 if (outputDesc->isDuplicated()) {
5079 return 0;
5080 }
5081
5082 uint32_t muteWaitMs = 0;
5083 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07005084 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005085
5086 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
5087 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07005088 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07005089 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
5090 bool doMute = false;
5091
5092 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
5093 doMute = true;
5094 outputDesc->mStrategyMutedByDevice[i] = true;
5095 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
5096 doMute = true;
5097 outputDesc->mStrategyMutedByDevice[i] = false;
5098 }
Eric Laurent99401132014-05-07 19:48:15 -07005099 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005100 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005101 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005102 // skip output if it does not share any device with current output
5103 if ((desc->supportedDevices() & outputDesc->supportedDevices())
5104 == AUDIO_DEVICE_NONE) {
5105 continue;
5106 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005107 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07005108 mute ? "muting" : "unmuting", i, curDevice);
5109 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005110 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005111 if (mute) {
5112 // FIXME: should not need to double latency if volume could be applied
5113 // immediately by the audioflinger mixer. We must account for the delay
5114 // between now and the next time the audioflinger thread for this output
5115 // will process a buffer (which corresponds to one buffer size,
5116 // usually 1/2 or 1/4 of the latency).
5117 if (muteWaitMs < desc->latency() * 2) {
5118 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005119 }
5120 }
5121 }
5122 }
5123 }
5124 }
5125
Eric Laurent99401132014-05-07 19:48:15 -07005126 // temporary mute output if device selection changes to avoid volume bursts due to
5127 // different per device volumes
5128 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005129 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5130 // temporary mute duration is conservatively set to 4 times the reported latency
5131 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5132 if (muteWaitMs < tempMuteWaitMs) {
5133 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005134 }
Eric Laurentdc462862016-07-19 12:29:53 -07005135
Eric Laurent99401132014-05-07 19:48:15 -07005136 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005137 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005138 // make sure that we do not start the temporary mute period too early in case of
5139 // delayed device change
5140 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005141 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07005142 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07005143 }
5144 }
5145 }
5146
Eric Laurente552edb2014-03-10 17:42:56 -07005147 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5148 if (muteWaitMs > delayMs) {
5149 muteWaitMs -= delayMs;
5150 usleep(muteWaitMs * 1000);
5151 return muteWaitMs;
5152 }
5153 return 0;
5154}
5155
Eric Laurentc75307b2015-03-17 15:29:32 -07005156uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005157 audio_devices_t device,
5158 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07005159 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005160 audio_patch_handle_t *patchHandle,
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005161 const char *address,
5162 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005163{
Eric Laurentc75307b2015-03-17 15:29:32 -07005164 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005165 AudioParameter param;
5166 uint32_t muteWaitMs;
5167
5168 if (outputDesc->isDuplicated()) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005169 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs,
5170 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
5171 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs,
5172 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005173 return muteWaitMs;
5174 }
5175 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5176 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07005177 if ((device != AUDIO_DEVICE_NONE) &&
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005178 ((device & outputDesc->supportedDevices()) == AUDIO_DEVICE_NONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005179 return 0;
5180 }
5181
5182 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07005183 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07005184
5185 audio_devices_t prevDevice = outputDesc->mDevice;
5186
Paul McLeanaa981192015-03-21 09:55:15 -07005187 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005188
5189 if (device != AUDIO_DEVICE_NONE) {
5190 outputDesc->mDevice = device;
5191 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005192
5193 // if the outputs are not materially active, there is no need to mute.
5194 if (requiresMuteCheck) {
5195 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
5196 } else {
5197 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5198 muteWaitMs = 0;
5199 }
Eric Laurente552edb2014-03-10 17:42:56 -07005200
5201 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005202 // the requested device is AUDIO_DEVICE_NONE
5203 // OR the requested device is the same as current device
5204 // AND force is not specified
5205 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07005206 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07005207 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
5208 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005209 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005210 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005211 return muteWaitMs;
5212 }
5213
5214 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07005215
Eric Laurente552edb2014-03-10 17:42:56 -07005216 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07005217 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005218 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005219 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07005220 DeviceVector deviceList;
5221 if ((address == NULL) || (strlen(address) == 0)) {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005222 deviceList = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurentc40d9692016-04-13 19:14:13 -07005223 } else {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005224 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
5225 device, String8(address));
5226 if (deviceDesc) deviceList.add(deviceDesc);
Eric Laurentc40d9692016-04-13 19:14:13 -07005227 }
5228
Eric Laurent1c333e22014-05-20 10:48:17 -07005229 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005230 PatchBuilder patchBuilder;
5231 patchBuilder.addSource(outputDesc);
Eric Laurent1c333e22014-05-20 10:48:17 -07005232 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005233 patchBuilder.addSink(deviceList.itemAt(i));
Eric Laurent1c333e22014-05-20 10:48:17 -07005234 }
Mikhail Naganovdc769682018-05-04 15:34:08 -07005235 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005236 }
Eric Laurentdf628922018-12-06 21:45:51 +00005237
5238 // inform all input as well
5239 for (size_t i = 0; i < mInputs.size(); i++) {
5240 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
5241 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
5242 AudioParameter inputCmd = AudioParameter();
5243 ALOGV("%s: inform input %d of device:%d", __func__,
5244 inputDescriptor->mIoHandle, device);
5245 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
5246 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
5247 inputCmd.toString(),
5248 delayMs);
5249 }
5250 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005251 }
Eric Laurente552edb2014-03-10 17:42:56 -07005252
5253 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07005254 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005255
5256 return muteWaitMs;
5257}
5258
Eric Laurentc75307b2015-03-17 15:29:32 -07005259status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005260 int delayMs,
5261 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005262{
Eric Laurent6a94d692014-05-20 11:18:06 -07005263 ssize_t index;
5264 if (patchHandle) {
5265 index = mAudioPatches.indexOfKey(*patchHandle);
5266 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005267 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005268 }
5269 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005270 return INVALID_OPERATION;
5271 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005272 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5273 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005274 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005275 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005276 removeAudioPatch(patchDesc->mHandle);
5277 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005278 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005279 return status;
5280}
5281
5282status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5283 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005284 bool force,
5285 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005286{
5287 status_t status = NO_ERROR;
5288
Eric Laurent1f2f2232014-06-02 12:01:23 -07005289 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005290 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5291 inputDesc->mDevice = device;
5292
Mikhail Naganov708e0382018-05-30 09:53:04 -07005293 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005294 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005295 PatchBuilder patchBuilder;
5296 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005297 // AUDIO_SOURCE_HOTWORD is for internal use only:
5298 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07005299 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5300 auto result = usecase;
5301 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5302 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5303 }
5304 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07005305 //only one input device for now
Mikhail Naganovdc769682018-05-04 15:34:08 -07005306 addSource(deviceList.itemAt(0));
5307 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005308 }
5309 }
5310 return status;
5311}
5312
Eric Laurent6a94d692014-05-20 11:18:06 -07005313status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5314 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005315{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005316 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005317 ssize_t index;
5318 if (patchHandle) {
5319 index = mAudioPatches.indexOfKey(*patchHandle);
5320 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005321 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005322 }
5323 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005324 return INVALID_OPERATION;
5325 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005326 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5327 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005328 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005329 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005330 removeAudioPatch(patchDesc->mHandle);
5331 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005332 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005333 return status;
5334}
5335
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005336sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005337 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005338 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005339 audio_format_t& format,
5340 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005341 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005342{
5343 // Choose an input profile based on the requested capture parameters: select the first available
5344 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005345 //
5346 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5347 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005348
Glenn Kasten730b9262018-03-29 15:01:26 -07005349 sp<IOProfile> firstInexact;
5350 uint32_t updatedSamplingRate = 0;
5351 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5352 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005353 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005354 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005355 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005356 //updatedFormat = format;
Eric Laurent275e8e92014-11-30 15:14:47 -08005357 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005358 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005359 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005360 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005361 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005362 &channelMask /*updatedChannelMask*/,
5363 // FIXME ugly cast
5364 (audio_output_flags_t) flags,
5365 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005366 return profile;
5367 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005368 if (firstInexact == nullptr && profile->isCompatibleProfile(device, address,
5369 samplingRate,
5370 &updatedSamplingRate,
5371 format,
5372 &updatedFormat,
5373 channelMask,
5374 &updatedChannelMask,
5375 // FIXME ugly cast
5376 (audio_output_flags_t) flags,
5377 false /*exactMatchRequiredForInputFlags*/)) {
5378 firstInexact = profile;
5379 }
5380
Eric Laurente552edb2014-03-10 17:42:56 -07005381 }
5382 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005383 if (firstInexact != nullptr) {
5384 samplingRate = updatedSamplingRate;
5385 format = updatedFormat;
5386 channelMask = updatedChannelMask;
5387 return firstInexact;
5388 }
Eric Laurente552edb2014-03-10 17:42:56 -07005389 return NULL;
5390}
5391
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005392
5393audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005394 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005395{
Eric Laurent97ac8712018-07-27 18:59:02 -07005396 // Honor explicit routing requests only if all active clients have a preferred route in which
5397 // case the last active client route is used
5398 sp<DeviceDescriptor> deviceDesc =
5399 findPreferredDevice(mInputs, inputSource, mAvailableInputDevices);
5400 if (deviceDesc != nullptr) {
5401 return deviceDesc->type();
5402 }
5403
5404
François Gaffie036e1e92015-03-19 10:16:24 +01005405 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5406 audio_devices_t selectedDeviceFromMix =
5407 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005408
François Gaffie036e1e92015-03-19 10:16:24 +01005409 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5410 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005411 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005412 return getDeviceForInputSource(inputSource);
5413}
5414
5415audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5416{
Eric Laurent97ac8712018-07-27 18:59:02 -07005417 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005418}
5419
Eric Laurente0720872014-03-11 09:30:41 -07005420float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005421 int index,
5422 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005423{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005424 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005425
5426 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5427 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5428 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5429 // the ringtone volume
5430 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5431 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5432 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5433 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5434 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5435 }
5436
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005437 // in-call: always cap volume by voice volume + some low headroom
5438 if ((stream != AUDIO_STREAM_VOICE_CALL) &&
Eric Laurent7731b5a2018-04-06 15:47:22 -07005439 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005440 switch (stream) {
5441 case AUDIO_STREAM_SYSTEM:
5442 case AUDIO_STREAM_RING:
5443 case AUDIO_STREAM_MUSIC:
5444 case AUDIO_STREAM_ALARM:
5445 case AUDIO_STREAM_NOTIFICATION:
5446 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5447 case AUDIO_STREAM_DTMF:
5448 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005449 int voiceVolumeIndex =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005450 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, device);
Eric Laurent7731b5a2018-04-06 15:47:22 -07005451 const float maxVoiceVolDb =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005452 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, device)
Eric Laurent7731b5a2018-04-06 15:47:22 -07005453 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005454 if (volumeDB > maxVoiceVolDb) {
5455 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5456 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5457 volumeDB = maxVoiceVolDb;
5458 }
5459 } break;
5460 default:
5461 break;
5462 }
5463 }
5464
Eric Laurente552edb2014-03-10 17:42:56 -07005465 // if a headset is connected, apply the following rules to ring tones and notifications
5466 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005467 // - always attenuate notifications volume by 6dB
5468 // - attenuate ring tones volume by 6dB unless music is not playing and
5469 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005470 // - if music is playing, always limit the volume to current music volume,
5471 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005472 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005473 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5474 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5475 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005476 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005477 AUDIO_DEVICE_OUT_USB_HEADSET |
5478 AUDIO_DEVICE_OUT_HEARING_AID)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005479 ((stream_strategy == STRATEGY_SONIFICATION)
5480 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005481 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005482 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005483 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005484 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005485 // when the phone is ringing we must consider that music could have been paused just before
5486 // by the music application and behave as if music was active if the last music track was
5487 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005488 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005489 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005490 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005491 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005492 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005493 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5494 musicDevice),
5495 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005496 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5497 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005498 if (volumeDB > minVolDB) {
5499 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005500 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005501 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005502 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5503 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5504 // on A2DP, also ensure notification volume is not too low compared to media when
5505 // intended to be played
5506 if ((volumeDB > -96.0f) &&
5507 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5508 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5509 stream, device,
5510 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5511 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5512 }
5513 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005514 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5515 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005516 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005517 }
5518 }
5519
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005520 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005521}
5522
Eric Laurent3839bc02018-07-10 18:33:34 -07005523int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
5524 audio_stream_type_t srcStream,
5525 audio_stream_type_t dstStream)
5526{
5527 if (srcStream == dstStream) {
5528 return srcIndex;
5529 }
5530 float minSrc = (float)mVolumeCurves->getVolumeIndexMin(srcStream);
5531 float maxSrc = (float)mVolumeCurves->getVolumeIndexMax(srcStream);
5532 float minDst = (float)mVolumeCurves->getVolumeIndexMin(dstStream);
5533 float maxDst = (float)mVolumeCurves->getVolumeIndexMax(dstStream);
5534
5535 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
5536}
5537
Eric Laurente0720872014-03-11 09:30:41 -07005538status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005539 int index,
5540 const sp<AudioOutputDescriptor>& outputDesc,
5541 audio_devices_t device,
5542 int delayMs,
5543 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005544{
Eric Laurente552edb2014-03-10 17:42:56 -07005545 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005546 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005547 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005548 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005549 return NO_ERROR;
5550 }
François Gaffie2110e042015-03-24 08:41:51 +01005551 audio_policy_forced_cfg_t forceUseForComm =
5552 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005553 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005554 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5555 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005556 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005557 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005558 return INVALID_OPERATION;
5559 }
5560
Eric Laurentc75307b2015-03-17 15:29:32 -07005561 if (device == AUDIO_DEVICE_NONE) {
5562 device = outputDesc->device();
5563 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005564
Eric Laurentffbc80f2015-03-18 18:30:19 -07005565 float volumeDb = computeVolume(stream, index, device);
HW Leeda7581e2018-05-22 18:31:34 +08005566 if (outputDesc->isFixedVolume(device) ||
5567 // Force VoIP volume to max for bluetooth SCO
5568 ((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
5569 (device & AUDIO_DEVICE_OUT_ALL_SCO) != 0)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005570 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005571 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005572
Eric Laurentffbc80f2015-03-18 18:30:19 -07005573 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005574
Eric Laurent3b73df72014-03-11 09:06:29 -07005575 if (stream == AUDIO_STREAM_VOICE_CALL ||
5576 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005577 float voiceVolume;
5578 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005579 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurent3839bc02018-07-10 18:33:34 -07005580 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005581 } else {
5582 voiceVolume = 1.0;
5583 }
5584
Eric Laurent18fba842016-03-31 14:41:26 -07005585 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005586 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5587 mLastVoiceVolume = voiceVolume;
5588 }
5589 }
5590
5591 return NO_ERROR;
5592}
5593
Eric Laurentc75307b2015-03-17 15:29:32 -07005594void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5595 audio_devices_t device,
5596 int delayMs,
5597 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005598{
Eric Laurentc75307b2015-03-17 15:29:32 -07005599 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005600
Eric Laurent794fde22016-03-11 09:50:45 -08005601 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005602 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005603 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005604 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005605 device,
5606 delayMs,
5607 force);
5608 }
5609}
5610
Eric Laurente0720872014-03-11 09:30:41 -07005611void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005612 bool on,
5613 const sp<AudioOutputDescriptor>& outputDesc,
5614 int delayMs,
5615 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005616{
Eric Laurent72249d52015-06-08 11:12:15 -07005617 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5618 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005619 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005620 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005621 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005622 }
5623 }
5624}
5625
Eric Laurente0720872014-03-11 09:30:41 -07005626void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005627 bool on,
5628 const sp<AudioOutputDescriptor>& outputDesc,
5629 int delayMs,
5630 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005631{
Eric Laurente552edb2014-03-10 17:42:56 -07005632 if (device == AUDIO_DEVICE_NONE) {
5633 device = outputDesc->device();
5634 }
5635
Eric Laurentc75307b2015-03-17 15:29:32 -07005636 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5637 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005638
5639 if (on) {
5640 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005641 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005642 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005643 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005644 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005645 }
5646 }
5647 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5648 outputDesc->mMuteCount[stream]++;
5649 } else {
5650 if (outputDesc->mMuteCount[stream] == 0) {
5651 ALOGV("setStreamMute() unmuting non muted stream!");
5652 return;
5653 }
5654 if (--outputDesc->mMuteCount[stream] == 0) {
5655 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005656 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005657 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005658 device,
5659 delayMs);
5660 }
5661 }
5662}
5663
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005664audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5665{
5666 // flags to stream type mapping
5667 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5668 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5669 }
5670 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5671 return AUDIO_STREAM_BLUETOOTH_SCO;
5672 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005673 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5674 return AUDIO_STREAM_TTS;
5675 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005676
Ari Hausman-Cohen5c00d012018-06-26 17:09:11 -07005677 return audio_usage_to_stream_type(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005678}
Eric Laurente83b55d2014-11-14 10:06:21 -08005679
François Gaffie53615e22015-03-19 09:24:12 +01005680bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5681{
Eric Laurente83b55d2014-11-14 10:06:21 -08005682 // has flags that map to a strategy?
5683 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5684 return true;
5685 }
5686
5687 // has known usage?
5688 switch (paa->usage) {
5689 case AUDIO_USAGE_UNKNOWN:
5690 case AUDIO_USAGE_MEDIA:
5691 case AUDIO_USAGE_VOICE_COMMUNICATION:
5692 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5693 case AUDIO_USAGE_ALARM:
5694 case AUDIO_USAGE_NOTIFICATION:
5695 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5696 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5697 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5698 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5699 case AUDIO_USAGE_NOTIFICATION_EVENT:
5700 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5701 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5702 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5703 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005704 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005705 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005706 break;
5707 default:
5708 return false;
5709 }
5710 return true;
5711}
5712
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005713bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005714 routing_strategy strategy, uint32_t inPastMs,
5715 nsecs_t sysTime) const
5716{
5717 if ((sysTime == 0) && (inPastMs != 0)) {
5718 sysTime = systemTime();
5719 }
Eric Laurent794fde22016-03-11 09:50:45 -08005720 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005721 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurent97ac8712018-07-27 18:59:02 -07005722 (STRATEGY_NONE == strategy)) &&
François Gaffiead3183e2015-03-18 16:55:35 +01005723 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5724 return true;
5725 }
5726 }
5727 return false;
5728}
5729
Eric Laurent484e9272018-06-07 17:29:23 -07005730bool AudioPolicyManager::isStrategyActiveOnSameModule(const sp<AudioOutputDescriptor>& outputDesc,
5731 routing_strategy strategy, uint32_t inPastMs,
5732 nsecs_t sysTime) const
5733{
5734 for (size_t i = 0; i < mOutputs.size(); i++) {
5735 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5736 if (outputDesc->sharesHwModuleWith(desc)
5737 && isStrategyActive(desc, strategy, inPastMs, sysTime)) {
5738 return true;
5739 }
5740 }
5741 return false;
5742}
5743
François Gaffie2110e042015-03-24 08:41:51 +01005744audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5745{
5746 return mEngine->getForceUse(usage);
5747}
5748
5749bool AudioPolicyManager::isInCall()
5750{
5751 return isStateInCall(mEngine->getPhoneState());
5752}
5753
5754bool AudioPolicyManager::isStateInCall(int state)
5755{
5756 return is_state_in_call(state);
5757}
5758
Eric Laurentd60560a2015-04-10 11:31:20 -07005759void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5760{
5761 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005762 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5763 if (sourceDesc->srcDevice()->equals(deviceDesc)) {
5764 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->portId());
5765 stopAudioSource(sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005766 }
5767 }
5768
5769 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5770 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5771 bool release = false;
5772 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5773 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5774 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5775 source->ext.device.type == deviceDesc->type()) {
5776 release = true;
5777 }
5778 }
5779 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5780 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5781 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5782 sink->ext.device.type == deviceDesc->type()) {
5783 release = true;
5784 }
5785 }
5786 if (release) {
5787 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5788 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5789 }
5790 }
5791}
5792
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005793void AudioPolicyManager::modifySurroundFormats(
5794 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
5795 // Use a set because FormatVector is unsorted.
5796 std::unordered_set<audio_format_t> enforcedSurround(
5797 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Phil Burk09bc4612016-02-24 15:58:15 -08005798
5799 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5800 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005801 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005802
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005803 std::unordered_set<audio_format_t> formatSet;
5804 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
5805 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5806 // Only copy non-surround formats to formatSet.
5807 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
5808 if (mConfig.getSurroundFormats().count(*formatIter) == 0 &&
5809 enforcedSurround.count(*formatIter) == 0) {
5810 formatSet.insert(*formatIter);
5811 }
5812 }
5813 } else {
5814 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
5815 }
5816 formatsPtr->clear(); // Re-filled from the formatSet in the end.
5817
jiabin81772902018-04-02 17:52:27 -07005818 // If MANUAL, keep the supported surround sound formats as current enabled ones.
5819 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005820 formatSet.insert(mSurroundFormats.begin(), mSurroundFormats.end());
5821 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
5822 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
5823 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08005824 }
jiabin81772902018-04-02 17:52:27 -07005825 } else { // NEVER, AUTO or ALWAYS
jiabin81772902018-04-02 17:52:27 -07005826 mSurroundFormats.clear();
jiabin81772902018-04-02 17:52:27 -07005827 // Modify formats based on surround preferences.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005828 if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
jiabin81772902018-04-02 17:52:27 -07005829 // If ALWAYS, add support for raw surround formats if all are missing.
5830 // This assumes that if any of these formats are reported by the HAL
5831 // then the report is valid and should not be modified.
5832 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005833 for (const auto& format : mConfig.getSurroundFormats()) {
5834 formatSet.insert(format.first);
5835 }
jiabin81772902018-04-02 17:52:27 -07005836 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005837 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
jiabin81772902018-04-02 17:52:27 -07005838
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005839 for (const auto& format : formatSet) {
Mikhail Naganov02743e22018-11-28 15:56:55 -08005840 if (mConfig.getSurroundFormats().count(format) != 0) {
5841 mSurroundFormats.insert(format);
Phil Burk07ac1142016-03-25 13:39:29 -07005842 }
Phil Burk09bc4612016-02-24 15:58:15 -08005843 }
Phil Burk07ac1142016-03-25 13:39:29 -07005844 }
Phil Burk09bc4612016-02-24 15:58:15 -08005845 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005846 for (const auto& format : formatSet) {
5847 formatsPtr->push(format);
5848 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005849}
5850
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005851void AudioPolicyManager::modifySurroundChannelMasks(ChannelsVector *channelMasksPtr) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005852 ChannelsVector &channelMasks = *channelMasksPtr;
5853 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5854 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5855
5856 // If NEVER, then remove support for channelMasks > stereo.
5857 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5858 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5859 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5860 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5861 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5862 channelMasks.removeAt(maskIndex);
5863 } else {
5864 maskIndex++;
5865 }
5866 }
jiabin81772902018-04-02 17:52:27 -07005867 // If ALWAYS or MANUAL, then make sure we at least support 5.1
5868 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
5869 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005870 bool supports5dot1 = false;
5871 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005872 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005873 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5874 supports5dot1 = true;
5875 break;
5876 }
5877 }
5878 // If not then add 5.1 support.
5879 if (!supports5dot1) {
5880 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
5881 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
5882 }
Phil Burk09bc4612016-02-24 15:58:15 -08005883 }
5884}
5885
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005886void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07005887 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005888 AudioProfileVector &profiles)
5889{
5890 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005891 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07005892
François Gaffie112b0af2015-11-19 16:13:25 +01005893 // Format MUST be checked first to update the list of AudioProfile
5894 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005895 reply = mpClientInterface->getParameters(
5896 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07005897 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005898 AudioParameter repliedParameters(reply);
5899 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005900 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005901 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5902 return;
5903 }
Phil Burk09bc4612016-02-24 15:58:15 -08005904 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07005905 if (device == AUDIO_DEVICE_OUT_HDMI) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005906 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005907 }
Phil Burk09bc4612016-02-24 15:58:15 -08005908 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005909 }
François Gaffie112b0af2015-11-19 16:13:25 +01005910
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005911 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08005912 ChannelsVector channelMasks;
5913 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005914 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07005915 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01005916
5917 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005918 reply = mpClientInterface->getParameters(
5919 ioHandle,
5920 requestedParameters.toString() + ";" +
5921 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01005922 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005923 AudioParameter repliedParameters(reply);
5924 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005925 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005926 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005927 }
5928 }
5929 if (profiles.hasDynamicChannelsFor(format)) {
5930 reply = mpClientInterface->getParameters(ioHandle,
5931 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07005932 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01005933 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005934 AudioParameter repliedParameters(reply);
5935 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005936 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005937 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07005938 if (device == AUDIO_DEVICE_OUT_HDMI) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005939 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07005940 }
François Gaffie112b0af2015-11-19 16:13:25 +01005941 }
5942 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08005943 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01005944 }
5945}
Eric Laurentd60560a2015-04-10 11:31:20 -07005946
Mikhail Naganovdc769682018-05-04 15:34:08 -07005947status_t AudioPolicyManager::installPatch(const char *caller,
5948 audio_patch_handle_t *patchHandle,
5949 AudioIODescriptorInterface *ioDescriptor,
5950 const struct audio_patch *patch,
5951 int delayMs)
5952{
5953 ssize_t index = mAudioPatches.indexOfKey(
5954 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
5955 *patchHandle : ioDescriptor->getPatchHandle());
5956 sp<AudioPatch> patchDesc;
5957 status_t status = installPatch(
5958 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
5959 if (status == NO_ERROR) {
5960 ioDescriptor->setPatchHandle(patchDesc->mHandle);
5961 }
5962 return status;
5963}
5964
5965status_t AudioPolicyManager::installPatch(const char *caller,
5966 ssize_t index,
5967 audio_patch_handle_t *patchHandle,
5968 const struct audio_patch *patch,
5969 int delayMs,
5970 uid_t uid,
5971 sp<AudioPatch> *patchDescPtr)
5972{
5973 sp<AudioPatch> patchDesc;
5974 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
5975 if (index >= 0) {
5976 patchDesc = mAudioPatches.valueAt(index);
5977 afPatchHandle = patchDesc->mAfPatchHandle;
5978 }
5979
5980 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
5981 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
5982 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
5983 if (status == NO_ERROR) {
5984 if (index < 0) {
5985 patchDesc = new AudioPatch(patch, uid);
5986 addAudioPatch(patchDesc->mHandle, patchDesc);
5987 } else {
5988 patchDesc->mPatch = *patch;
5989 }
5990 patchDesc->mAfPatchHandle = afPatchHandle;
5991 if (patchHandle) {
5992 *patchHandle = patchDesc->mHandle;
5993 }
5994 nextAudioPortGeneration();
5995 mpClientInterface->onAudioPatchListUpdate();
5996 }
5997 if (patchDescPtr) *patchDescPtr = patchDesc;
5998 return status;
5999}
6000
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006001} // namespace android