blob: f07b797ad9a4e05b9570186f0f1cc014b4888d5d [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070017#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090018
19// Need to keep the log statements even in production builds
20// to enable VERBOSE logging dynamically.
21// You can enable VERBOSE logging as follows:
22// adb shell setprop log.tag.APM_AudioPolicyManager V
23#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070024
25//#define VERY_VERBOSE_LOGGING
26#ifdef VERY_VERBOSE_LOGGING
27#define ALOGVV ALOGV
28#else
29#define ALOGVV(a...) do { } while(0)
30#endif
31
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +090032#define AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH 128
33#define AUDIO_POLICY_XML_CONFIG_FILE_NAME "audio_policy_configuration.xml"
Petri Gyntherf497f292018-04-17 18:46:10 -070034#define AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME \
35 "audio_policy_configuration_a2dp_offload_disabled.xml"
François Gaffief4ad6e52015-11-19 16:59:57 +010036
Eric Laurentd4692962014-05-05 18:13:44 -070037#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070038#include <math.h>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080039#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110040#include <vector>
Eric Laurentd4692962014-05-05 18:13:44 -070041
François Gaffie2110e042015-03-24 08:41:51 +010042#include <AudioPolicyManagerInterface.h>
43#include <AudioPolicyEngineInstance.h>
Eric Laurente552edb2014-03-10 17:42:56 -070044#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070045#include <utils/Log.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070046#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080047#include <media/AudioPolicyHelper.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070048#include <private/android_filesystem_config.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070049#include <soundtrigger/SoundTrigger.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070050#include <system/audio.h>
Mikhail Naganov9ee05402016-10-13 15:58:17 -070051#include <audio_policy_conf.h>
Eric Laurentd4692962014-05-05 18:13:44 -070052#include "AudioPolicyManager.h"
François Gaffied1ab2bd2015-12-02 18:20:06 +010053#include <Serializer.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010054#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010055#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070056
Eric Laurent3b73df72014-03-11 09:06:29 -070057namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070058
Eric Laurentdc462862016-07-19 12:29:53 -070059//FIXME: workaround for truncated touch sounds
60// to be removed when the problem is handled by system UI
61#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070062
63// Largest difference in dB on earpiece in call between the voice volume and another
64// media / notification / system volume.
65constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
66
Mikhail Naganov15be9d22017-11-08 14:18:13 +110067// Compressed formats for MSD module, ordered from most preferred to least preferred.
68static const std::vector<audio_format_t> compressedFormatsOrder = {{
69 AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
70 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
71// Channel masks for MSD module, 3D > 2D > 1D ordering (most preferred to least preferred).
72static const std::vector<audio_channel_mask_t> surroundChannelMasksOrder = {{
73 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
74 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
75 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
76
Eric Laurente552edb2014-03-10 17:42:56 -070077// ----------------------------------------------------------------------------
78// AudioPolicyInterface implementation
79// ----------------------------------------------------------------------------
80
Eric Laurente0720872014-03-11 09:30:41 -070081status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -080082 audio_policy_dev_state_t state,
83 const char *device_address,
84 const char *device_name)
Eric Laurente552edb2014-03-10 17:42:56 -070085{
jiabina7b43792018-02-15 16:04:46 -080086 status_t status = setDeviceConnectionStateInt(device, state, device_address, device_name);
87 nextAudioPortGeneration();
88 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -080089}
90
François Gaffie44481e72016-04-20 07:49:57 +020091void AudioPolicyManager::broadcastDeviceConnectionState(audio_devices_t device,
92 audio_policy_dev_state_t state,
93 const String8 &device_address)
94{
95 AudioParameter param(device_address);
96 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganov388360c2016-10-17 17:09:41 -070097 AudioParameter::keyStreamConnect : AudioParameter::keyStreamDisconnect);
François Gaffie44481e72016-04-20 07:49:57 +020098 param.addInt(key, device);
99 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
100}
101
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800102status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800103 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -0800104 const char *device_address,
105 const char *device_name)
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800106{
Paul McLeane743a472015-01-28 11:07:31 -0800107 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s",
Mikhail Naganov7e22e942017-12-07 10:04:29 -0800108 device, state, device_address, device_name);
Eric Laurente552edb2014-03-10 17:42:56 -0700109
110 // connect/disconnect only 1 device at a time
111 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
112
François Gaffie53615e22015-03-19 09:24:12 +0100113 sp<DeviceDescriptor> devDesc =
114 mHwModules.getDeviceDescriptor(device, device_address, device_name);
Paul McLeane743a472015-01-28 11:07:31 -0800115
Eric Laurente552edb2014-03-10 17:42:56 -0700116 // handle output devices
117 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700118 SortedVector <audio_io_handle_t> outputs;
119
Eric Laurent3a4311c2014-03-17 12:00:47 -0700120 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
121
Eric Laurente552edb2014-03-10 17:42:56 -0700122 // save a copy of the opened output descriptors before any output is opened or closed
123 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
124 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700125 switch (state)
126 {
127 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800128 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700129 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700130 ALOGW("setDeviceConnectionState() device already connected: %x", device);
131 return INVALID_OPERATION;
132 }
133 ALOGV("setDeviceConnectionState() connecting device %x", device);
134
Eric Laurente552edb2014-03-10 17:42:56 -0700135 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700136 index = mAvailableOutputDevices.add(devDesc);
137 if (index >= 0) {
François Gaffie53615e22015-03-19 09:24:12 +0100138 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700139 if (module == 0) {
140 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
141 device);
142 mAvailableOutputDevices.remove(devDesc);
143 return INVALID_OPERATION;
144 }
Paul McLeane743a472015-01-28 11:07:31 -0800145 mAvailableOutputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700146 } else {
147 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700148 }
149
François Gaffie44481e72016-04-20 07:49:57 +0200150 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
151 // parameters on newly connected devices (instead of opening the outputs...)
152 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
153
Eric Laurenta1d525f2015-01-29 13:36:45 -0800154 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700155 mAvailableOutputDevices.remove(devDesc);
François Gaffie44481e72016-04-20 07:49:57 +0200156
157 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
158 devDesc->mAddress);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700159 return INVALID_OPERATION;
160 }
François Gaffie2110e042015-03-24 08:41:51 +0100161 // Propagate device availability to Engine
162 mEngine->setDeviceConnectionState(devDesc, state);
163
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700164 // outputs should never be empty here
165 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
166 "checkOutputsForDevice() returned no outputs but status OK");
167 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
168 outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800169
Eric Laurent3ae5f312015-02-03 17:12:08 -0800170 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700171 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700172 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700173 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700174 ALOGW("setDeviceConnectionState() device not connected: %x", device);
175 return INVALID_OPERATION;
176 }
177
Paul McLean5c477aa2014-08-20 16:47:57 -0700178 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
179
Paul McLeane743a472015-01-28 11:07:31 -0800180 // Send Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200181 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700182
Eric Laurente552edb2014-03-10 17:42:56 -0700183 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700184 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700185
Eric Laurenta1d525f2015-01-29 13:36:45 -0800186 checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress);
François Gaffie2110e042015-03-24 08:41:51 +0100187
188 // Propagate device availability to Engine
189 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700190 } break;
191
192 default:
193 ALOGE("setDeviceConnectionState() invalid state: %x", state);
194 return BAD_VALUE;
195 }
196
Mikhail Naganov37977152018-07-11 15:54:44 -0700197 checkForDeviceAndOutputChanges([&]() {
198 // outputs must be closed after checkOutputForAllStrategies() is executed
199 if (!outputs.isEmpty()) {
200 for (audio_io_handle_t output : outputs) {
201 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
202 // close unused outputs after device disconnection or direct outputs that have been
203 // opened by checkOutputsForDevice() to query dynamic parameters
204 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
205 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
206 (desc->mDirectOpenCount == 0))) {
207 closeOutput(output);
208 }
Eric Laurente552edb2014-03-10 17:42:56 -0700209 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700210 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
211 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700212 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700213 return false;
214 });
Eric Laurente552edb2014-03-10 17:42:56 -0700215
Eric Laurent87ffa392015-05-22 10:32:38 -0700216 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700217 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
218 updateCallRouting(newDevice);
219 }
Mikhail Naganov100f0122018-11-29 11:22:16 -0800220 const audio_devices_t msdOutDevice = getModuleDeviceTypes(
221 mAvailableOutputDevices, AUDIO_HARDWARE_MODULE_ID_MSD);
Eric Laurente552edb2014-03-10 17:42:56 -0700222 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700223 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
224 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
225 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700226 // do not force device change on duplicated output because if device is 0, it will
227 // also force a device 0 for the two outputs it is duplicated to which may override
228 // a valid device selection on those outputs.
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100229 bool force = (msdOutDevice == AUDIO_DEVICE_NONE || msdOutDevice != desc->device())
230 && !desc->isDuplicated()
François Gaffie53615e22015-03-19 09:24:12 +0100231 && (!device_distinguishes_on_address(device)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700232 // always force when disconnecting (a non-duplicated device)
233 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
Eric Laurentc75307b2015-03-17 15:29:32 -0700234 setOutputDevice(desc, newDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700235 }
Eric Laurente552edb2014-03-10 17:42:56 -0700236 }
237
Eric Laurentd60560a2015-04-10 11:31:20 -0700238 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
239 cleanUpForDevice(devDesc);
240 }
241
Eric Laurent72aa32f2014-05-30 18:51:48 -0700242 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700243 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700244 } // end if is output device
245
Eric Laurente552edb2014-03-10 17:42:56 -0700246 // handle input devices
247 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700248 SortedVector <audio_io_handle_t> inputs;
249
Eric Laurent3a4311c2014-03-17 12:00:47 -0700250 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700251 switch (state)
252 {
253 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700254 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700255 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700256 ALOGW("setDeviceConnectionState() device already connected: %d", device);
257 return INVALID_OPERATION;
258 }
François Gaffie53615e22015-03-19 09:24:12 +0100259 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700260 if (module == NULL) {
261 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
262 device);
263 return INVALID_OPERATION;
264 }
François Gaffie44481e72016-04-20 07:49:57 +0200265
266 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
267 // parameters on newly connected devices (instead of opening the inputs...)
268 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
269
Paul McLean9080a4c2015-06-18 08:24:02 -0700270 if (checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress) != NO_ERROR) {
François Gaffie44481e72016-04-20 07:49:57 +0200271 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
272 devDesc->mAddress);
Eric Laurentd4692962014-05-05 18:13:44 -0700273 return INVALID_OPERATION;
274 }
275
Eric Laurent3a4311c2014-03-17 12:00:47 -0700276 index = mAvailableInputDevices.add(devDesc);
277 if (index >= 0) {
Paul McLeane743a472015-01-28 11:07:31 -0800278 mAvailableInputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700279 } else {
280 return NO_MEMORY;
281 }
Eric Laurent3ae5f312015-02-03 17:12:08 -0800282
François Gaffie2110e042015-03-24 08:41:51 +0100283 // Propagate device availability to Engine
284 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700285 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700286
287 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700288 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700289 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700290 ALOGW("setDeviceConnectionState() device not connected: %d", device);
291 return INVALID_OPERATION;
292 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700293
294 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
295
296 // Set Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200297 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700298
Paul McLean9080a4c2015-06-18 08:24:02 -0700299 checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700300 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700301
François Gaffie2110e042015-03-24 08:41:51 +0100302 // Propagate device availability to Engine
303 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700304 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700305
306 default:
307 ALOGE("setDeviceConnectionState() invalid state: %x", state);
308 return BAD_VALUE;
309 }
310
Eric Laurentd4692962014-05-05 18:13:44 -0700311 closeAllInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700312 // As the input device list can impact the output device selection, update
313 // getDeviceForStrategy() cache
314 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700315
Eric Laurent87ffa392015-05-22 10:32:38 -0700316 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700317 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
318 updateCallRouting(newDevice);
319 }
320
Eric Laurentd60560a2015-04-10 11:31:20 -0700321 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
322 cleanUpForDevice(devDesc);
323 }
324
Eric Laurentb52c1522014-05-20 11:27:36 -0700325 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700326 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700327 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700328
329 ALOGW("setDeviceConnectionState() invalid device: %x", device);
330 return BAD_VALUE;
331}
332
Eric Laurente0720872014-03-11 09:30:41 -0700333audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100334 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700335{
Eric Laurent634b7142016-04-20 13:48:02 -0700336 sp<DeviceDescriptor> devDesc =
337 mHwModules.getDeviceDescriptor(device, device_address, "",
338 (strlen(device_address) != 0)/*matchAddress*/);
339
340 if (devDesc == 0) {
341 ALOGW("getDeviceConnectionState() undeclared device, type %08x, address: %s",
342 device, device_address);
343 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
344 }
François Gaffie53615e22015-03-19 09:24:12 +0100345
Eric Laurent3a4311c2014-03-17 12:00:47 -0700346 DeviceVector *deviceVector;
347
Eric Laurente552edb2014-03-10 17:42:56 -0700348 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700349 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700350 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700351 deviceVector = &mAvailableInputDevices;
352 } else {
353 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
354 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700355 }
Eric Laurent634b7142016-04-20 13:48:02 -0700356
357 return (deviceVector->getDevice(device, String8(device_address)) != 0) ?
358 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800359}
360
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800361status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
362 const char *device_address,
363 const char *device_name)
364{
365 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700366 String8 reply;
367 AudioParameter param;
368 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800369
370 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s",
371 device, device_address, device_name);
372
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800373 // connect/disconnect only 1 device at a time
374 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
375
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800376 // Check if the device is currently connected
377 sp<DeviceDescriptor> devDesc =
378 mHwModules.getDeviceDescriptor(device, device_address, device_name);
379 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
380 if (index < 0) {
381 // Nothing to do: device is not connected
382 return NO_ERROR;
383 }
384
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700385 // For offloaded A2DP, Hw modules may have the capability to
386 // configure codecs. Check if any of the loaded hw modules
387 // supports this.
388 // If supported, send a set parameter to configure A2DP codecs
389 // and return. No need to toggle device state.
390 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
391 reply = mpClientInterface->getParameters(
392 AUDIO_IO_HANDLE_NONE,
393 String8(AudioParameter::keyReconfigA2dpSupported));
394 AudioParameter repliedParameters(reply);
395 repliedParameters.getInt(
396 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
397 if (isReconfigA2dpSupported) {
398 const String8 key(AudioParameter::keyReconfigA2dp);
399 param.add(key, String8("true"));
400 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
401 return NO_ERROR;
402 }
403 }
404
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800405 // Toggle the device state: UNAVAILABLE -> AVAILABLE
406 // This will force reading again the device configuration
407 status = setDeviceConnectionState(device,
408 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
409 device_address, device_name);
410 if (status != NO_ERROR) {
411 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
412 status);
413 return status;
414 }
415
416 status = setDeviceConnectionState(device,
417 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
418 device_address, device_name);
419 if (status != NO_ERROR) {
420 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
421 status);
422 return status;
423 }
424
425 return NO_ERROR;
426}
427
Eric Laurentdc462862016-07-19 12:29:53 -0700428uint32_t AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700429{
430 bool createTxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700431 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700432
Andy Hunga76c7de2016-12-13 19:14:31 -0800433 if(!hasPrimaryOutput() || mPrimaryOutput->device() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurentdc462862016-07-19 12:29:53 -0700434 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700435 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800436 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700437 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
438
439 // release existing RX patch if any
440 if (mCallRxPatch != 0) {
441 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
442 mCallRxPatch.clear();
443 }
444 // release TX patch if any
445 if (mCallTxPatch != 0) {
446 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
447 mCallTxPatch.clear();
448 }
449
450 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
451 // via setOutputDevice() on primary output.
452 // Otherwise, create two audio patches for TX and RX path.
453 if (availablePrimaryOutputDevices() & rxDevice) {
Eric Laurentdc462862016-07-19 12:29:53 -0700454 muteWaitMs = setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700455 // If the TX device is also on the primary HW module, setOutputDevice() will take care
456 // of it due to legacy implementation. If not, create a patch.
457 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
458 == AUDIO_DEVICE_NONE) {
459 createTxPatch = true;
460 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700461 } else { // create RX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800462 mCallRxPatch = createTelephonyPatch(true /*isRx*/, rxDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700463 createTxPatch = true;
464 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700465 if (createTxPatch) { // create TX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800466 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txDevice, delayMs);
467 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700468
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800469 return muteWaitMs;
470}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700471
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800472sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
473 bool isRx, audio_devices_t device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700474 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700475
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800476 sp<DeviceDescriptor> txSourceDeviceDesc;
477 if (isRx) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700478 patchBuilder.addSink(findDevice(mAvailableOutputDevices, device)).
479 addSource(findDevice(mAvailableInputDevices, AUDIO_DEVICE_IN_TELEPHONY_RX));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800480 } else {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700481 patchBuilder.addSource(txSourceDeviceDesc = findDevice(mAvailableInputDevices, device)).
482 addSink(findDevice(mAvailableOutputDevices, AUDIO_DEVICE_OUT_TELEPHONY_TX));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800483 }
484
485 audio_devices_t outputDevice = isRx ? device : AUDIO_DEVICE_OUT_TELEPHONY_TX;
486 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(outputDevice, mOutputs);
jiabin40573322018-11-08 12:08:02 -0800487 audio_io_handle_t output = selectOutput(outputs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800488 // request to reuse existing output stream if one is already opened to reach the target device
489 if (output != AUDIO_IO_HANDLE_NONE) {
490 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
491 ALOG_ASSERT(!outputDesc->isDuplicated(),
492 "%s() %#x device output %d is duplicated", __func__, outputDevice, output);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700493 patchBuilder.addSource(outputDesc, { .stream = AUDIO_STREAM_PATCH });
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800494 }
495
496 if (!isRx) {
Eric Laurentc0a889f2015-10-14 14:36:34 -0700497 // terminate active capture if on the same HW module as the call TX source device
498 // FIXME: would be better to refine to only inputs whose profile connects to the
499 // call TX device but this information is not in the audio patch and logic here must be
500 // symmetric to the one in startInput()
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800501 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800502 if (activeDesc->hasSameHwModuleAs(txSourceDeviceDesc)) {
Eric Laurent8f42ea12018-08-08 09:08:25 -0700503 closeActiveClients(activeDesc);
Eric Laurentc0a889f2015-10-14 14:36:34 -0700504 }
505 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700506 }
Eric Laurentdc462862016-07-19 12:29:53 -0700507
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800508 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Mikhail Naganovdc769682018-05-04 15:34:08 -0700509 status_t status = mpClientInterface->createAudioPatch(
510 patchBuilder.patch(), &afPatchHandle, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800511 ALOGW_IF(status != NO_ERROR,
512 "%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
513 sp<AudioPatch> audioPatch;
514 if (status == NO_ERROR) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700515 audioPatch = new AudioPatch(patchBuilder.patch(), mUidCached);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800516 audioPatch->mAfPatchHandle = afPatchHandle;
517 audioPatch->mUid = mUidCached;
518 }
519 return audioPatch;
520}
521
Mikhail Naganovdc769682018-05-04 15:34:08 -0700522sp<DeviceDescriptor> AudioPolicyManager::findDevice(
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100523 const DeviceVector& devices, audio_devices_t device) const {
Mikhail Naganov708e0382018-05-30 09:53:04 -0700524 DeviceVector deviceList = devices.getDevicesFromTypeMask(device);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800525 ALOG_ASSERT(!deviceList.isEmpty(),
526 "%s() selected device type %#x is not in devices list", __func__, device);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700527 return deviceList.itemAt(0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700528}
529
Mikhail Naganov100f0122018-11-29 11:22:16 -0800530audio_devices_t AudioPolicyManager::getModuleDeviceTypes(
531 const DeviceVector& devices, const char *moduleId) const {
532 sp<HwModule> mod = mHwModules.getModuleFromName(moduleId);
533 return mod != 0 ? devices.getDeviceTypesFromHwModule(mod->getHandle()) : AUDIO_DEVICE_NONE;
534}
535
536bool AudioPolicyManager::isDeviceOfModule(
537 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
538 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
539 if (module != 0) {
540 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
541 .indexOf(devDesc) != NAME_NOT_FOUND
542 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
543 .indexOf(devDesc) != NAME_NOT_FOUND;
544 }
545 return false;
546}
547
Eric Laurente0720872014-03-11 09:30:41 -0700548void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700549{
550 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100551 // store previous phone state for management of sonification strategy below
552 int oldState = mEngine->getPhoneState();
553
554 if (mEngine->setPhoneState(state) != NO_ERROR) {
555 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700556 return;
557 }
François Gaffie2110e042015-03-24 08:41:51 +0100558 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700559 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700560 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700561 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800562 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700563 }
564
François Gaffie2110e042015-03-24 08:41:51 +0100565 /**
566 * Switching to or from incall state or switching between telephony and VoIP lead to force
567 * routing command.
568 */
569 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
570 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700571
572 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700573 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700574
Eric Laurente552edb2014-03-10 17:42:56 -0700575 int delayMs = 0;
576 if (isStateInCall(state)) {
577 nsecs_t sysTime = systemTime();
578 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700579 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700580 // mute media and sonification strategies and delay device switch by the largest
581 // latency of any output where either strategy is active.
582 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100583 if ((isStrategyActive(desc, STRATEGY_MEDIA,
584 SONIFICATION_HEADSET_MUSIC_DELAY,
585 sysTime) ||
586 isStrategyActive(desc, STRATEGY_SONIFICATION,
587 SONIFICATION_HEADSET_MUSIC_DELAY,
588 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700589 (delayMs < (int)desc->latency()*2)) {
590 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700591 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700592 setStrategyMute(STRATEGY_MEDIA, true, desc);
593 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700594 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700595 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
596 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700597 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
598 }
599 }
600
Eric Laurent87ffa392015-05-22 10:32:38 -0700601 if (hasPrimaryOutput()) {
602 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
603 // the device returned is not necessarily reachable via this output
604 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
605 // force routing command to audio hardware when ending call
606 // even if no device change is needed
607 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
608 rxDevice = mPrimaryOutput->device();
609 }
Eric Laurente552edb2014-03-10 17:42:56 -0700610
Eric Laurent87ffa392015-05-22 10:32:38 -0700611 if (state == AUDIO_MODE_IN_CALL) {
612 updateCallRouting(rxDevice, delayMs);
613 } else if (oldState == AUDIO_MODE_IN_CALL) {
614 if (mCallRxPatch != 0) {
615 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
616 mCallRxPatch.clear();
617 }
618 if (mCallTxPatch != 0) {
619 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
620 mCallTxPatch.clear();
621 }
622 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
623 } else {
624 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700625 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700626 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700627
628 // reevaluate routing on all outputs in case tracks have been started during the call
629 for (size_t i = 0; i < mOutputs.size(); i++) {
630 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
631 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
632 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
Yung Ti Suf60c8242018-05-10 18:07:26 +0800633 setOutputDevice(desc, newDevice, (newDevice != AUDIO_DEVICE_NONE), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700634 }
635 }
636
Eric Laurente552edb2014-03-10 17:42:56 -0700637 if (isStateInCall(state)) {
638 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700639 // force reevaluating accessibility routing when call starts
640 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700641 }
642
643 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700644 if (state == AUDIO_MODE_RINGTONE &&
645 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700646 mLimitRingtoneVolume = true;
647 } else {
648 mLimitRingtoneVolume = false;
649 }
650}
651
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700652audio_mode_t AudioPolicyManager::getPhoneState() {
653 return mEngine->getPhoneState();
654}
655
Eric Laurente0720872014-03-11 09:30:41 -0700656void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700657 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700658{
François Gaffie2110e042015-03-24 08:41:51 +0100659 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700660 if (config == mEngine->getForceUse(usage)) {
661 return;
662 }
Eric Laurente552edb2014-03-10 17:42:56 -0700663
François Gaffie2110e042015-03-24 08:41:51 +0100664 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
665 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
666 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700667 }
François Gaffie2110e042015-03-24 08:41:51 +0100668 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
669 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
670 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700671
672 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700673 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800674
Eric Laurentdc462862016-07-19 12:29:53 -0700675 //FIXME: workaround for truncated touch sounds
676 // to be removed when the problem is handled by system UI
677 uint32_t delayMs = 0;
678 uint32_t waitMs = 0;
679 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
680 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
681 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700682 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700683 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
Eric Laurentdc462862016-07-19 12:29:53 -0700684 waitMs = updateCallRouting(newDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700685 }
Eric Laurente552edb2014-03-10 17:42:56 -0700686 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700687 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
688 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
689 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700690 waitMs = setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE),
691 delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700692 }
Eric Laurente552edb2014-03-10 17:42:56 -0700693 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700694 applyStreamVolumes(outputDesc, newDevice, waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700695 }
696 }
697
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800698 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800699 audio_devices_t newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700700 // Force new input selection if the new device can not be reached via current input
Eric Laurentfb66dd92016-01-28 18:32:03 -0800701 if (activeDesc->mProfile->getSupportedDevices().types() &
702 (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
703 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700704 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800705 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700706 }
Eric Laurente552edb2014-03-10 17:42:56 -0700707 }
Eric Laurente552edb2014-03-10 17:42:56 -0700708}
709
Eric Laurente0720872014-03-11 09:30:41 -0700710void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700711{
712 ALOGV("setSystemProperty() property %s, value %s", property, value);
713}
714
Michael Chana94fbb22018-04-24 14:31:19 +1000715// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
716// search to profiles for direct outputs.
717sp<IOProfile> AudioPolicyManager::getProfileForOutput(
718 audio_devices_t device,
719 uint32_t samplingRate,
720 audio_format_t format,
721 audio_channel_mask_t channelMask,
722 audio_output_flags_t flags,
723 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700724{
Michael Chana94fbb22018-04-24 14:31:19 +1000725 if (directOnly) {
726 // only retain flags that will drive the direct output profile selection
727 // if explicitly requested
728 static const uint32_t kRelevantFlags =
729 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
730 AUDIO_OUTPUT_FLAG_VOIP_RX);
731 flags =
732 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
733 }
Eric Laurent861a6282015-05-18 15:40:16 -0700734
735 sp<IOProfile> profile;
736
Mikhail Naganovd4120142017-12-06 15:49:22 -0800737 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800738 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent861a6282015-05-18 15:40:16 -0700739 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700740 samplingRate, NULL /*updatedSamplingRate*/,
741 format, NULL /*updatedFormat*/,
742 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700743 flags)) {
744 continue;
745 }
746 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100747 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700748 continue;
749 }
Michael Chana94fbb22018-04-24 14:31:19 +1000750 if (!directOnly) return curProfile;
751 // when searching for direct outputs, if several profiles are compatible, give priority
752 // to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100753 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700754 continue;
755 }
756 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100757 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700758 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700759 }
Eric Laurente552edb2014-03-10 17:42:56 -0700760 }
761 }
Eric Laurent861a6282015-05-18 15:40:16 -0700762 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700763}
764
Eric Laurentf4e63452017-11-06 19:31:46 +0000765audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700766{
Eric Laurent3b73df72014-03-11 09:06:29 -0700767 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700768 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800769
770 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
771 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
772 // format, flags, etc. This may result in some discrepancy for functions that utilize
773 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
774 // and AudioSystem::getOutputSamplingRate().
775
Eric Laurentf4e63452017-11-06 19:31:46 +0000776 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
jiabin40573322018-11-08 12:08:02 -0800777 audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -0700778
Eric Laurentf4e63452017-11-06 19:31:46 +0000779 ALOGV("getOutput() stream %d selected device %08x, output %d", stream, device, output);
780 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700781}
782
Eric Laurente83b55d2014-11-14 10:06:21 -0800783status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
784 audio_io_handle_t *output,
785 audio_session_t session,
786 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700787 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800788 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200789 audio_output_flags_t *flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700790 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800791 audio_port_handle_t *portId)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700792{
Eric Laurente83b55d2014-11-14 10:06:21 -0800793 audio_attributes_t attributes;
Eric Laurent8fc147b2018-07-22 19:13:55 -0700794 DeviceVector outputDevices;
795 routing_strategy strategy;
796 audio_devices_t device;
Eric Laurent97ac8712018-07-27 18:59:02 -0700797 const audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Mikhail Naganov100f0122018-11-29 11:22:16 -0800798 audio_devices_t msdDevice =
799 getModuleDeviceTypes(mAvailableOutputDevices, AUDIO_HARDWARE_MODULE_ID_MSD);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700800
Eric Laurent8f42ea12018-08-08 09:08:25 -0700801 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
802 if (*portId != AUDIO_PORT_HANDLE_NONE) {
803 return INVALID_OPERATION;
804 }
805
Eric Laurente83b55d2014-11-14 10:06:21 -0800806 if (attr != NULL) {
807 if (!isValidAttributes(attr)) {
808 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
809 attr->usage, attr->content_type, attr->flags,
810 attr->tags);
811 return BAD_VALUE;
812 }
813 attributes = *attr;
814 } else {
815 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
816 ALOGE("getOutputForAttr(): invalid stream type");
817 return BAD_VALUE;
818 }
819 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700820 }
Eric Laurent20b9ef02016-12-05 11:03:16 -0800821
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700822 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
Eric Laurent97ac8712018-07-27 18:59:02 -0700823 " session %d selectedDeviceId %d",
824 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
825 session, requestedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700826
Eric Laurent97ac8712018-07-27 18:59:02 -0700827 *stream = streamTypefromAttributesInt(&attributes);
828
829 strategy = getStrategyForAttr(&attributes);
830
Scott Randolph7b1fd232018-06-18 15:33:03 -0700831 // First check for explicit routing (eg. setPreferredDevice)
Eric Laurent97ac8712018-07-27 18:59:02 -0700832 if (requestedDeviceId != AUDIO_PORT_HANDLE_NONE) {
833 sp<DeviceDescriptor> deviceDesc =
834 mAvailableOutputDevices.getDeviceFromId(requestedDeviceId);
835 device = deviceDesc->type();
Scott Randolph7b1fd232018-06-18 15:33:03 -0700836 } else {
837 // If no explict route, is there a matching dynamic policy that applies?
838 sp<SwAudioOutputDescriptor> desc;
839 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
840 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
841 if (!audio_has_proportional_frames(config->format)) {
842 return BAD_VALUE;
843 }
844 *stream = streamTypefromAttributesInt(&attributes);
845 *output = desc->mIoHandle;
Eric Laurent97ac8712018-07-27 18:59:02 -0700846 AudioMix *mix = desc->mPolicyMix;
847 sp<DeviceDescriptor> deviceDesc =
848 mAvailableOutputDevices.getDevice(mix->mDeviceType, mix->mDeviceAddress);
849 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Scott Randolph7b1fd232018-06-18 15:33:03 -0700850 ALOGV("getOutputForAttr() returns output %d", *output);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700851 goto exit;
Scott Randolph7b1fd232018-06-18 15:33:03 -0700852 }
853
854 // Virtual sources must always be dynamicaly or explicitly routed
855 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
856 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
857 return BAD_VALUE;
858 }
Eric Laurent97ac8712018-07-27 18:59:02 -0700859 device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700860 }
Scott Randolph7b1fd232018-06-18 15:33:03 -0700861
Eric Laurente83b55d2014-11-14 10:06:21 -0800862 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200863 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -0700864 }
865
Nadav Barb2f18162018-07-18 13:01:53 +0300866 // Set incall music only if device was explicitly set, and fallback to the device which is
867 // chosen by the engine if not.
868 // FIXME: provide a more generic approach which is not device specific and move this back
869 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +0200870 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
Nadav Barb2f18162018-07-18 13:01:53 +0300871 if (device == AUDIO_DEVICE_OUT_TELEPHONY_TX &&
Nadav Bar20919492018-11-20 10:20:51 +0200872 (*stream == AUDIO_STREAM_MUSIC || attributes.usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +0300873 audio_is_linear_pcm(config->format) &&
874 isInCall()) {
Eric Laurent97ac8712018-07-27 18:59:02 -0700875 if (requestedDeviceId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +0300876 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
877 } else {
Eric Laurent97ac8712018-07-27 18:59:02 -0700878 // Get the devce type directly from the engine to bypass preferred route logic
Nadav Barb2f18162018-07-18 13:01:53 +0300879 device = mEngine->getDeviceForStrategy(strategy);
880 }
881 }
882
Glenn Kasten49f36ba2017-12-06 13:02:02 -0800883 ALOGV("getOutputForAttr() device 0x%x, sampling rate %d, format %#x, channel mask %#x, "
884 "flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +0200885 device, config->sample_rate, config->format, config->channel_mask, *flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700886
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100887 *output = AUDIO_IO_HANDLE_NONE;
888 if (msdDevice != AUDIO_DEVICE_NONE) {
889 *output = getOutputForDevice(msdDevice, session, *stream, config, flags);
890 if (*output != AUDIO_IO_HANDLE_NONE && setMsdPatch(device) == NO_ERROR) {
891 ALOGV("%s() Using MSD device 0x%x instead of device 0x%x",
892 __func__, msdDevice, device);
893 device = msdDevice;
894 } else {
895 *output = AUDIO_IO_HANDLE_NONE;
896 }
897 }
898 if (*output == AUDIO_IO_HANDLE_NONE) {
899 *output = getOutputForDevice(device, session, *stream, config, flags);
900 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800901 if (*output == AUDIO_IO_HANDLE_NONE) {
902 return INVALID_OPERATION;
903 }
Paul McLeanaa981192015-03-21 09:55:15 -0700904
Eric Laurent8fc147b2018-07-22 19:13:55 -0700905 outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -0700906 *selectedDeviceId = outputDevices.size() > 0 ? outputDevices.itemAt(0)->getId()
907 : AUDIO_PORT_HANDLE_NONE;
908
Eric Laurent8fc147b2018-07-22 19:13:55 -0700909exit:
910 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
911 .format = config->format,
912 .channel_mask = config->channel_mask };
Eric Laurent8f42ea12018-08-08 09:08:25 -0700913 *portId = AudioPort::getNextUniqueId();
914
Eric Laurent8fc147b2018-07-22 19:13:55 -0700915 sp<TrackClientDescriptor> clientDesc =
Eric Laurent97ac8712018-07-27 18:59:02 -0700916 new TrackClientDescriptor(*portId, uid, session, attributes, clientConfig,
917 requestedDeviceId, *stream,
918 getStrategyForAttr(&attributes),
919 *flags);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700920 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Andy Hung39efb7a2018-09-26 15:39:28 -0700921 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700922
923 ALOGV(" getOutputForAttr() returns output %d selectedDeviceId %d for port ID %d",
924 *output, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -0700925
Eric Laurente83b55d2014-11-14 10:06:21 -0800926 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700927}
928
929audio_io_handle_t AudioPolicyManager::getOutputForDevice(
930 audio_devices_t device,
Kevin Rocard169753c2017-03-06 14:18:23 -0800931 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700932 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -0800933 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200934 audio_output_flags_t *flags)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700935{
Andy Hungc88b0642018-04-27 15:42:35 -0700936 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700937 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700938
Eric Laurente552edb2014-03-10 17:42:56 -0700939 // open a direct output if required by specified parameters
940 //force direct flag if offload flag is set: offloading implies a direct output stream
941 // and all common behaviors are driven by checking only the direct flag
942 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +0200943 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
944 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700945 }
Nadav Bar766fb022018-01-07 12:18:03 +0200946 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
947 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -0700948 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800949 // only allow deep buffering for music stream type
950 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +0200951 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700952 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +0200953 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700954 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
955 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +0200956 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800957 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700958 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +0200959 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700960 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +0200961 audio_is_linear_pcm(config->format) &&
962 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200963 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700964 AUDIO_OUTPUT_FLAG_DIRECT);
965 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700966 }
Eric Laurente552edb2014-03-10 17:42:56 -0700967
Nadav Bar766fb022018-01-07 12:18:03 +0200968
Eric Laurentb732cf52014-09-24 19:08:21 -0700969 sp<IOProfile> profile;
970
971 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700972 // and not explicitly requested
Nadav Bar766fb022018-01-07 12:18:03 +0200973 if (((*flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Eric Laurentfe231122017-11-17 17:48:06 -0800974 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
975 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
Eric Laurentb732cf52014-09-24 19:08:21 -0700976 goto non_direct_output;
977 }
978
Andy Hung2ddee192015-12-18 17:34:44 -0800979 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
980 // This prevents creating an offloaded track and tearing it down immediately after start
981 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700982 // FIXME: We should check the audio session here but we do not have it in this context.
983 // This may prevent offloading in rare situations where effects are left active by apps
984 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700985
Nadav Bar766fb022018-01-07 12:18:03 +0200986 if (((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800987 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Michael Chana94fbb22018-04-24 14:31:19 +1000988 profile = getProfileForOutput(device,
989 config->sample_rate,
990 config->format,
991 config->channel_mask,
992 (audio_output_flags_t)*flags,
993 true /* directOnly */);
Eric Laurente552edb2014-03-10 17:42:56 -0700994 }
995
Eric Laurent1c333e22014-05-20 10:48:17 -0700996 if (profile != 0) {
Andy Hungc88b0642018-04-27 15:42:35 -0700997 // exclusive outputs for MMAP and Offload are enforced by different session ids.
998 for (size_t i = 0; i < mOutputs.size(); i++) {
999 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1000 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1001 // reuse direct output if currently open by the same client
1002 // and configured with same parameters
1003 if ((config->sample_rate == desc->mSamplingRate) &&
Andy Hung5659ed52018-04-30 10:31:26 -07001004 (config->format == desc->mFormat) &&
Andy Hungc88b0642018-04-27 15:42:35 -07001005 (config->channel_mask == desc->mChannelMask) &&
1006 (session == desc->mDirectClientSession)) {
1007 desc->mDirectOpenCount++;
1008 ALOGI("getOutputForDevice() reusing direct output %d for session %d",
1009 mOutputs.keyAt(i), session);
1010 return mOutputs.keyAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001011 }
1012 }
1013 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08001014
1015 if (!profile->canOpenNewIo()) {
1016 goto non_direct_output;
Eric Laurente552edb2014-03-10 17:42:56 -07001017 }
Eric Laurent861a6282015-05-18 15:40:16 -07001018
Eric Laurent3974e3b2017-12-07 17:58:43 -08001019 sp<SwAudioOutputDescriptor> outputDesc =
1020 new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurent53b810e2017-12-10 17:25:10 -08001021
Mikhail Naganov708e0382018-05-30 09:53:04 -07001022 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -08001023 String8 address = outputDevices.size() > 0 ? outputDevices.itemAt(0)->mAddress
1024 : String8("");
1025
Dean Wheatley3023b382018-08-09 07:42:40 +10001026 // MSD patch may be using the only output stream that can service this request. Release
1027 // MSD patch to prioritize this request over any active output on MSD.
1028 AudioPatchCollection msdPatches = getMsdPatches();
1029 for (size_t i = 0; i < msdPatches.size(); i++) {
1030 const auto& patch = msdPatches[i];
1031 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1032 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1033 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
1034 (sink->ext.device.type & device) != AUDIO_DEVICE_NONE &&
1035 (address.isEmpty() || strncmp(sink->ext.device.address, address.string(),
1036 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
1037 releaseAudioPatch(patch->mHandle, mUidCached);
1038 break;
1039 }
1040 }
1041 }
1042
Nadav Bar766fb022018-01-07 12:18:03 +02001043 status = outputDesc->open(config, device, address, stream, *flags, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07001044
1045 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001046 if (status != NO_ERROR ||
Eric Laurentfe231122017-11-17 17:48:06 -08001047 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
Andy Hung5659ed52018-04-30 10:31:26 -07001048 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->mFormat) ||
Eric Laurentfe231122017-11-17 17:48:06 -08001049 (config->channel_mask != 0 && config->channel_mask != outputDesc->mChannelMask)) {
1050 ALOGV("getOutputForDevice() failed opening direct output: output %d sample rate %d %d,"
1051 "format %d %d, channel mask %04x %04x", output, config->sample_rate,
1052 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
1053 config->channel_mask, outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001054 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001055 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07001056 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001057 // fall back to mixer output if possible when the direct output could not be open
Eric Laurentfe231122017-11-17 17:48:06 -08001058 if (audio_is_linear_pcm(config->format) &&
1059 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -08001060 goto non_direct_output;
1061 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001062 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001063 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001064 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -08001065 outputDesc->mDirectClientSession = session;
1066
Eric Laurente552edb2014-03-10 17:42:56 -07001067 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001068 mPreviousOutputs = mOutputs;
Eric Laurentf4e63452017-11-06 19:31:46 +00001069 ALOGV("getOutputForDevice() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001070 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001071 return output;
1072 }
1073
Eric Laurentb732cf52014-09-24 19:08:21 -07001074non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001075
1076 // A request for HW A/V sync cannot fallback to a mixed output because time
1077 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001078 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001079 return AUDIO_IO_HANDLE_NONE;
1080 }
1081
Eric Laurente552edb2014-03-10 17:42:56 -07001082 // ignoring channel mask due to downmix capability in mixer
1083
1084 // open a non direct output
1085
1086 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001087 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001088 // get which output is suitable for the specified stream. The actual
1089 // routing change will happen when startOutput() will be called
1090 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1091
Eric Laurent8838a382014-09-08 16:44:28 -07001092 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001093 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabin40573322018-11-08 12:08:02 -08001094 output = selectOutput(outputs, *flags, config->format,
1095 config->channel_mask, config->sample_rate);
Eric Laurente552edb2014-03-10 17:42:56 -07001096 }
Eric Laurentf4e63452017-11-06 19:31:46 +00001097 ALOGW_IF((output == 0), "getOutputForDevice() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001098 "sampling rate %d, format %#x, channels %#x, flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +02001099 stream, config->sample_rate, config->format, config->channel_mask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001100
Eric Laurente552edb2014-03-10 17:42:56 -07001101 return output;
1102}
1103
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001104sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001105 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001106 if (msdModule != 0) {
1107 DeviceVector msdInputDevices = mAvailableInputDevices.getDevicesFromHwModule(
1108 msdModule->getHandle());
1109 if (!msdInputDevices.isEmpty()) return msdInputDevices.itemAt(0);
1110 }
1111 return 0;
1112}
1113
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001114const AudioPatchCollection AudioPolicyManager::getMsdPatches() const {
1115 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001116 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1117 if (msdModule != 0) {
1118 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1119 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1120 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1121 const struct audio_port_config *source = &patch->mPatch.sources[j];
1122 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1123 source->ext.device.hw_module == msdModule->getHandle()) {
1124 msdPatches.addAudioPatch(patch->mHandle, patch);
1125 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001126 }
1127 }
1128 }
1129 return msdPatches;
1130}
1131
1132status_t AudioPolicyManager::getBestMsdAudioProfileFor(audio_devices_t outputDevice,
1133 bool hwAvSync, audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1134{
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001135 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001136 if (msdModule == nullptr) {
1137 ALOGE("%s() unable to get MSD module", __func__);
1138 return NO_INIT;
1139 }
1140 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(outputDevice);
1141 if (deviceModule == nullptr) {
1142 ALOGE("%s() unable to get module for %#x", __func__, outputDevice);
1143 return NO_INIT;
1144 }
1145 const InputProfileCollection &inputProfiles = msdModule->getInputProfiles();
1146 if (inputProfiles.isEmpty()) {
1147 ALOGE("%s() no input profiles for MSD module", __func__);
1148 return NO_INIT;
1149 }
1150 const OutputProfileCollection &outputProfiles = deviceModule->getOutputProfiles();
1151 if (outputProfiles.isEmpty()) {
1152 ALOGE("%s() no output profiles for device %#x", __func__, outputDevice);
1153 return NO_INIT;
1154 }
1155 AudioProfileVector msdProfiles;
1156 // Each IOProfile represents a MixPort from audio_policy_configuration.xml
1157 for (const auto &inProfile : inputProfiles) {
1158 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0)) {
1159 msdProfiles.appendVector(inProfile->getAudioProfiles());
1160 }
1161 }
1162 AudioProfileVector deviceProfiles;
1163 for (const auto &outProfile : outputProfiles) {
1164 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0)) {
1165 deviceProfiles.appendVector(outProfile->getAudioProfiles());
1166 }
1167 }
1168 struct audio_config_base bestSinkConfig;
1169 status_t result = msdProfiles.findBestMatchingOutputConfig(deviceProfiles,
1170 compressedFormatsOrder, surroundChannelMasksOrder, true /*preferHigherSamplingRates*/,
1171 &bestSinkConfig);
1172 if (result != NO_ERROR) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001173 ALOGD("%s() no matching profiles found for device: %#x, hwAvSync: %d",
1174 __func__, outputDevice, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001175 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001176 }
1177 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1178 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1179 sinkConfig->format = bestSinkConfig.format;
1180 // For encoded streams force direct flag to prevent downstream mixing.
1181 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1182 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
1183 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1184 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1185 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1186 sourceConfig->format = bestSinkConfig.format;
1187 // Copy input stream directly without any processing (e.g. resampling).
1188 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1189 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1190 if (hwAvSync) {
1191 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1192 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1193 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1194 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1195 }
1196 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1197 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1198 sinkConfig->config_mask |= config_mask;
1199 sourceConfig->config_mask |= config_mask;
1200 return NO_ERROR;
1201}
1202
1203PatchBuilder AudioPolicyManager::buildMsdPatch(audio_devices_t outputDevice) const
1204{
1205 PatchBuilder patchBuilder;
1206 patchBuilder.addSource(getMsdAudioInDevice()).
1207 addSink(findDevice(mAvailableOutputDevices, outputDevice));
1208 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1209 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
1210 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1211 // For now, we just forcefully try with HwAvSync first.
1212 status_t res = getBestMsdAudioProfileFor(outputDevice, true /*hwAvSync*/,
1213 &sourceConfig, &sinkConfig) == NO_ERROR ? NO_ERROR :
1214 getBestMsdAudioProfileFor(
1215 outputDevice, false /*hwAvSync*/, &sourceConfig, &sinkConfig);
1216 if (res == NO_ERROR) {
1217 // Found a matching profile for encoded audio. Re-create PatchBuilder with this config.
1218 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1219 }
1220 ALOGV("%s() no matching profile found. Fall through to default PCM patch"
1221 " supporting PCM format conversion.", __func__);
1222 return patchBuilder;
1223}
1224
1225status_t AudioPolicyManager::setMsdPatch(audio_devices_t outputDevice) {
1226 ALOGV("%s() for outputDevice %#x", __func__, outputDevice);
1227 if (outputDevice == AUDIO_DEVICE_NONE) {
1228 // Use media strategy for unspecified output device. This should only
1229 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1230 // therefore invalidate explicit routing requests.
1231 outputDevice = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
1232 }
1233 PatchBuilder patchBuilder = buildMsdPatch(outputDevice);
1234 const struct audio_patch* patch = patchBuilder.patch();
1235 const AudioPatchCollection msdPatches = getMsdPatches();
1236 if (!msdPatches.isEmpty()) {
1237 LOG_ALWAYS_FATAL_IF(msdPatches.size() > 1,
1238 "The current MSD prototype only supports one output patch");
1239 sp<AudioPatch> currentPatch = msdPatches.valueAt(0);
1240 if (audio_patches_are_equal(&currentPatch->mPatch, patch)) {
1241 return NO_ERROR;
1242 }
1243 releaseAudioPatch(currentPatch->mHandle, mUidCached);
1244 }
1245 status_t status = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1246 patch, 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1247 ALOGE_IF(status != NO_ERROR, "%s() error %d creating MSD audio patch", __func__, status);
1248 ALOGI_IF(status == NO_ERROR, "%s() Patch created from MSD_IN to "
1249 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__, outputDevice,
1250 patch->sources[0].format, patch->sources[0].channel_mask, patch->sources[0].sample_rate);
1251 return status;
1252}
1253
Eric Laurente0720872014-03-11 09:30:41 -07001254audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001255 audio_output_flags_t flags,
jiabin40573322018-11-08 12:08:02 -08001256 audio_format_t format,
1257 audio_channel_mask_t channelMask,
1258 uint32_t samplingRate)
Eric Laurente552edb2014-03-10 17:42:56 -07001259{
1260 // select one output among several that provide a path to a particular device or set of
1261 // devices (the list was previously build by getOutputsForDevice()).
1262 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001263 // 1: the output supporting haptic playback when requesting haptic playback
1264 // 2: the output with the highest number of requested policy flags
1265 // 3: the output with the bit depth the closest to the requested one
1266 // 4: the primary output
1267 // 5: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001268
1269 if (outputs.size() == 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001270 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001271 }
1272 if (outputs.size() == 1) {
1273 return outputs[0];
1274 }
1275
1276 int maxCommonFlags = 0;
jiabin40573322018-11-08 12:08:02 -08001277 const size_t hapticChannelCount = audio_channel_count_from_out_mask(
1278 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001279 audio_io_handle_t outputForFlags = AUDIO_IO_HANDLE_NONE;
1280 audio_io_handle_t outputForPrimary = AUDIO_IO_HANDLE_NONE;
1281 audio_io_handle_t outputForFormat = AUDIO_IO_HANDLE_NONE;
Eric Laurente6930022016-02-11 10:20:40 -08001282 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1283 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001284
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001285 for (audio_io_handle_t output : outputs) {
1286 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001287 if (!outputDesc->isDuplicated()) {
chenhg1794d712018-10-09 15:20:37 -07001288 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1289 continue;
1290 }
jiabin40573322018-11-08 12:08:02 -08001291 // If haptic channel is specified, use the haptic output if present.
1292 // When using haptic output, same audio format and sample rate are required.
1293 if (hapticChannelCount > 0) {
1294 // If haptic channel is specified, use the first output that
1295 // support haptic playback.
1296 if (audio_channel_count_from_out_mask(
1297 outputDesc->mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL) >= hapticChannelCount
1298 && format == outputDesc->mFormat
1299 && samplingRate == outputDesc->mSamplingRate) {
1300 return output;
1301 }
1302 } else {
1303 // When haptic channel is not specified, skip haptic output.
1304 if (outputDesc->mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL) {
1305 continue;
1306 }
1307 }
1308
Eric Laurent8838a382014-09-08 16:44:28 -07001309 // if a valid format is specified, skip output if not compatible
1310 if (format != AUDIO_FORMAT_INVALID) {
chenhg1794d712018-10-09 15:20:37 -07001311 if (!audio_is_linear_pcm(format)) {
Eric Laurent8838a382014-09-08 16:44:28 -07001312 continue;
1313 }
Eric Laurente6930022016-02-11 10:20:40 -08001314 if (AudioPort::isBetterFormatMatch(
1315 outputDesc->mFormat, bestFormat, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001316 outputForFormat = output;
Eric Laurente6930022016-02-11 10:20:40 -08001317 bestFormat = outputDesc->mFormat;
1318 }
Eric Laurent8838a382014-09-08 16:44:28 -07001319 }
1320
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001321 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001322 if (commonFlags >= maxCommonFlags) {
1323 if (commonFlags == maxCommonFlags) {
Andy Hungc9901522017-11-10 20:07:54 -08001324 if (format != AUDIO_FORMAT_INVALID
1325 && AudioPort::isBetterFormatMatch(
1326 outputDesc->mFormat, bestFormatForFlags, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001327 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001328 bestFormatForFlags = outputDesc->mFormat;
1329 }
1330 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001331 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001332 maxCommonFlags = commonFlags;
1333 bestFormatForFlags = outputDesc->mFormat;
1334 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001335 ALOGV("selectOutput() commonFlags for output %d, %04x", output, commonFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001336 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001337 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001338 outputForPrimary = output;
Eric Laurente552edb2014-03-10 17:42:56 -07001339 }
1340 }
1341 }
1342
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001343 if (outputForFlags != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001344 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001345 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001346 if (outputForFormat != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001347 return outputForFormat;
1348 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001349 if (outputForPrimary != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001350 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001351 }
1352
1353 return outputs[0];
1354}
1355
Eric Laurent8fc147b2018-07-22 19:13:55 -07001356status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001357{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001358 ALOGV("%s portId %d", __FUNCTION__, portId);
1359
1360 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1361 if (outputDesc == 0) {
1362 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001363 return BAD_VALUE;
1364 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001365 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001366
Eric Laurent8fc147b2018-07-22 19:13:55 -07001367 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001368 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001369
Eric Laurent733ce942017-12-07 12:18:25 -08001370 status_t status = outputDesc->start();
1371 if (status != NO_ERROR) {
1372 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001373 }
1374
Eric Laurent97ac8712018-07-27 18:59:02 -07001375 uint32_t delayMs;
1376 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001377
1378 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001379 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001380 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001381 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001382 if (delayMs != 0) {
1383 usleep(delayMs * 1000);
1384 }
1385
1386 return status;
1387}
1388
Eric Laurent97ac8712018-07-27 18:59:02 -07001389status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1390 const sp<TrackClientDescriptor>& client,
1391 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001392{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001393 // cannot start playback of STREAM_TTS if any other output is being used
1394 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001395
1396 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001397 audio_stream_type_t stream = client->stream();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001398 if (stream == AUDIO_STREAM_TTS) {
1399 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001400 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001401 return INVALID_OPERATION;
1402 } else {
1403 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1404 }
1405 } else {
1406 // some playback other than beacon starts
1407 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1408 }
1409
Eric Laurent77305a62016-07-25 16:39:22 -07001410 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001411 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001412 bool force = !outputDesc->isActive() &&
1413 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001414
Eric Laurent97ac8712018-07-27 18:59:02 -07001415 audio_devices_t device = AUDIO_DEVICE_NONE;
1416 AudioMix *policyMix = NULL;
1417 const char *address = NULL;
1418 if (outputDesc->mPolicyMix != NULL) {
1419 policyMix = outputDesc->mPolicyMix;
1420 address = policyMix->mDeviceAddress.string();
1421 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1422 device = policyMix->mDeviceType;
1423 } else {
1424 device = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1425 }
1426 }
1427
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001428 // requiresMuteCheck is false when we can bypass mute strategy.
1429 // It covers a common case when there is no materially active audio
1430 // and muting would result in unnecessary delay and dropped audio.
1431 const uint32_t outputLatencyMs = outputDesc->latency();
1432 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1433
Eric Laurente552edb2014-03-10 17:42:56 -07001434 // increment usage count for this stream on the requested output:
1435 // NOTE that the usage count is the same for duplicated output and hardware output which is
1436 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001437 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001438
1439 if (client->hasPreferredDevice(true)) {
1440 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
1441 if (device != outputDesc->device()) {
1442 checkStrategyRoute(getStrategy(stream), outputDesc->mIoHandle);
1443 }
1444 }
Eric Laurente552edb2014-03-10 17:42:56 -07001445
Eric Laurent36829f92017-04-07 19:04:42 -07001446 if (stream == AUDIO_STREAM_MUSIC) {
1447 selectOutputForMusicEffects();
1448 }
1449
Eric Laurent592dd7b2018-08-05 18:58:48 -07001450 if (outputDesc->streamActiveCount(stream) == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001451 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001452 if (device == AUDIO_DEVICE_NONE) {
1453 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001454 }
Eric Laurent36829f92017-04-07 19:04:42 -07001455
Eric Laurente552edb2014-03-10 17:42:56 -07001456 routing_strategy strategy = getStrategy(stream);
1457 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001458 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1459 (beaconMuteLatency > 0);
1460 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001461 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001462 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001463 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001464 // An output has a shared device if
1465 // - managed by the same hw module
1466 // - supports the currently selected device
1467 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
1468 && (desc->supportedDevices() & device) != AUDIO_DEVICE_NONE;
1469
Eric Laurent77305a62016-07-25 16:39:22 -07001470 // force a device change if any other output is:
1471 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001472 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001473 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001474 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001475 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001476 // change the device currently selected by the other output.
1477 if (sharedDevice &&
Eric Laurent77305a62016-07-25 16:39:22 -07001478 desc->device() != device &&
Eric Laurent77305a62016-07-25 16:39:22 -07001479 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001480 force = true;
1481 }
1482 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001483 // a notification so that audio focus effect can propagate, or that a mute/unmute
1484 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001485 const uint32_t latencyMs = desc->latency();
1486 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1487
1488 if (shouldWait && isActive && (waitMs < latencyMs)) {
1489 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001490 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001491
1492 // Require mute check if another output is on a shared device
1493 // and currently active to have proper drain and avoid pops.
1494 // Note restoring AudioTracks onto this output needs to invoke
1495 // a volume ramp if there is no mute.
1496 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001497 }
1498 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001499
1500 const uint32_t muteWaitMs =
1501 setOutputDevice(outputDesc, device, force, 0, NULL, address, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001502
Eric Laurente552edb2014-03-10 17:42:56 -07001503 // apply volume rules for current stream and device if necessary
1504 checkAndSetVolume(stream,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001505 mVolumeCurves->getVolumeIndex(stream, outputDesc->device()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001506 outputDesc,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001507 outputDesc->device());
Eric Laurente552edb2014-03-10 17:42:56 -07001508
1509 // update the outputs if starting an output with a stream that can affect notification
1510 // routing
1511 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001512
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001513 // force reevaluating accessibility routing when ringtone or alarm starts
1514 if (strategy == STRATEGY_SONIFICATION) {
1515 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1516 }
Eric Laurentdc462862016-07-19 12:29:53 -07001517
1518 if (waitMs > muteWaitMs) {
1519 *delayMs = waitMs - muteWaitMs;
1520 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001521
1522 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1523 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1524 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1525 // change occurs after the MixerThread starts and causes a stream volume
1526 // glitch.
1527 //
1528 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001529 }
Eric Laurentdc462862016-07-19 12:29:53 -07001530
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001531 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1532 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1533 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1534 }
1535
Eric Laurent97ac8712018-07-27 18:59:02 -07001536 // Automatically enable the remote submix input when output is started on a re routing mix
1537 // of type MIX_TYPE_RECORDERS
1538 if (audio_is_remote_submix_device(device) && policyMix != NULL &&
1539 policyMix->mMixType == MIX_TYPE_RECORDERS) {
1540 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1541 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1542 address,
1543 "remote-submix");
1544 }
1545
Eric Laurente552edb2014-03-10 17:42:56 -07001546 return NO_ERROR;
1547}
1548
Eric Laurent8fc147b2018-07-22 19:13:55 -07001549status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001550{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001551 ALOGV("%s portId %d", __FUNCTION__, portId);
1552
1553 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1554 if (outputDesc == 0) {
1555 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001556 return BAD_VALUE;
1557 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001558 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001559
Eric Laurent97ac8712018-07-27 18:59:02 -07001560 ALOGV("stopOutput() output %d, stream %d, session %d",
1561 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07001562
Eric Laurent97ac8712018-07-27 18:59:02 -07001563 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08001564
Eric Laurent733ce942017-12-07 12:18:25 -08001565 if (status == NO_ERROR ) {
1566 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001567 }
1568 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001569}
1570
Eric Laurent97ac8712018-07-27 18:59:02 -07001571status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1572 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07001573{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001574 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07001575 audio_stream_type_t stream = client->stream();
1576
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001577 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1578
Eric Laurent592dd7b2018-08-05 18:58:48 -07001579 if (outputDesc->streamActiveCount(stream) > 0) {
1580 if (outputDesc->streamActiveCount(stream) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001581 // Automatically disable the remote submix input when output is stopped on a
1582 // re routing mix of type MIX_TYPE_RECORDERS
1583 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1584 outputDesc->mPolicyMix != NULL &&
1585 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1586 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1587 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1588 outputDesc->mPolicyMix->mDeviceAddress,
1589 "remote-submix");
1590 }
1591 }
1592 bool forceDeviceUpdate = false;
1593 if (client->hasPreferredDevice(true)) {
1594 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1595 forceDeviceUpdate = true;
1596 }
1597
Eric Laurente552edb2014-03-10 17:42:56 -07001598 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07001599 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07001600
Eric Laurente552edb2014-03-10 17:42:56 -07001601 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001602 if (outputDesc->streamActiveCount(stream) == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001603 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001604 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001605 // delay the device switch by twice the latency because stopOutput() is executed when
1606 // the track stop() command is received and at that time the audio track buffer can
1607 // still contain data that needs to be drained. The latency only covers the audio HAL
1608 // and kernel buffers. Also the latency does not always include additional delay in the
1609 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001610 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001611
1612 // force restoring the device selection on other active outputs if it differs from the
1613 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001614 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001615 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001616 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001617 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001618 desc->isActive() &&
1619 outputDesc->sharesHwModuleWith(desc) &&
1620 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001621 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1622 bool force = desc->device() != newDevice2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001623
Eric Laurentc75307b2015-03-17 15:29:32 -07001624 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001625 newDevice2,
1626 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001627 delayMs);
1628 // re-apply device specific volume if not done by setOutputDevice()
1629 if (!force) {
1630 applyStreamVolumes(desc, newDevice2, delayMs);
1631 }
Eric Laurente552edb2014-03-10 17:42:56 -07001632 }
1633 }
1634 // update the outputs if stopping one with a stream that can affect notification routing
1635 handleNotificationRoutingForStream(stream);
1636 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001637
1638 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1639 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1640 setStrategyMute(STRATEGY_SONIFICATION, false, outputDesc);
1641 }
1642
Eric Laurent36829f92017-04-07 19:04:42 -07001643 if (stream == AUDIO_STREAM_MUSIC) {
1644 selectOutputForMusicEffects();
1645 }
Eric Laurente552edb2014-03-10 17:42:56 -07001646 return NO_ERROR;
1647 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001648 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001649 return INVALID_OPERATION;
1650 }
1651}
1652
Eric Laurent8fc147b2018-07-22 19:13:55 -07001653void AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001654{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001655 ALOGV("%s portId %d", __FUNCTION__, portId);
1656
1657 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1658 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07001659 // If an output descriptor is closed due to a device routing change,
1660 // then there are race conditions with releaseOutput from tracks
1661 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
1662 // destroyed shortly thereafter.
1663 //
1664 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07001665 ALOGW("releaseOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001666 return;
1667 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001668
1669 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001670
Eric Laurent8fc147b2018-07-22 19:13:55 -07001671 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1672 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001673 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07001674 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001675 return;
1676 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001677 if (--outputDesc->mDirectOpenCount == 0) {
1678 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07001679 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001680 }
1681 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001682 // stopOutput() needs to be successfully called before releaseOutput()
1683 // otherwise there may be inaccurate stream reference counts.
1684 // This is checked in outputDesc->removeClient below.
1685 outputDesc->removeClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001686}
1687
Eric Laurentcaf7f482014-11-25 17:50:47 -08001688status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1689 audio_io_handle_t *input,
1690 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001691 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001692 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001693 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001694 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001695 input_type_t *inputType,
1696 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001697{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001698 ALOGV("getInputForAttr() source %d, sampling rate %d, format %#x, channel mask %#x,"
Eric Laurentcaf7f482014-11-25 17:50:47 -08001699 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001700 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001701
Eric Laurentad2e7b92017-09-14 20:06:42 -07001702 status_t status = NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -08001703 // handle legacy remote submix case where the address was not always specified
1704 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001705 audio_source_t halInputSource;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001706 audio_source_t inputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001707 AudioMix *policyMix = NULL;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001708 DeviceVector inputDevices;
Eric Laurent8fc147b2018-07-22 19:13:55 -07001709 sp<AudioInputDescriptor> inputDesc;
1710 sp<RecordClientDescriptor> clientDesc;
1711 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001712 bool isSoundTrigger;
1713 audio_devices_t device;
1714
1715 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1716 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1717 return INVALID_OPERATION;
1718 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001719
Eric Laurentfe231122017-11-17 17:48:06 -08001720 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1721 inputSource = AUDIO_SOURCE_MIC;
1722 }
1723
Paul McLean466dc8e2015-04-17 13:15:36 -06001724 // Explicit routing?
1725 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -07001726 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
jiabinc0c831a2018-01-29 17:55:15 -08001727 deviceDesc = mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001728 }
Paul McLean466dc8e2015-04-17 13:15:36 -06001729
Eric Laurentad2e7b92017-09-14 20:06:42 -07001730 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1731 // possible
1732 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1733 *input != AUDIO_IO_HANDLE_NONE) {
1734 ssize_t index = mInputs.indexOfKey(*input);
1735 if (index < 0) {
1736 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1737 status = BAD_VALUE;
1738 goto error;
1739 }
1740 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001741 RecordClientVector clients = inputDesc->getClientsForSession(session);
1742 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001743 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1744 status = BAD_VALUE;
1745 goto error;
1746 }
1747 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1748 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001749 // corresponds to a new client and is only permitted from the same UID.
1750 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07001751 if (clients.size() > 1) {
1752 for (const auto& client : clients) {
1753 // The client map is ordered by key values (portId) and portIds are allocated
1754 // incrementaly. So the first client in this list is the one opened by audio flinger
1755 // when the mmap stream is created and should be ignored as it does not correspond
1756 // to an actual client
1757 if (client == *clients.cbegin()) {
1758 continue;
1759 }
1760 if (uid != client->uid() && !client->isSilenced()) {
1761 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
1762 uid, client->portId(), client->uid());
1763 status = INVALID_OPERATION;
1764 goto error;
1765 }
Eric Laurent331679c2018-04-16 17:03:16 -07001766 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001767 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001768 *inputType = API_INPUT_LEGACY;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001769 device = inputDesc->mDevice;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001770
Eric Laurent8f42ea12018-08-08 09:08:25 -07001771 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001772 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001773 }
1774
1775 *input = AUDIO_IO_HANDLE_NONE;
1776 *inputType = API_INPUT_INVALID;
1777
Eric Laurentad2e7b92017-09-14 20:06:42 -07001778 halInputSource = inputSource;
1779
Eric Laurentc447ded2015-01-06 08:47:05 -08001780 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001781 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001782 status = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
1783 if (status != NO_ERROR) {
1784 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001785 }
1786 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001787 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1788 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001789 } else {
Eric Laurent97ac8712018-07-27 18:59:02 -07001790 if (deviceDesc != 0) {
1791 device = deviceDesc->type();
1792 } else {
1793 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
1794 }
Eric Laurent275e8e92014-11-30 15:14:47 -08001795 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001796 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001797 status = BAD_VALUE;
1798 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001799 }
Eric Laurentc722f302014-12-10 11:21:49 -08001800 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001801 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001802 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1803 // there is an external policy, but this input is attached to a mix of recorders,
1804 // meaning it receives audio injected into the framework, so the recorder doesn't
1805 // know about it and is therefore considered "legacy"
1806 *inputType = API_INPUT_LEGACY;
1807 } else {
1808 // recording a mix of players defined by an external policy, we're rerouting for
1809 // an external policy
1810 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1811 }
Eric Laurentc722f302014-12-10 11:21:49 -08001812 } else if (audio_is_remote_submix_device(device)) {
1813 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001814 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001815 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1816 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001817 } else {
1818 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001819 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001820
Eric Laurent599c7582015-12-07 18:05:55 -08001821 }
1822
Eric Laurent8f42ea12018-08-08 09:08:25 -07001823 *input = getInputForDevice(device, address, session, inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001824 config, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001825 policyMix);
1826 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001827 status = INVALID_OPERATION;
1828 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001829 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001830
Eric Laurent8f42ea12018-08-08 09:08:25 -07001831exit:
1832
Mikhail Naganov708e0382018-05-30 09:53:04 -07001833 inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -07001834 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
Eric Laurent8f42ea12018-08-08 09:08:25 -07001835 : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07001836
Eric Laurent8f42ea12018-08-08 09:08:25 -07001837 isSoundTrigger = inputSource == AUDIO_SOURCE_HOTWORD &&
1838 mSoundTriggerSessions.indexOfKey(session) > 0;
1839 *portId = AudioPort::getNextUniqueId();
1840
Eric Laurent8fc147b2018-07-22 19:13:55 -07001841 clientDesc = new RecordClientDescriptor(*portId, uid, session,
Eric Laurent8f42ea12018-08-08 09:08:25 -07001842 *attr, *config, requestedDeviceId,
1843 inputSource,flags, isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001844 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07001845 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001846
1847 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
1848 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001849
Eric Laurent599c7582015-12-07 18:05:55 -08001850 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001851
1852error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07001853 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001854}
1855
1856
1857audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1858 String8 address,
1859 audio_session_t session,
Eric Laurent599c7582015-12-07 18:05:55 -08001860 audio_source_t inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001861 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08001862 audio_input_flags_t flags,
1863 AudioMix *policyMix)
1864{
1865 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1866 audio_source_t halInputSource = inputSource;
1867 bool isSoundTrigger = false;
1868
1869 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1870 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1871 if (index >= 0) {
1872 input = mSoundTriggerSessions.valueFor(session);
1873 isSoundTrigger = true;
1874 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1875 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1876 } else {
1877 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001878 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001879 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08001880 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001881 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001882 }
1883
Andy Hungf129b032015-04-07 13:45:50 -07001884 // find a compatible input profile (not necessarily identical in parameters)
1885 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08001886 // sampling rate and flags may be updated by getInputProfile
1887 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
1888 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07001889 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08001890 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07001891 audio_input_flags_t profileFlags = flags;
1892 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07001893 profileFormat = config->format; // reset each time through loop, in case it is updated
Eric Laurent275e8e92014-11-30 15:14:47 -08001894 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001895 profileSamplingRate, profileFormat, profileChannelMask,
1896 profileFlags);
1897 if (profile != 0) {
1898 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001899 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1900 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001901 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1902 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1903 } else { // fail
Glenn Kastenfaa10a62017-05-25 15:52:05 -07001904 ALOGW("getInputForDevice() could not find profile for device 0x%X, "
Eric Laurentfe231122017-11-17 17:48:06 -08001905 "sampling rate %u, format %#x, channel mask 0x%X, flags %#x",
1906 device, config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001907 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001908 }
Eric Laurente552edb2014-03-10 17:42:56 -07001909 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001910 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08001911 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08001912 if (samplingRate == 0) {
1913 samplingRate = profileSamplingRate;
1914 }
Eric Laurente552edb2014-03-10 17:42:56 -07001915
Eric Laurent322b4d22015-04-03 15:57:54 -07001916 if (profile->getModuleHandle() == 0) {
1917 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001918 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001919 }
1920
Eric Laurent3974e3b2017-12-07 17:58:43 -08001921 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001922 for (size_t i = 0; i < mInputs.size(); ) {
1923 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
1924 if (desc->mProfile != profile) {
1925 continue;
1926 }
1927 // if sound trigger, reuse input if used by other sound trigger on same session
1928 // else
1929 // reuse input if active client app is not in IDLE state
1930 //
1931 RecordClientVector clients = desc->clientsList();
1932 bool doClose = false;
1933 for (const auto& client : clients) {
1934 if (isSoundTrigger != client->isSoundTrigger()) {
1935 continue;
1936 }
1937 if (client->isSoundTrigger()) {
1938 if (session == client->session()) {
1939 return desc->mIoHandle;
1940 }
1941 continue;
1942 }
1943 if (client->active() && client->appState() != APP_STATE_IDLE) {
1944 return desc->mIoHandle;
1945 }
1946 doClose = true;
1947 }
1948 if (doClose) {
1949 closeInput(desc->mIoHandle);
1950 } else {
1951 i++;
1952 }
1953 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08001954 }
1955
Eric Laurentfe231122017-11-17 17:48:06 -08001956 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001957
Eric Laurentfe231122017-11-17 17:48:06 -08001958 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
1959 lConfig.sample_rate = profileSamplingRate;
1960 lConfig.channel_mask = profileChannelMask;
1961 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07001962
Eric Laurent53b810e2017-12-10 17:25:10 -08001963 if (address == "") {
Mikhail Naganov708e0382018-05-30 09:53:04 -07001964 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -08001965 // the inputs vector must be of size >= 1, but we don't want to crash here
1966 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress : String8("");
1967 }
1968
Eric Laurentfe231122017-11-17 17:48:06 -08001969 status_t status = inputDesc->open(&lConfig, device, address,
1970 halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001971
1972 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001973 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08001974 (profileSamplingRate != lConfig.sample_rate) ||
1975 !audio_formats_match(profileFormat, lConfig.format) ||
1976 (profileChannelMask != lConfig.channel_mask)) {
1977 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001978 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08001979 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001980 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001981 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07001982 }
Eric Laurent599c7582015-12-07 18:05:55 -08001983 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001984 }
1985
Eric Laurentc722f302014-12-10 11:21:49 -08001986 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001987
Eric Laurent599c7582015-12-07 18:05:55 -08001988 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001989 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001990
Eric Laurent599c7582015-12-07 18:05:55 -08001991 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001992}
1993
Eric Laurent4eb58f12018-12-07 16:41:02 -08001994status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08001995{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001996 ALOGV("%s portId %d", __FUNCTION__, portId);
1997
1998 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
1999 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002000 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002001 return BAD_VALUE;
2002 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002003 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002004 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002005 if (client->active()) {
2006 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2007 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002008 }
2009
Eric Laurent8f42ea12018-08-08 09:08:25 -07002010 audio_session_t session = client->session();
2011
Eric Laurent4eb58f12018-12-07 16:41:02 -08002012 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002013
Eric Laurent4eb58f12018-12-07 16:41:02 -08002014 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002015
Eric Laurent4eb58f12018-12-07 16:41:02 -08002016 status_t status = inputDesc->start();
2017 if (status != NO_ERROR) {
2018 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002019 }
Eric Laurente552edb2014-03-10 17:42:56 -07002020
Eric Laurent4eb58f12018-12-07 16:41:02 -08002021 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002022 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002023 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002024
Eric Laurent8f42ea12018-08-08 09:08:25 -07002025 // indicate active capture to sound trigger service if starting capture from a mic on
2026 // primary HW module
2027 audio_devices_t device = getNewInputDevice(inputDesc);
2028 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002029
Eric Laurent8f42ea12018-08-08 09:08:25 -07002030 if (inputDesc->activeCount() == 1) {
2031 // if input maps to a dynamic policy with an activity listener, notify of state change
2032 if ((inputDesc->mPolicyMix != NULL)
2033 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2034 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2035 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002036 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002037
Eric Laurent8f42ea12018-08-08 09:08:25 -07002038 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2039 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2040 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
2041 SoundTrigger::setCaptureState(true);
2042 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002043
Eric Laurent8f42ea12018-08-08 09:08:25 -07002044 // automatically enable the remote submix output when input is started if not
2045 // used by a policy mix of type MIX_TYPE_RECORDERS
2046 // For remote submix (a virtual device), we open only one input per capture request.
2047 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2048 String8 address = String8("");
2049 if (inputDesc->mPolicyMix == NULL) {
2050 address = String8("0");
2051 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2052 address = inputDesc->mPolicyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002053 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002054 if (address != "") {
2055 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2056 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2057 address, "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08002058 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002059 }
Eric Laurente552edb2014-03-10 17:42:56 -07002060 }
2061
Eric Laurent8f42ea12018-08-08 09:08:25 -07002062 ALOGV("%s input %d source = %d exit", __FUNCTION__, input, client->source());
Eric Laurente552edb2014-03-10 17:42:56 -07002063
Eric Laurente552edb2014-03-10 17:42:56 -07002064 return NO_ERROR;
2065}
2066
Eric Laurent8fc147b2018-07-22 19:13:55 -07002067status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002068{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002069 ALOGV("%s portId %d", __FUNCTION__, portId);
2070
2071 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2072 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002073 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002074 return BAD_VALUE;
2075 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002076 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002077 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002078 if (!client->active()) {
2079 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002080 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002081 }
2082
Eric Laurent8f42ea12018-08-08 09:08:25 -07002083 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002084
Eric Laurent8f42ea12018-08-08 09:08:25 -07002085 inputDesc->stop();
2086 if (inputDesc->isActive()) {
2087 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2088 } else {
2089 // if input maps to a dynamic policy with an activity listener, notify of state change
2090 if ((inputDesc->mPolicyMix != NULL)
2091 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2092 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2093 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002094 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002095
2096 // automatically disable the remote submix output when input is stopped if not
2097 // used by a policy mix of type MIX_TYPE_RECORDERS
2098 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2099 String8 address = String8("");
2100 if (inputDesc->mPolicyMix == NULL) {
2101 address = String8("0");
2102 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2103 address = inputDesc->mPolicyMix->mDeviceAddress;
2104 }
2105 if (address != "") {
2106 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2107 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2108 address, "remote-submix");
2109 }
2110 }
2111
2112 audio_devices_t device = inputDesc->mDevice;
2113 resetInputDevice(input);
2114
2115 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2116 // primary HW module
2117 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2118 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2119 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
2120 SoundTrigger::setCaptureState(false);
2121 }
2122 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002123 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002124 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002125}
2126
Eric Laurent8fc147b2018-07-22 19:13:55 -07002127void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002128{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002129 ALOGV("%s portId %d", __FUNCTION__, portId);
2130
2131 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2132 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002133 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002134 return;
2135 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002136 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002137 audio_io_handle_t input = inputDesc->mIoHandle;
2138
Eric Laurent8f42ea12018-08-08 09:08:25 -07002139 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002140
Andy Hung39efb7a2018-09-26 15:39:28 -07002141 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002142
Andy Hung39efb7a2018-09-26 15:39:28 -07002143 if (inputDesc->getClientCount() > 0) {
2144 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002145 return;
2146 }
2147
Eric Laurent05b90f82014-08-27 15:32:29 -07002148 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002149 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002150 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002151}
2152
Eric Laurent8f42ea12018-08-08 09:08:25 -07002153void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002154{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002155 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002156
2157 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002158 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002159 }
2160}
2161
Eric Laurent8f42ea12018-08-08 09:08:25 -07002162void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2163{
2164 stopInput(portId);
2165 releaseInput(portId);
2166}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002167
Eric Laurentd4692962014-05-05 18:13:44 -07002168void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002169 bool patchRemoved = false;
2170
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002171 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002172 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002173 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002174 if (patch_index >= 0) {
2175 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002176 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002177 mAudioPatches.removeItemsAt(patch_index);
2178 patchRemoved = true;
2179 }
Eric Laurentfe231122017-11-17 17:48:06 -08002180 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002181 }
2182 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002183 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002184 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002185
2186 if (patchRemoved) {
2187 mpClientInterface->onAudioPatchListUpdate();
2188 }
Eric Laurentd4692962014-05-05 18:13:44 -07002189}
2190
Eric Laurente0720872014-03-11 09:30:41 -07002191void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002192 int indexMin,
2193 int indexMax)
2194{
2195 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002196 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002197
2198 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002199 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2200 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002201 continue;
2202 }
2203 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002204 }
Eric Laurente552edb2014-03-10 17:42:56 -07002205}
2206
Eric Laurente0720872014-03-11 09:30:41 -07002207status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002208 int index,
2209 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002210{
2211
Nadav Bar7c605f62017-12-25 00:01:52 +02002212 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2213 // app that has MODIFY_PHONE_STATE permission.
2214 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
2215 !(stream == AUDIO_STREAM_VOICE_CALL && index == 0)) ||
François Gaffied1ab2bd2015-12-02 18:20:06 +01002216 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002217 return BAD_VALUE;
2218 }
2219 if (!audio_is_output_device(device)) {
2220 return BAD_VALUE;
2221 }
2222
2223 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002224 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002225
Eric Laurent1fd372e2016-04-06 14:23:53 -07002226 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002227 stream, device, index);
2228
Eric Laurent28d09f02016-03-08 10:43:05 -08002229 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002230 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2231 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002232 continue;
2233 }
2234 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2235 }
Eric Laurente552edb2014-03-10 17:42:56 -07002236
Eric Laurent1fd372e2016-04-06 14:23:53 -07002237 // update volume on all outputs and streams matching the following:
2238 // - The requested stream (or a stream matching for volume control) is active on the output
2239 // - The device (or devices) selected by the strategy corresponding to this stream includes
2240 // the requested device
2241 // - For non default requested device, currently selected device on the output is either the
2242 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002243 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2244 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002245 status_t status = NO_ERROR;
2246 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002247 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
nobuaki tanaka985d15a2017-07-19 13:38:51 +09002248 audio_devices_t curDevice = desc->device();
Eric Laurent794fde22016-03-11 09:50:45 -08002249 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
Eric Laurent3839bc02018-07-10 18:33:34 -07002250 if (!(streamsMatchForvolume(stream, (audio_stream_type_t)curStream))) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002251 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002252 }
Eric Laurentdcd4ab12018-06-29 17:45:13 -07002253 if (!(desc->isStreamActive((audio_stream_type_t)curStream) || isInCall())) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002254 continue;
2255 }
Eric Laurent794fde22016-03-11 09:50:45 -08002256 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002257 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2258 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002259 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2260 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002261 continue;
2262 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002263 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002264 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002265 curStreamDevice |= device;
nobuaki tanaka985d15a2017-07-19 13:38:51 +09002266 applyVolume = (Volume::getDeviceForVolume(curDevice) & curStreamDevice) != 0;
Eric Laurente76f29c2016-09-14 17:17:53 -07002267 } else {
2268 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002269 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002270 }
Eric Laurent3839bc02018-07-10 18:33:34 -07002271 // rescale index before applying to curStream as ranges may be different for
2272 // stream and curStream
2273 int idx = rescaleVolumeIndex(index, stream, (audio_stream_type_t)curStream);
Eric Laurente76f29c2016-09-14 17:17:53 -07002274 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002275 //FIXME: workaround for truncated touch sounds
2276 // delayed volume change for system stream to be removed when the problem is
2277 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002278 status_t volStatus =
Eric Laurent3839bc02018-07-10 18:33:34 -07002279 checkAndSetVolume((audio_stream_type_t)curStream, idx, desc, curDevice,
Eric Laurentdc462862016-07-19 12:29:53 -07002280 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002281 if (volStatus != NO_ERROR) {
2282 status = volStatus;
2283 }
2284 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002285 }
Eric Laurente552edb2014-03-10 17:42:56 -07002286 }
2287 return status;
2288}
2289
Eric Laurente0720872014-03-11 09:30:41 -07002290status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002291 int *index,
2292 audio_devices_t device)
2293{
2294 if (index == NULL) {
2295 return BAD_VALUE;
2296 }
2297 if (!audio_is_output_device(device)) {
2298 return BAD_VALUE;
2299 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002300 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002301 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002302 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002303 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2304 }
François Gaffiedfd74092015-03-19 12:10:59 +01002305 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002306
François Gaffied1ab2bd2015-12-02 18:20:06 +01002307 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002308 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2309 return NO_ERROR;
2310}
2311
Eric Laurent36829f92017-04-07 19:04:42 -07002312audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002313{
2314 // select one output among several suitable for global effects.
2315 // The priority is as follows:
2316 // 1: An offloaded output. If the effect ends up not being offloadable,
2317 // AudioFlinger will invalidate the track and the offloaded output
2318 // will be closed causing the effect to be moved to a PCM output.
2319 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002320 // 3: The primary output
2321 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002322
Eric Laurent3b73df72014-03-11 09:06:29 -07002323 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002324 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent36829f92017-04-07 19:04:42 -07002325 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002326
Eric Laurent36829f92017-04-07 19:04:42 -07002327 if (outputs.size() == 0) {
2328 return AUDIO_IO_HANDLE_NONE;
2329 }
Eric Laurente552edb2014-03-10 17:42:56 -07002330
Eric Laurent36829f92017-04-07 19:04:42 -07002331 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2332 bool activeOnly = true;
2333
2334 while (output == AUDIO_IO_HANDLE_NONE) {
2335 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2336 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2337 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2338
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002339 for (audio_io_handle_t output : outputs) {
2340 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002341 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2342 continue;
2343 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002344 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2345 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002346 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002347 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002348 }
2349 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002350 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002351 }
2352 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002353 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002354 }
2355 }
2356 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2357 output = outputOffloaded;
2358 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2359 output = outputDeepBuffer;
2360 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2361 output = outputPrimary;
2362 } else {
2363 output = outputs[0];
2364 }
2365 activeOnly = false;
2366 }
2367
2368 if (output != mMusicEffectOutput) {
2369 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2370 mMusicEffectOutput = output;
2371 }
2372
2373 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002374 return output;
2375}
2376
Eric Laurent36829f92017-04-07 19:04:42 -07002377audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2378{
2379 return selectOutputForMusicEffects();
2380}
2381
Eric Laurente0720872014-03-11 09:30:41 -07002382status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002383 audio_io_handle_t io,
2384 uint32_t strategy,
2385 int session,
2386 int id)
2387{
2388 ssize_t index = mOutputs.indexOfKey(io);
2389 if (index < 0) {
2390 index = mInputs.indexOfKey(io);
2391 if (index < 0) {
2392 ALOGW("registerEffect() unknown io %d", io);
2393 return INVALID_OPERATION;
2394 }
2395 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002396 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002397}
2398
Eric Laurentc75307b2015-03-17 15:29:32 -07002399bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2400{
Eric Laurent28d09f02016-03-08 10:43:05 -08002401 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002402 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2403 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002404 continue;
2405 }
2406 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2407 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002408 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002409}
2410
2411bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2412{
2413 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2414}
2415
Eric Laurente0720872014-03-11 09:30:41 -07002416bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002417{
2418 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002419 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002420 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002421 return true;
2422 }
2423 }
2424 return false;
2425}
2426
Eric Laurent275e8e92014-11-30 15:14:47 -08002427// Register a list of custom mixes with their attributes and format.
2428// When a mix is registered, corresponding input and output profiles are
2429// added to the remote submix hw module. The profile contains only the
2430// parameters (sampling rate, format...) specified by the mix.
2431// The corresponding input remote submix device is also connected.
2432//
2433// When a remote submix device is connected, the address is checked to select the
2434// appropriate profile and the corresponding input or output stream is opened.
2435//
2436// When capture starts, getInputForAttr() will:
2437// - 1 look for a mix matching the address passed in attribtutes tags if any
2438// - 2 if none found, getDeviceForInputSource() will:
2439// - 2.1 look for a mix matching the attributes source
2440// - 2.2 if none found, default to device selection by policy rules
2441// At this time, the corresponding output remote submix device is also connected
2442// and active playback use cases can be transferred to this mix if needed when reconnecting
2443// after AudioTracks are invalidated
2444//
2445// When playback starts, getOutputForAttr() will:
2446// - 1 look for a mix matching the address passed in attribtutes tags if any
2447// - 2 if none found, look for a mix matching the attributes usage
2448// - 3 if none found, default to device and output selection by policy rules.
2449
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002450status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002451{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002452 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2453 status_t res = NO_ERROR;
2454
2455 sp<HwModule> rSubmixModule;
2456 // examine each mix's route type
2457 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002458 AudioMix mix = mixes[i];
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002459 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
Eric Laurent97ac8712018-07-27 18:59:02 -07002460 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002461 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002462 break;
2463 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002464 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002465 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002466 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002467 rSubmixModule = mHwModules.getModuleFromName(
2468 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2469 if (rSubmixModule == 0) {
2470 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2471 i);
2472 res = INVALID_OPERATION;
2473 break;
2474 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002475 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002476
Eric Laurent97ac8712018-07-27 18:59:02 -07002477 String8 address = mix.mDeviceAddress;
2478 if (mix.mMixType == MIX_TYPE_PLAYERS) {
2479 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2480 } else {
2481 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
2482 }
François Gaffie036e1e92015-03-19 10:16:24 +01002483
Eric Laurent97ac8712018-07-27 18:59:02 -07002484 if (mPolicyMixes.registerMix(address, mix, 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002485 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002486 res = INVALID_OPERATION;
2487 break;
2488 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002489 audio_config_t outputConfig = mix.mFormat;
2490 audio_config_t inputConfig = mix.mFormat;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002491 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2492 // stereo and let audio flinger do the channel conversion if needed.
2493 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2494 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2495 rSubmixModule->addOutputProfile(address, &outputConfig,
2496 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2497 rSubmixModule->addInputProfile(address, &inputConfig,
2498 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002499
Eric Laurent97ac8712018-07-27 18:59:02 -07002500 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002501 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2502 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2503 address.string(), "remote-submix");
2504 } else {
2505 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2506 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2507 address.string(), "remote-submix");
2508 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002509 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2510 String8 address = mix.mDeviceAddress;
2511 audio_devices_t device = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002512 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2513 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002514
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002515 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002516 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2517 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2518 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2519 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2520 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2521 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002522 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2523 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002524 if (mPolicyMixes.registerMix(address, mix, desc) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002525 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002526 } else {
2527 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002528 }
2529 break;
2530 }
2531 }
2532
2533 if (res != NO_ERROR) {
2534 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002535 i, device, address.string());
2536 res = INVALID_OPERATION;
2537 break;
2538 } else if (!foundOutput) {
2539 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2540 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002541 res = INVALID_OPERATION;
2542 break;
2543 }
Eric Laurentc722f302014-12-10 11:21:49 -08002544 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002545 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002546 if (res != NO_ERROR) {
2547 unregisterPolicyMixes(mixes);
2548 }
2549 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002550}
2551
2552status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2553{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002554 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002555 status_t res = NO_ERROR;
2556 sp<HwModule> rSubmixModule;
2557 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002558 for (const auto& mix : mixes) {
2559 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002560
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002561 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002562 rSubmixModule = mHwModules.getModuleFromName(
2563 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2564 if (rSubmixModule == 0) {
2565 res = INVALID_OPERATION;
2566 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002567 }
2568 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002569
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002570 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002571
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002572 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2573 res = INVALID_OPERATION;
2574 continue;
2575 }
2576
2577 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2578 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2579 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2580 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2581 address.string(), "remote-submix");
2582 }
2583 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2584 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2585 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2586 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2587 address.string(), "remote-submix");
2588 }
2589 rSubmixModule->removeOutputProfile(address);
2590 rSubmixModule->removeInputProfile(address);
2591
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002592 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2593 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002594 res = INVALID_OPERATION;
2595 continue;
2596 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002597 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002598 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002599 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002600}
2601
Mikhail Naganov100f0122018-11-29 11:22:16 -08002602void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
2603{
2604 size_t i = 0;
2605 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
2606 for (const auto& fmt : mManualSurroundFormats) {
2607 if (i++ != 0) dst->append(", ");
2608 std::string sfmt;
2609 FormatConverter::toString(fmt, sfmt);
2610 dst->append(sfmt.size() >= audioFormatPrefixLen ?
2611 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
2612 }
2613}
2614
Andy Hungc29d82b2018-10-05 12:23:17 -07002615void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07002616{
Andy Hungc29d82b2018-10-05 12:23:17 -07002617 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
2618 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07002619 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002620 std::string stateLiteral;
2621 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07002622 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002623 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
2624 "communications", "media", "record", "dock", "system",
2625 "HDMI system audio", "encoded surround output", "vibrate ringing" };
2626 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
2627 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08002628 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
2629 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
2630 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
2631 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
2632 dst->append(" (MANUAL: ");
2633 dumpManualSurroundFormats(dst);
2634 dst->append(")");
2635 }
2636 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002637 }
Andy Hungc29d82b2018-10-05 12:23:17 -07002638 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
2639 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
2640 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
2641 mAvailableOutputDevices.dump(dst, String8("Available output"));
2642 mAvailableInputDevices.dump(dst, String8("Available input"));
2643 mHwModulesAll.dump(dst);
2644 mOutputs.dump(dst);
2645 mInputs.dump(dst);
2646 mVolumeCurves->dump(dst);
2647 mEffects.dump(dst);
2648 mAudioPatches.dump(dst);
2649 mPolicyMixes.dump(dst);
2650 mAudioSources.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07002651}
2652
2653status_t AudioPolicyManager::dump(int fd)
2654{
2655 String8 result;
2656 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07002657 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002658 return NO_ERROR;
2659}
2660
2661// This function checks for the parameters which can be offloaded.
2662// This can be enhanced depending on the capability of the DSP and policy
2663// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002664bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002665{
2666 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002667 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002668 offloadInfo.sample_rate, offloadInfo.channel_mask,
2669 offloadInfo.format,
2670 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2671 offloadInfo.has_video);
2672
Andy Hung2ddee192015-12-18 17:34:44 -08002673 if (mMasterMono) {
2674 return false; // no offloading if mono is set.
2675 }
2676
Eric Laurente552edb2014-03-10 17:42:56 -07002677 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07002678 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
2679 ALOGV("offload disabled by audio.offload.disable");
2680 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002681 }
2682
2683 // Check if stream type is music, then only allow offload as of now.
2684 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2685 {
2686 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2687 return false;
2688 }
2689
2690 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002691 const bool allowOffloadWithVideo =
2692 property_get_bool("audio.offload.video", false /* default_value */);
2693 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002694 ALOGV("isOffloadSupported: has_video == true, returning false");
2695 return false;
2696 }
2697
2698 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07002699 const int min_duration_secs = property_get_int32(
2700 "audio.offload.min.duration.secs", -1 /* default_value */);
2701 if (min_duration_secs >= 0) {
2702 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
2703 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%d)",
2704 min_duration_secs);
Eric Laurente552edb2014-03-10 17:42:56 -07002705 return false;
2706 }
2707 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2708 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2709 return false;
2710 }
2711
2712 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2713 // creating an offloaded track and tearing it down immediately after start when audioflinger
2714 // detects there is an active non offloadable effect.
2715 // FIXME: We should check the audio session here but we do not have it in this context.
2716 // This may prevent offloading in rare situations where effects are left active by apps
2717 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002718 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002719 return false;
2720 }
2721
2722 // See if there is a profile to support this.
2723 // AUDIO_DEVICE_NONE
Michael Chana94fbb22018-04-24 14:31:19 +10002724 sp<IOProfile> profile = getProfileForOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002725 offloadInfo.sample_rate,
2726 offloadInfo.format,
2727 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10002728 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
2729 true /* directOnly */);
Eric Laurent1c333e22014-05-20 10:48:17 -07002730 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2731 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002732}
2733
Michael Chana94fbb22018-04-24 14:31:19 +10002734bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
2735 const audio_attributes_t& attributes) {
2736 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
2737 audio_attributes_flags_to_audio_output_flags(attributes.flags, output_flags);
2738 sp<IOProfile> profile = getProfileForOutput(AUDIO_DEVICE_NONE /*ignore device */,
2739 config.sample_rate,
2740 config.format,
2741 config.channel_mask,
2742 output_flags,
2743 true /* directOnly */);
2744 ALOGV("%s() profile %sfound with name: %s, "
2745 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
2746 __FUNCTION__, profile != 0 ? "" : "NOT ",
2747 (profile != 0 ? profile->getTagName().string() : "null"),
2748 config.sample_rate, config.format, config.channel_mask, output_flags);
2749 return (profile != 0);
2750}
2751
Eric Laurent6a94d692014-05-20 11:18:06 -07002752status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2753 audio_port_type_t type,
2754 unsigned int *num_ports,
2755 struct audio_port *ports,
2756 unsigned int *generation)
2757{
2758 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2759 generation == NULL) {
2760 return BAD_VALUE;
2761 }
2762 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2763 if (ports == NULL) {
2764 *num_ports = 0;
2765 }
2766
2767 size_t portsWritten = 0;
2768 size_t portsMax = *num_ports;
2769 *num_ports = 0;
2770 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002771 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2772 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002773 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002774 for (const auto& dev : mAvailableOutputDevices) {
2775 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002776 continue;
2777 }
2778 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002779 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002780 }
2781 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002782 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002783 }
2784 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002785 for (const auto& dev : mAvailableInputDevices) {
2786 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002787 continue;
2788 }
2789 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002790 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002791 }
2792 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002793 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002794 }
2795 }
2796 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2797 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2798 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2799 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2800 }
2801 *num_ports += mInputs.size();
2802 }
2803 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002804 size_t numOutputs = 0;
2805 for (size_t i = 0; i < mOutputs.size(); i++) {
2806 if (!mOutputs[i]->isDuplicated()) {
2807 numOutputs++;
2808 if (portsWritten < portsMax) {
2809 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2810 }
2811 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002812 }
Eric Laurent84c70242014-06-23 08:46:27 -07002813 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002814 }
2815 }
2816 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002817 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002818 return NO_ERROR;
2819}
2820
Eric Laurent99fcae42018-05-17 16:59:18 -07002821status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07002822{
Eric Laurent99fcae42018-05-17 16:59:18 -07002823 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
2824 return BAD_VALUE;
2825 }
2826 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
2827 if (dev != 0) {
2828 dev->toAudioPort(port);
2829 return NO_ERROR;
2830 }
2831 dev = mAvailableInputDevices.getDeviceFromId(port->id);
2832 if (dev != 0) {
2833 dev->toAudioPort(port);
2834 return NO_ERROR;
2835 }
2836 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
2837 if (out != 0) {
2838 out->toAudioPort(port);
2839 return NO_ERROR;
2840 }
2841 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
2842 if (in != 0) {
2843 in->toAudioPort(port);
2844 return NO_ERROR;
2845 }
2846 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002847}
2848
Eric Laurent6a94d692014-05-20 11:18:06 -07002849status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2850 audio_patch_handle_t *handle,
2851 uid_t uid)
2852{
2853 ALOGV("createAudioPatch()");
2854
2855 if (handle == NULL || patch == NULL) {
2856 return BAD_VALUE;
2857 }
2858 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2859
Mikhail Naganovac9858b2018-06-15 13:12:37 -07002860 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07002861 return BAD_VALUE;
2862 }
2863 // only one source per audio patch supported for now
2864 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002865 return INVALID_OPERATION;
2866 }
Eric Laurent874c42872014-08-08 15:13:39 -07002867
2868 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002869 return INVALID_OPERATION;
2870 }
Eric Laurent874c42872014-08-08 15:13:39 -07002871 for (size_t i = 0; i < patch->num_sinks; i++) {
2872 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2873 return INVALID_OPERATION;
2874 }
2875 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002876
2877 sp<AudioPatch> patchDesc;
2878 ssize_t index = mAudioPatches.indexOfKey(*handle);
2879
Eric Laurent6a94d692014-05-20 11:18:06 -07002880 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2881 patch->sources[0].role,
2882 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002883#if LOG_NDEBUG == 0
2884 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002885 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002886 patch->sinks[i].role,
2887 patch->sinks[i].type);
2888 }
2889#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002890
2891 if (index >= 0) {
2892 patchDesc = mAudioPatches.valueAt(index);
2893 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2894 mUidCached, patchDesc->mUid, uid);
2895 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2896 return INVALID_OPERATION;
2897 }
2898 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002899 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002900 }
2901
2902 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002903 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002904 if (outputDesc == NULL) {
2905 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2906 return BAD_VALUE;
2907 }
Eric Laurent84c70242014-06-23 08:46:27 -07002908 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2909 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002910 if (patchDesc != 0) {
2911 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2912 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2913 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2914 return BAD_VALUE;
2915 }
2916 }
Eric Laurent874c42872014-08-08 15:13:39 -07002917 DeviceVector devices;
2918 for (size_t i = 0; i < patch->num_sinks; i++) {
2919 // Only support mix to devices connection
2920 // TODO add support for mix to mix connection
2921 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2922 ALOGV("createAudioPatch() source mix but sink is not a device");
2923 return INVALID_OPERATION;
2924 }
2925 sp<DeviceDescriptor> devDesc =
2926 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2927 if (devDesc == 0) {
2928 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2929 return BAD_VALUE;
2930 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002931
François Gaffie53615e22015-03-19 09:24:12 +01002932 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002933 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002934 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002935 NULL, // updatedSamplingRate
2936 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002937 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002938 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002939 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002940 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002941 ALOGV("createAudioPatch() profile not supported for device %08x",
2942 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002943 return INVALID_OPERATION;
2944 }
2945 devices.add(devDesc);
2946 }
2947 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002948 return INVALID_OPERATION;
2949 }
Eric Laurent874c42872014-08-08 15:13:39 -07002950
Eric Laurent6a94d692014-05-20 11:18:06 -07002951 // TODO: reconfigure output format and channels here
2952 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002953 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002954 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002955 index = mAudioPatches.indexOfKey(*handle);
2956 if (index >= 0) {
2957 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2958 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2959 }
2960 patchDesc = mAudioPatches.valueAt(index);
2961 patchDesc->mUid = uid;
2962 ALOGV("createAudioPatch() success");
2963 } else {
2964 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2965 return INVALID_OPERATION;
2966 }
2967 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2968 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2969 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002970 // only one sink supported when connecting an input device to a mix
2971 if (patch->num_sinks > 1) {
2972 return INVALID_OPERATION;
2973 }
François Gaffie53615e22015-03-19 09:24:12 +01002974 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002975 if (inputDesc == NULL) {
2976 return BAD_VALUE;
2977 }
2978 if (patchDesc != 0) {
2979 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2980 return BAD_VALUE;
2981 }
2982 }
2983 sp<DeviceDescriptor> devDesc =
2984 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2985 if (devDesc == 0) {
2986 return BAD_VALUE;
2987 }
2988
François Gaffie53615e22015-03-19 09:24:12 +01002989 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002990 devDesc->mAddress,
2991 patch->sinks[0].sample_rate,
2992 NULL, /*updatedSampleRate*/
2993 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002994 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002995 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002996 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002997 // FIXME for the parameter type,
2998 // and the NONE
2999 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003000 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003001 return INVALID_OPERATION;
3002 }
3003 // TODO: reconfigure output format and channels here
3004 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01003005 devDesc->type(), inputDesc->mIoHandle);
3006 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003007 index = mAudioPatches.indexOfKey(*handle);
3008 if (index >= 0) {
3009 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3010 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
3011 }
3012 patchDesc = mAudioPatches.valueAt(index);
3013 patchDesc->mUid = uid;
3014 ALOGV("createAudioPatch() success");
3015 } else {
3016 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
3017 return INVALID_OPERATION;
3018 }
3019 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3020 // device to device connection
3021 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003022 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003023 return BAD_VALUE;
3024 }
3025 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003026 sp<DeviceDescriptor> srcDeviceDesc =
3027 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07003028 if (srcDeviceDesc == 0) {
3029 return BAD_VALUE;
3030 }
Eric Laurent874c42872014-08-08 15:13:39 -07003031
Eric Laurent6a94d692014-05-20 11:18:06 -07003032 //update source and sink with our own data as the data passed in the patch may
3033 // be incomplete.
3034 struct audio_patch newPatch = *patch;
3035 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003036
Eric Laurent874c42872014-08-08 15:13:39 -07003037 for (size_t i = 0; i < patch->num_sinks; i++) {
3038 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3039 ALOGV("createAudioPatch() source device but one sink is not a device");
3040 return INVALID_OPERATION;
3041 }
3042
3043 sp<DeviceDescriptor> sinkDeviceDesc =
3044 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3045 if (sinkDeviceDesc == 0) {
3046 return BAD_VALUE;
3047 }
3048 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
3049
Eric Laurent3bcf8592015-04-03 12:13:24 -07003050 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003051 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003052 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08003053 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003054 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003055 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003056 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003057 return INVALID_OPERATION;
3058 }
Eric Laurent874c42872014-08-08 15:13:39 -07003059 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01003060 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003061 // if the sink device is reachable via an opened output stream, request to go via
3062 // this output stream by adding a second source to the patch description
jiabin40573322018-11-08 12:08:02 -08003063 audio_io_handle_t output = selectOutput(outputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003064 if (output != AUDIO_IO_HANDLE_NONE) {
3065 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3066 if (outputDesc->isDuplicated()) {
3067 return INVALID_OPERATION;
3068 }
3069 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003070 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003071 newPatch.num_sources = 2;
3072 }
Eric Laurent83b88082014-06-20 18:31:16 -07003073 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003074 }
3075 // TODO: check from routing capabilities in config file and other conflicting patches
3076
Mikhail Naganovdc769682018-05-04 15:34:08 -07003077 status_t status = installPatch(__func__, index, handle, &newPatch, 0, uid, &patchDesc);
3078 if (status != NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003079 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3080 status);
3081 return INVALID_OPERATION;
3082 }
3083 } else {
3084 return BAD_VALUE;
3085 }
3086 } else {
3087 return BAD_VALUE;
3088 }
3089 return NO_ERROR;
3090}
3091
3092status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3093 uid_t uid)
3094{
3095 ALOGV("releaseAudioPatch() patch %d", handle);
3096
3097 ssize_t index = mAudioPatches.indexOfKey(handle);
3098
3099 if (index < 0) {
3100 return BAD_VALUE;
3101 }
3102 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3103 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3104 mUidCached, patchDesc->mUid, uid);
3105 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3106 return INVALID_OPERATION;
3107 }
3108
3109 struct audio_patch *patch = &patchDesc->mPatch;
3110 patchDesc->mUid = mUidCached;
3111 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003112 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003113 if (outputDesc == NULL) {
3114 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3115 return BAD_VALUE;
3116 }
3117
Eric Laurentc75307b2015-03-17 15:29:32 -07003118 setOutputDevice(outputDesc,
3119 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07003120 true,
3121 0,
3122 NULL);
3123 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3124 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003125 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003126 if (inputDesc == NULL) {
3127 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3128 return BAD_VALUE;
3129 }
3130 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003131 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003132 true,
3133 NULL);
3134 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003135 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3136 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3137 status, patchDesc->mAfPatchHandle);
3138 removeAudioPatch(patchDesc->mHandle);
3139 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003140 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003141 } else {
3142 return BAD_VALUE;
3143 }
3144 } else {
3145 return BAD_VALUE;
3146 }
3147 return NO_ERROR;
3148}
3149
3150status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3151 struct audio_patch *patches,
3152 unsigned int *generation)
3153{
François Gaffie53615e22015-03-19 09:24:12 +01003154 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003155 return BAD_VALUE;
3156 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003157 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003158 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003159}
3160
Eric Laurente1715a42014-05-20 11:30:42 -07003161status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003162{
Eric Laurente1715a42014-05-20 11:30:42 -07003163 ALOGV("setAudioPortConfig()");
3164
3165 if (config == NULL) {
3166 return BAD_VALUE;
3167 }
3168 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3169 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003170 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3171 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003172 }
3173
Eric Laurenta121f902014-06-03 13:32:54 -07003174 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003175 if (config->type == AUDIO_PORT_TYPE_MIX) {
3176 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003177 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003178 if (outputDesc == NULL) {
3179 return BAD_VALUE;
3180 }
Eric Laurent84c70242014-06-23 08:46:27 -07003181 ALOG_ASSERT(!outputDesc->isDuplicated(),
3182 "setAudioPortConfig() called on duplicated output %d",
3183 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003184 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003185 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003186 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003187 if (inputDesc == NULL) {
3188 return BAD_VALUE;
3189 }
Eric Laurenta121f902014-06-03 13:32:54 -07003190 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003191 } else {
3192 return BAD_VALUE;
3193 }
3194 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3195 sp<DeviceDescriptor> deviceDesc;
3196 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3197 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3198 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3199 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3200 } else {
3201 return BAD_VALUE;
3202 }
3203 if (deviceDesc == NULL) {
3204 return BAD_VALUE;
3205 }
Eric Laurenta121f902014-06-03 13:32:54 -07003206 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003207 } else {
3208 return BAD_VALUE;
3209 }
3210
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003211 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003212 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3213 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003214 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003215 audioPortConfig->toAudioPortConfig(&newConfig, config);
3216 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003217 }
Eric Laurenta121f902014-06-03 13:32:54 -07003218 if (status != NO_ERROR) {
3219 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003220 }
Eric Laurente1715a42014-05-20 11:30:42 -07003221
3222 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003223}
3224
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003225void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3226{
Eric Laurentd60560a2015-04-10 11:31:20 -07003227 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003228 clearAudioPatches(uid);
3229 clearSessionRoutes(uid);
3230}
3231
Eric Laurent6a94d692014-05-20 11:18:06 -07003232void AudioPolicyManager::clearAudioPatches(uid_t uid)
3233{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003234 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003235 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3236 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003237 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003238 }
3239 }
3240}
3241
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003242void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3243 audio_io_handle_t ouptutToSkip)
3244{
3245 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3246 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3247 for (size_t j = 0; j < mOutputs.size(); j++) {
3248 if (mOutputs.keyAt(j) == ouptutToSkip) {
3249 continue;
3250 }
3251 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3252 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3253 continue;
3254 }
3255 // If the default device for this strategy is on another output mix,
3256 // invalidate all tracks in this strategy to force re connection.
3257 // Otherwise select new device on the output mix.
3258 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003259 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003260 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3261 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3262 }
3263 }
3264 } else {
3265 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3266 setOutputDevice(outputDesc, newDevice, false);
3267 }
3268 }
3269}
3270
3271void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3272{
3273 // remove output routes associated with this uid
3274 SortedVector<routing_strategy> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07003275 for (size_t i = 0; i < mOutputs.size(); i++) {
3276 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003277 for (const auto& client : outputDesc->getClientIterable()) {
3278 if (client->hasPreferredDevice() && client->uid() == uid) {
3279 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3280 affectedStrategies.add(getStrategy(client->stream()));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003281 }
3282 }
3283 }
3284 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003285 for (const auto& strategy : affectedStrategies) {
3286 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003287 }
3288
3289 // remove input routes associated with this uid
3290 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07003291 for (size_t i = 0; i < mInputs.size(); i++) {
3292 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003293 for (const auto& client : inputDesc->getClientIterable()) {
3294 if (client->hasPreferredDevice() && client->uid() == uid) {
3295 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3296 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003297 }
3298 }
3299 }
3300 // reroute inputs if necessary
3301 SortedVector<audio_io_handle_t> inputsToClose;
3302 for (size_t i = 0; i < mInputs.size(); i++) {
3303 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08003304 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003305 inputsToClose.add(inputDesc->mIoHandle);
3306 }
3307 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003308 for (const auto& input : inputsToClose) {
3309 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003310 }
3311}
3312
Eric Laurentd60560a2015-04-10 11:31:20 -07003313void AudioPolicyManager::clearAudioSources(uid_t uid)
3314{
3315 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003316 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3317 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07003318 stopAudioSource(mAudioSources.keyAt(i));
3319 }
3320 }
3321}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003322
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003323status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3324 audio_io_handle_t *ioHandle,
3325 audio_devices_t *device)
3326{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003327 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3328 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003329 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003330
François Gaffiedf372692015-03-19 10:43:27 +01003331 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003332}
3333
Eric Laurentd60560a2015-04-10 11:31:20 -07003334status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003335 const audio_attributes_t *attributes,
3336 audio_port_handle_t *portId,
3337 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003338{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003339 ALOGV("%s", __FUNCTION__);
3340 *portId = AUDIO_PORT_HANDLE_NONE;
3341
3342 if (source == NULL || attributes == NULL || portId == NULL) {
3343 ALOGW("%s invalid argument: source %p attributes %p handle %p",
3344 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003345 return BAD_VALUE;
3346 }
3347
Eric Laurentd60560a2015-04-10 11:31:20 -07003348 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3349 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003350 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
3351 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003352 return INVALID_OPERATION;
3353 }
3354
3355 sp<DeviceDescriptor> srcDeviceDesc =
3356 mAvailableInputDevices.getDevice(source->ext.device.type,
3357 String8(source->ext.device.address));
3358 if (srcDeviceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003359 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003360 return BAD_VALUE;
3361 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003362
3363 *portId = AudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07003364
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003365 struct audio_patch dummyPatch = {};
Eric Laurentd60560a2015-04-10 11:31:20 -07003366 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003367
3368 sp<SourceClientDescriptor> sourceDesc =
3369 new SourceClientDescriptor(*portId, uid, *attributes, patchDesc, srcDeviceDesc,
Eric Laurent97ac8712018-07-27 18:59:02 -07003370 streamTypefromAttributesInt(attributes),
3371 getStrategyForAttr(attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07003372
3373 status_t status = connectAudioSource(sourceDesc);
3374 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003375 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003376 }
3377 return status;
3378}
3379
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003380status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003381{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003382 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003383
3384 // make sure we only have one patch per source.
3385 disconnectAudioSource(sourceDesc);
3386
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003387 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003388 routing_strategy strategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003389 audio_stream_type_t stream = sourceDesc->stream();
3390 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->srcDevice();
Eric Laurentd60560a2015-04-10 11:31:20 -07003391
3392 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3393 sp<DeviceDescriptor> sinkDeviceDesc =
3394 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3395
3396 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003397
3398 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3399 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003400 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003401 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3402 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3403 // create patch between src device and output device
3404 // create Hwoutput and add to mHwOutputs
3405 } else {
3406 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
jiabin40573322018-11-08 12:08:02 -08003407 audio_io_handle_t output = selectOutput(outputs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003408 if (output == AUDIO_IO_HANDLE_NONE) {
3409 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3410 return INVALID_OPERATION;
3411 }
3412 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3413 if (outputDesc->isDuplicated()) {
3414 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3415 return INVALID_OPERATION;
3416 }
Eric Laurent733ce942017-12-07 12:18:25 -08003417 status_t status = outputDesc->start();
3418 if (status != NO_ERROR) {
3419 return status;
3420 }
3421
Eric Laurentd60560a2015-04-10 11:31:20 -07003422 // create a special patch with no sink and two sources:
3423 // - the second source indicates to PatchPanel through which output mix this patch should
3424 // be connected as well as the stream type for volume control
3425 // - the sink is defined by whatever output device is currently selected for the output
3426 // though which this patch is routed.
Mikhail Naganovdc769682018-05-04 15:34:08 -07003427 PatchBuilder patchBuilder;
3428 patchBuilder.addSource(srcDeviceDesc).addSource(outputDesc, { .stream = stream });
3429 status = mpClientInterface->createAudioPatch(patchBuilder.patch(),
Eric Laurentd60560a2015-04-10 11:31:20 -07003430 &afPatchHandle,
3431 0);
3432 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3433 status, afPatchHandle);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003434 sourceDesc->patchDesc()->mPatch = *patchBuilder.patch();
Eric Laurentd60560a2015-04-10 11:31:20 -07003435 if (status != NO_ERROR) {
3436 ALOGW("%s patch panel could not connect device patch, error %d",
3437 __FUNCTION__, status);
3438 return INVALID_OPERATION;
3439 }
3440 uint32_t delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07003441 status = startSource(outputDesc, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003442
3443 if (status != NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003444 mpClientInterface->releaseAudioPatch(sourceDesc->patchDesc()->mAfPatchHandle, 0);
Eric Laurentd60560a2015-04-10 11:31:20 -07003445 return status;
3446 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003447 sourceDesc->setSwOutput(outputDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003448 if (delayMs != 0) {
3449 usleep(delayMs * 1000);
3450 }
3451 }
3452
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003453 sourceDesc->patchDesc()->mAfPatchHandle = afPatchHandle;
3454 addAudioPatch(sourceDesc->patchDesc()->mHandle, sourceDesc->patchDesc());
Eric Laurentd60560a2015-04-10 11:31:20 -07003455
3456 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003457}
3458
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003459status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07003460{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003461 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
3462 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003463 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003464 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003465 return BAD_VALUE;
3466 }
3467 status_t status = disconnectAudioSource(sourceDesc);
3468
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003469 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003470 return status;
3471}
3472
Andy Hung2ddee192015-12-18 17:34:44 -08003473status_t AudioPolicyManager::setMasterMono(bool mono)
3474{
3475 if (mMasterMono == mono) {
3476 return NO_ERROR;
3477 }
3478 mMasterMono = mono;
3479 // if enabling mono we close all offloaded devices, which will invalidate the
3480 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3481 // for recreating the new AudioTrack as non-offloaded PCM.
3482 //
3483 // If disabling mono, we leave all tracks as is: we don't know which clients
3484 // and tracks are able to be recreated as offloaded. The next "song" should
3485 // play back offloaded.
3486 if (mMasterMono) {
3487 Vector<audio_io_handle_t> offloaded;
3488 for (size_t i = 0; i < mOutputs.size(); ++i) {
3489 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3490 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3491 offloaded.push(desc->mIoHandle);
3492 }
3493 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003494 for (const auto& handle : offloaded) {
3495 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003496 }
3497 }
3498 // update master mono for all remaining outputs
3499 for (size_t i = 0; i < mOutputs.size(); ++i) {
3500 updateMono(mOutputs.keyAt(i));
3501 }
3502 return NO_ERROR;
3503}
3504
3505status_t AudioPolicyManager::getMasterMono(bool *mono)
3506{
3507 *mono = mMasterMono;
3508 return NO_ERROR;
3509}
3510
Eric Laurentac9cef52017-06-09 15:46:26 -07003511float AudioPolicyManager::getStreamVolumeDB(
3512 audio_stream_type_t stream, int index, audio_devices_t device)
3513{
3514 return computeVolume(stream, index, device);
3515}
3516
jiabin81772902018-04-02 17:52:27 -07003517status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3518 audio_format_t *surroundFormats,
3519 bool *surroundFormatsEnabled,
3520 bool reported)
3521{
3522 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3523 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3524 return BAD_VALUE;
3525 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003526 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p reported %d",
3527 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled, reported);
jiabin81772902018-04-02 17:52:27 -07003528
3529 size_t formatsWritten = 0;
3530 size_t formatsMax = *numSurroundFormats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08003531 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
jiabin81772902018-04-02 17:52:27 -07003532 if (reported) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003533 // Return formats from all device profiles that have already been resolved by
Mikhail Naganov2563f232018-09-27 14:48:01 -07003534 // checkOutputsForDevice().
Mikhail Naganov100f0122018-11-29 11:22:16 -08003535 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
3536 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
3537 FormatVector supportedFormats =
3538 device->getAudioPort()->getAudioProfiles().getSupportedFormats();
3539 for (size_t j = 0; j < supportedFormats.size(); j++) {
3540 if (mConfig.getSurroundFormats().count(supportedFormats[j]) != 0) {
3541 formats.insert(supportedFormats[j]);
3542 } else {
3543 for (const auto& pair : mConfig.getSurroundFormats()) {
3544 if (pair.second.count(supportedFormats[j]) != 0) {
3545 formats.insert(pair.first);
3546 break;
3547 }
3548 }
3549 }
3550 }
jiabin81772902018-04-02 17:52:27 -07003551 }
3552 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003553 for (const auto& pair : mConfig.getSurroundFormats()) {
3554 formats.insert(pair.first);
jiabin81772902018-04-02 17:52:27 -07003555 }
3556 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003557 *numSurroundFormats = formats.size();
3558 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3559 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov2563f232018-09-27 14:48:01 -07003560 for (const auto& format: formats) {
jiabin81772902018-04-02 17:52:27 -07003561 if (formatsWritten < formatsMax) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003562 surroundFormats[formatsWritten] = format;
Mikhail Naganov100f0122018-11-29 11:22:16 -08003563 bool formatEnabled = true;
3564 switch (forceUse) {
3565 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
3566 formatEnabled = mManualSurroundFormats.count(format) != 0;
3567 break;
3568 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
3569 formatEnabled = false;
3570 break;
3571 default: // AUTO or ALWAYS => true
3572 break;
jiabin81772902018-04-02 17:52:27 -07003573 }
3574 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3575 }
jiabin81772902018-04-02 17:52:27 -07003576 }
3577 return NO_ERROR;
3578}
3579
3580status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3581{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003582 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003583 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
3584 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003585 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07003586 return BAD_VALUE;
3587 }
3588
Mikhail Naganov100f0122018-11-29 11:22:16 -08003589 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
3590 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003591 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07003592 return INVALID_OPERATION;
3593 }
3594
Mikhail Naganov100f0122018-11-29 11:22:16 -08003595 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07003596 return NO_ERROR;
3597 }
3598
Mikhail Naganov100f0122018-11-29 11:22:16 -08003599 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07003600 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003601 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003602 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003603 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07003604 }
3605 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003606 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003607 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003608 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07003609 }
3610 }
3611
3612 sp<SwAudioOutputDescriptor> outputDesc;
3613 bool profileUpdated = false;
Mikhail Naganov708e0382018-05-30 09:53:04 -07003614 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003615 AUDIO_DEVICE_OUT_HDMI);
3616 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3617 // Simulate reconnection to update enabled surround sound formats.
3618 String8 address = hdmiOutputDevices[i]->mAddress;
3619 String8 name = hdmiOutputDevices[i]->getName();
3620 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3621 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3622 address.c_str(),
3623 name.c_str());
3624 if (status != NO_ERROR) {
3625 continue;
3626 }
3627 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3628 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3629 address.c_str(),
3630 name.c_str());
3631 profileUpdated |= (status == NO_ERROR);
3632 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003633 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
Mikhail Naganov708e0382018-05-30 09:53:04 -07003634 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003635 AUDIO_DEVICE_IN_HDMI);
3636 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3637 // Simulate reconnection to update enabled surround sound formats.
3638 String8 address = hdmiInputDevices[i]->mAddress;
3639 String8 name = hdmiInputDevices[i]->getName();
3640 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3641 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3642 address.c_str(),
3643 name.c_str());
3644 if (status != NO_ERROR) {
3645 continue;
3646 }
3647 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3648 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3649 address.c_str(),
3650 name.c_str());
3651 profileUpdated |= (status == NO_ERROR);
3652 }
3653
jiabin81772902018-04-02 17:52:27 -07003654 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003655 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08003656 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07003657 }
3658
3659 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3660}
3661
Eric Laurentf32108e2018-10-04 17:22:04 -07003662void AudioPolicyManager::setAppState(uid_t uid, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003663{
Eric Laurentf32108e2018-10-04 17:22:04 -07003664 Vector<sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
Eric Laurentf32108e2018-10-04 17:22:04 -07003665
Eric Laurent4eb58f12018-12-07 16:41:02 -08003666 ALOGV("%s(uid:%d, state:%d)", __func__, uid, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003667
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003668 for (size_t i = 0; i < activeInputs.size(); i++) {
3669 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
Eric Laurent8f42ea12018-08-08 09:08:25 -07003670 RecordClientVector clients = activeDesc->clientsList(true /*activeOnly*/);
3671 for (const auto& client : clients) {
3672 if (uid == client->uid()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003673 client->setAppState(state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003674 }
3675 }
3676 }
3677}
3678
jiabin6012f912018-11-02 17:06:30 -07003679bool AudioPolicyManager::isHapticPlaybackSupported()
3680{
3681 for (const auto& hwModule : mHwModules) {
3682 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
3683 for (const auto &outProfile : outputProfiles) {
3684 struct audio_port audioPort;
3685 outProfile->toAudioPort(&audioPort);
3686 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
3687 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
3688 return true;
3689 }
3690 }
3691 }
3692 }
3693 return false;
3694}
3695
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003696status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003697{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003698 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003699
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003700 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003701 if (patchDesc == 0) {
3702 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003703 sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003704 return BAD_VALUE;
3705 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003706 removeAudioPatch(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003707
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003708 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003709 if (swOutputDesc != 0) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003710 status_t status = stopSource(swOutputDesc, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08003711 if (status == NO_ERROR) {
3712 swOutputDesc->stop();
3713 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003714 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3715 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003716 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003717 if (hwOutputDesc != 0) {
3718 // release patch between src device and output device
3719 // close Hwoutput and remove from mHwOutputs
3720 } else {
3721 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3722 }
3723 }
3724 return NO_ERROR;
3725}
3726
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003727sp<SourceClientDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
Eric Laurentd60560a2015-04-10 11:31:20 -07003728 audio_io_handle_t output, routing_strategy strategy)
3729{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003730 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07003731 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003732 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3733 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003734 routing_strategy sourceStrategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003735 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003736 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3737 source = sourceDesc;
3738 break;
3739 }
3740 }
3741 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003742}
3743
Eric Laurente552edb2014-03-10 17:42:56 -07003744// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003745// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003746// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003747uint32_t AudioPolicyManager::nextAudioPortGeneration()
3748{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003749 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003750}
3751
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003752// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3753static const char *kConfigLocationList[] =
3754 {"/odm/etc", "/vendor/etc", "/system/etc"};
3755static const int kConfigLocationListSize =
3756 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3757
3758static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3759 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07003760 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003761 status_t ret;
3762
Petri Gyntherf497f292018-04-17 18:46:10 -07003763 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
3764 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
3765 // A2DP offload supported but disabled: try to use special XML file
3766 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
3767 }
3768 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3769
3770 for (const char* fileName : fileNames) {
3771 for (int i = 0; i < kConfigLocationListSize; i++) {
Petri Gyntherf497f292018-04-17 18:46:10 -07003772 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
3773 "%s/%s", kConfigLocationList[i], fileName);
Mikhail Naganova289aea2018-09-17 15:26:23 -07003774 ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile, &config);
Petri Gyntherf497f292018-04-17 18:46:10 -07003775 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003776 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07003777 return ret;
3778 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003779 }
3780 }
3781 return ret;
3782}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003783
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003784AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
3785 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07003786 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07003787 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003788 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07003789 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003790 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003791 mVolumeCurves(new VolumeCurvesCollection()),
3792 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08003793 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003794 mAudioPortGeneration(1),
3795 mBeaconMuteRefCount(0),
3796 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003797 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003798 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003799 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08003800 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07003801{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003802}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003803
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003804AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
3805 : AudioPolicyManager(clientInterface, false /*forTesting*/)
3806{
3807 loadConfig();
3808 initialize();
3809}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003810
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07003811// This check is to catch any legacy platform updating to Q without having
3812// switched to XML since its deprecation on O.
3813// TODO: after Q release, remove this check and flag as XML is now the only
3814// option and all legacy platform should have transitioned to XML.
3815#ifndef USE_XML_AUDIO_POLICY_CONF
3816#error Audio policy no longer supports legacy .conf configuration format
François Gaffied1ab2bd2015-12-02 18:20:06 +01003817#endif
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07003818
3819void AudioPolicyManager::loadConfig() {
3820 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003821 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003822 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01003823 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003824}
3825
3826status_t AudioPolicyManager::initialize() {
3827 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01003828
3829 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003830 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3831 if (!engineInstance) {
3832 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003833 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003834 }
3835 // Retrieve the Policy Manager Interface
3836 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3837 if (mEngine == NULL) {
3838 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003839 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003840 }
3841 mEngine->setObserver(this);
3842 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003843 if (status != NO_ERROR) {
3844 LOG_FATAL("Policy engine not initialized(err=%d)", status);
3845 return status;
3846 }
François Gaffie2110e042015-03-24 08:41:51 +01003847
Eric Laurent3a4311c2014-03-17 12:00:47 -07003848 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003849 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003850 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3851 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Mikhail Naganovd4120142017-12-06 15:49:22 -08003852 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003853 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08003854 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
3855 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003856 continue;
3857 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08003858 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07003859 // open all output streams needed to access attached devices
3860 // except for direct output streams that are only opened when they are actually
3861 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003862 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003863 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003864 if (!outProfile->canOpenNewIo()) {
3865 ALOGE("Invalid Output profile max open count %u for profile %s",
3866 outProfile->maxOpenCount, outProfile->getTagName().c_str());
3867 continue;
3868 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003869 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003870 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003871 continue;
3872 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003873 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003874 mTtsOutputAvailable = true;
3875 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003876
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003877 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003878 continue;
3879 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003880 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003881 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3882 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003883 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003884 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003885 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003886 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003887 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003888 if ((profileType & outputDeviceTypes) == 0) {
3889 continue;
3890 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003891 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3892 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003893 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov708e0382018-05-30 09:53:04 -07003894 const DeviceVector &devicesForType = supportedDevices.getDevicesFromTypeMask(
3895 profileType);
Eric Laurentc40d9692016-04-13 19:14:13 -07003896 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3897 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003898 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08003899 status_t status = outputDesc->open(nullptr, profileType, address,
3900 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07003901
3902 if (status != NO_ERROR) {
3903 ALOGW("Cannot open output stream for device %08x on hw module %s",
3904 outputDesc->mDevice,
Mikhail Naganovd4120142017-12-06 15:49:22 -08003905 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003906 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003907 for (const auto& dev : supportedDevices) {
3908 ssize_t index = mAvailableOutputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07003909 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003910 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003911 mAvailableOutputDevices[index]->attach(hwModule);
Eric Laurentd78f1532014-09-16 16:38:20 -07003912 }
3913 }
3914 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003915 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003916 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003917 }
3918 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003919 setOutputDevice(outputDesc,
Eric Laurentfe231122017-11-17 17:48:06 -08003920 profileType,
Eric Laurentc40d9692016-04-13 19:14:13 -07003921 true,
3922 0,
3923 NULL,
Eric Laurentfe231122017-11-17 17:48:06 -08003924 address);
Eric Laurentd78f1532014-09-16 16:38:20 -07003925 }
Eric Laurente552edb2014-03-10 17:42:56 -07003926 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003927 // open input streams needed to access attached devices to validate
3928 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003929 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003930 if (!inProfile->canOpenNewIo()) {
3931 ALOGE("Invalid Input profile max open count %u for profile %s",
3932 inProfile->maxOpenCount, inProfile->getTagName().c_str());
3933 continue;
3934 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003935 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003936 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003937 continue;
3938 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003939 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003940 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003941 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
3942
Eric Laurentd78f1532014-09-16 16:38:20 -07003943 if ((profileType & inputDeviceTypes) == 0) {
3944 continue;
3945 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08003946 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08003947 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07003948
Mikhail Naganov708e0382018-05-30 09:53:04 -07003949 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(profileType);
Eric Laurent53b810e2017-12-10 17:25:10 -08003950 // the inputs vector must be of size >= 1, but we don't want to crash here
3951 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3952 : String8("");
3953 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
3954 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
3955
Eric Laurentd78f1532014-09-16 16:38:20 -07003956 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08003957 status_t status = inputDesc->open(nullptr,
3958 profileType,
Eric Laurent53b810e2017-12-10 17:25:10 -08003959 address,
Eric Laurentfe231122017-11-17 17:48:06 -08003960 AUDIO_SOURCE_MIC,
3961 AUDIO_INPUT_FLAG_NONE,
3962 &input);
Eric Laurentd78f1532014-09-16 16:38:20 -07003963
3964 if (status == NO_ERROR) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003965 for (const auto& dev : inProfile->getSupportedDevices()) {
3966 ssize_t index = mAvailableInputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07003967 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07003968 if (index >= 0) {
3969 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
3970 if (!devDesc->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003971 devDesc->attach(hwModule);
Eric Laurent83efe1c2017-07-09 16:51:08 -07003972 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07003973 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003974 }
3975 }
Eric Laurentfe231122017-11-17 17:48:06 -08003976 inputDesc->close();
Eric Laurentd78f1532014-09-16 16:38:20 -07003977 } else {
3978 ALOGW("Cannot open input stream for device %08x on hw module %s",
Eric Laurentfe231122017-11-17 17:48:06 -08003979 profileType,
Mikhail Naganovd4120142017-12-06 15:49:22 -08003980 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003981 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003982 }
3983 }
3984 // make sure all attached devices have been allocated a unique ID
3985 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003986 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003987 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003988 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
3989 continue;
3990 }
François Gaffie2110e042015-03-24 08:41:51 +01003991 // The device is now validated and can be appended to the available devices of the engine
3992 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
3993 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003994 i++;
3995 }
3996 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003997 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01003998 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003999 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
4000 continue;
4001 }
François Gaffie2110e042015-03-24 08:41:51 +01004002 // The device is now validated and can be appended to the available devices of the engine
4003 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
4004 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004005 i++;
4006 }
4007 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004008 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01004009 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004010 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004011 }
jiabin9ff780e2018-03-19 18:19:52 -07004012 // If microphones address is empty, set it according to device type
4013 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
4014 if (mAvailableInputDevices[i]->mAddress.isEmpty()) {
4015 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
4016 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
4017 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
4018 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BACK_MICROPHONE_ADDRESS);
4019 }
4020 }
4021 }
Eric Laurente552edb2014-03-10 17:42:56 -07004022
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004023 if (mPrimaryOutput == 0) {
4024 ALOGE("Failed to open primary output");
4025 status = NO_INIT;
4026 }
Eric Laurente552edb2014-03-10 17:42:56 -07004027
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09004028 // Silence ALOGV statements
4029 property_set("log.tag." LOG_TAG, "D");
4030
Eric Laurente552edb2014-03-10 17:42:56 -07004031 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004032 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004033}
4034
Eric Laurente0720872014-03-11 09:30:41 -07004035AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004036{
Eric Laurente552edb2014-03-10 17:42:56 -07004037 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004038 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004039 }
4040 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004041 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004042 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004043 mAvailableOutputDevices.clear();
4044 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004045 mOutputs.clear();
4046 mInputs.clear();
4047 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004048 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004049 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004050}
4051
Eric Laurente0720872014-03-11 09:30:41 -07004052status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004053{
Eric Laurent87ffa392015-05-22 10:32:38 -07004054 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004055}
4056
Eric Laurente552edb2014-03-10 17:42:56 -07004057// ---
4058
Eric Laurent98e38192018-02-15 18:31:53 -08004059void AudioPolicyManager::addOutput(audio_io_handle_t output,
4060 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004061{
Eric Laurent1c333e22014-05-20 10:48:17 -07004062 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08004063 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004064 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004065 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004066 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004067}
4068
François Gaffie53615e22015-03-19 09:24:12 +01004069void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4070{
4071 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004072 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004073}
4074
Eric Laurent98e38192018-02-15 18:31:53 -08004075void AudioPolicyManager::addInput(audio_io_handle_t input,
4076 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004077{
Eric Laurent1c333e22014-05-20 10:48:17 -07004078 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004079 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004080}
Eric Laurente552edb2014-03-10 17:42:56 -07004081
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004082void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08004083 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004084 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004085 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08004086 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004087 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08004088 if (devDesc != 0) {
4089 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
4090 desc->mIoHandle, address.string());
4091 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004092 }
4093}
4094
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004095status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004096 audio_policy_dev_state_t state,
4097 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004098 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07004099{
François Gaffie53615e22015-03-19 09:24:12 +01004100 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07004101 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004102
4103 if (audio_device_is_digital(device)) {
4104 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004105 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004106 }
Eric Laurente552edb2014-03-10 17:42:56 -07004107
Eric Laurent3b73df72014-03-11 09:06:29 -07004108 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004109 // first list already open outputs that can be routed to this device
4110 for (size_t i = 0; i < mOutputs.size(); i++) {
4111 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07004112 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004113 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004114 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
4115 outputs.add(mOutputs.keyAt(i));
4116 } else {
4117 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08004118 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004119 }
Eric Laurente552edb2014-03-10 17:42:56 -07004120 }
4121 }
4122 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004123 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004124 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004125 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4126 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004127 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004128 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004129 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004130 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004131 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4132 j, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004133 }
Eric Laurente552edb2014-03-10 17:42:56 -07004134 }
4135 }
4136 }
4137
Eric Laurent7b279bb2015-12-14 10:18:23 -08004138 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004139
Eric Laurente552edb2014-03-10 17:42:56 -07004140 if (profiles.isEmpty() && outputs.isEmpty()) {
4141 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4142 return BAD_VALUE;
4143 }
4144
4145 // open outputs for matching profiles if needed. Direct outputs are also opened to
4146 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4147 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004148 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004149
4150 // nothing to do if one output is already opened for this profile
4151 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004152 for (j = 0; j < outputs.size(); j++) {
4153 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004154 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004155 // matching profile: save the sample rates, format and channel masks supported
4156 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07004157 if (audio_device_is_digital(device)) {
4158 devDesc->importAudioPort(profile);
4159 }
Eric Laurente552edb2014-03-10 17:42:56 -07004160 break;
4161 }
4162 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004163 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004164 continue;
4165 }
4166
Eric Laurent3974e3b2017-12-07 17:58:43 -08004167 if (!profile->canOpenNewIo()) {
4168 ALOGW("Max Output number %u already opened for this profile %s",
4169 profile->maxOpenCount, profile->getTagName().c_str());
4170 continue;
4171 }
4172
Eric Laurent83efe1c2017-07-09 16:51:08 -07004173 ALOGV("opening output for device %08x with params %s profile %p name %s",
4174 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004175 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004176 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004177 status_t status = desc->open(nullptr, device, address,
4178 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004179
Eric Laurentfe231122017-11-17 17:48:06 -08004180 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004181 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004182 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004183 char *param = audio_device_address_to_parameter(device, address);
4184 mpClientInterface->setParameters(output, String8(param));
4185 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004186 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08004187 updateAudioProfiles(devDesc, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004188 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004189 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004190 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004191 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004192 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004193 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004194 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004195 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4196 profile->pickAudioProfile(
4197 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004198 config.offload_info.sample_rate = config.sample_rate;
4199 config.offload_info.channel_mask = config.channel_mask;
4200 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004201
4202 status_t status = desc->open(&config, device, address, AUDIO_STREAM_DEFAULT,
4203 AUDIO_OUTPUT_FLAG_NONE, &output);
4204 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004205 output = AUDIO_IO_HANDLE_NONE;
4206 }
Eric Laurentd4692962014-05-05 18:13:44 -07004207 }
4208
Eric Laurentcf2c0212014-07-25 16:20:43 -07004209 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004210 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01004211 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004212 sp<AudioPolicyMix> policyMix;
4213 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004214 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
4215 address.string());
4216 }
François Gaffie036e1e92015-03-19 10:16:24 +01004217 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07004218 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01004219
Eric Laurent87ffa392015-05-22 10:32:38 -07004220 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4221 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004222 // no duplicated output for direct outputs and
4223 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004224 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004225
Eric Laurentd4692962014-05-05 18:13:44 -07004226 //TODO: configure audio effect output stage here
4227
4228 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004229 sp<SwAudioOutputDescriptor> dupOutputDesc =
4230 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4231 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4232 &duplicatedOutput);
4233 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004234 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004235 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004236 } else {
4237 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004238 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004239 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004240 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004241 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004242 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004243 }
Eric Laurente552edb2014-03-10 17:42:56 -07004244 }
4245 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004246 } else {
4247 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004248 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004249 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004250 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004251 profiles.removeAt(profile_index);
4252 profile_index--;
4253 } else {
4254 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004255 // Load digital format info only for digital devices
4256 if (audio_device_is_digital(device)) {
4257 devDesc->importAudioPort(profile);
4258 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004259
François Gaffie53615e22015-03-19 09:24:12 +01004260 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004261 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4262 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004263 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004264 NULL/*patch handle*/, address.string());
4265 }
Eric Laurente552edb2014-03-10 17:42:56 -07004266 ALOGV("checkOutputsForDevice(): adding output %d", output);
4267 }
4268 }
4269
4270 if (profiles.isEmpty()) {
4271 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4272 return BAD_VALUE;
4273 }
Eric Laurentd4692962014-05-05 18:13:44 -07004274 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004275 // check if one opened output is not needed any more after disconnecting one device
4276 for (size_t i = 0; i < mOutputs.size(); i++) {
4277 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004278 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004279 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004280 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004281 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004282 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004283 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004284 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4285 mOutputs.keyAt(i));
4286 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004287 }
Eric Laurente552edb2014-03-10 17:42:56 -07004288 }
4289 }
Eric Laurentd4692962014-05-05 18:13:44 -07004290 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004291 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004292 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4293 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004294 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004295 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004296 "clearing direct output profile %zu on module %s",
4297 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004298 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004299 }
4300 }
4301 }
4302 }
4303 return NO_ERROR;
4304}
4305
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004306status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004307 audio_policy_dev_state_t state,
4308 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004309 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004310{
Paul McLean9080a4c2015-06-18 08:24:02 -07004311 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004312 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004313
4314 if (audio_device_is_digital(device)) {
4315 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004316 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004317 }
4318
Eric Laurentd4692962014-05-05 18:13:44 -07004319 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4320 // first list already open inputs that can be routed to this device
4321 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4322 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004323 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004324 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4325 inputs.add(mInputs.keyAt(input_index));
4326 }
4327 }
4328
4329 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004330 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004331 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004332 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004333 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004334 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004335 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004336
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004337 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004338 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004339 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004340 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004341 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4342 profile_index, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004343 }
Eric Laurentd4692962014-05-05 18:13:44 -07004344 }
4345 }
4346 }
4347
4348 if (profiles.isEmpty() && inputs.isEmpty()) {
4349 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4350 return BAD_VALUE;
4351 }
4352
4353 // open inputs for matching profiles if needed. Direct inputs are also opened to
4354 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4355 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4356
Eric Laurent1c333e22014-05-20 10:48:17 -07004357 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004358
Eric Laurentd4692962014-05-05 18:13:44 -07004359 // nothing to do if one input is already opened for this profile
4360 size_t input_index;
4361 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4362 desc = mInputs.valueAt(input_index);
4363 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004364 if (audio_device_is_digital(device)) {
4365 devDesc->importAudioPort(profile);
4366 }
Eric Laurentd4692962014-05-05 18:13:44 -07004367 break;
4368 }
4369 }
4370 if (input_index != mInputs.size()) {
4371 continue;
4372 }
4373
Eric Laurent3974e3b2017-12-07 17:58:43 -08004374 if (!profile->canOpenNewIo()) {
4375 ALOGW("Max Input number %u already opened for this profile %s",
4376 profile->maxOpenCount, profile->getTagName().c_str());
4377 continue;
4378 }
4379
Eric Laurentfe231122017-11-17 17:48:06 -08004380 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004381 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004382 status_t status = desc->open(nullptr,
4383 device,
4384 address,
4385 AUDIO_SOURCE_MIC,
4386 AUDIO_INPUT_FLAG_NONE,
4387 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004388
Eric Laurentcf2c0212014-07-25 16:20:43 -07004389 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004390 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004391 char *param = audio_device_address_to_parameter(device, address);
4392 mpClientInterface->setParameters(input, String8(param));
4393 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004394 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08004395 updateAudioProfiles(devDesc, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004396 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004397 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004398 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004399 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004400 }
4401
4402 if (input != 0) {
4403 addInput(input, desc);
4404 }
4405 } // endif input != 0
4406
Eric Laurentcf2c0212014-07-25 16:20:43 -07004407 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004408 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004409 profiles.removeAt(profile_index);
4410 profile_index--;
4411 } else {
4412 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004413 if (audio_device_is_digital(device)) {
4414 devDesc->importAudioPort(profile);
4415 }
Eric Laurentd4692962014-05-05 18:13:44 -07004416 ALOGV("checkInputsForDevice(): adding input %d", input);
4417 }
4418 } // end scan profiles
4419
4420 if (profiles.isEmpty()) {
4421 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4422 return BAD_VALUE;
4423 }
4424 } else {
4425 // Disconnect
4426 // check if one opened input is not needed any more after disconnecting one device
4427 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4428 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004429 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004430 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4431 mInputs.keyAt(input_index));
4432 inputs.add(mInputs.keyAt(input_index));
4433 }
4434 }
4435 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004436 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004437 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004438 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004439 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004440 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004441 if (profile->supportDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004442 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4443 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004444 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004445 }
4446 }
4447 }
4448 } // end disconnect
4449
4450 return NO_ERROR;
4451}
4452
4453
Eric Laurente0720872014-03-11 09:30:41 -07004454void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004455{
4456 ALOGV("closeOutput(%d)", output);
4457
Eric Laurentc75307b2015-03-17 15:29:32 -07004458 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004459 if (outputDesc == NULL) {
4460 ALOGW("closeOutput() unknown output %d", output);
4461 return;
4462 }
François Gaffie036e1e92015-03-19 10:16:24 +01004463 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004464
Eric Laurente552edb2014-03-10 17:42:56 -07004465 // look for duplicated outputs connected to the output being removed.
4466 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004467 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004468 if (dupOutputDesc->isDuplicated() &&
4469 (dupOutputDesc->mOutput1 == outputDesc ||
4470 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004471 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004472 if (dupOutputDesc->mOutput1 == outputDesc) {
4473 outputDesc2 = dupOutputDesc->mOutput2;
4474 } else {
4475 outputDesc2 = dupOutputDesc->mOutput1;
4476 }
4477 // As all active tracks on duplicated output will be deleted,
4478 // and as they were also referenced on the other output, the reference
4479 // count for their stream type must be adjusted accordingly on
4480 // the other output.
Andy Hungaf036da2018-09-21 10:46:21 -07004481 const bool wasActive = outputDesc2->isActive();
4482 for (const auto &clientPair : dupOutputDesc->getActiveClients()) {
4483 outputDesc2->changeStreamActiveCount(clientPair.first, -clientPair.second);
Eric Laurente552edb2014-03-10 17:42:56 -07004484 }
Eric Laurent733ce942017-12-07 12:18:25 -08004485 // stop() will be a no op if the output is still active but is needed in case all
4486 // active streams refcounts where cleared above
4487 if (wasActive) {
4488 outputDesc2->stop();
4489 }
Eric Laurente552edb2014-03-10 17:42:56 -07004490 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4491 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4492
4493 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004494 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004495 }
4496 }
4497
Eric Laurent05b90f82014-08-27 15:32:29 -07004498 nextAudioPortGeneration();
4499
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004500 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004501 if (index >= 0) {
4502 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004503 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004504 mAudioPatches.removeItemsAt(index);
4505 mpClientInterface->onAudioPatchListUpdate();
4506 }
4507
Eric Laurentfe231122017-11-17 17:48:06 -08004508 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004509
François Gaffie53615e22015-03-19 09:24:12 +01004510 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004511 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10004512
4513 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
4514 // no direct outputs are open.
Mikhail Naganov100f0122018-11-29 11:22:16 -08004515 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Dean Wheatley3023b382018-08-09 07:42:40 +10004516 bool directOutputOpen = false;
4517 for (size_t i = 0; i < mOutputs.size(); i++) {
4518 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
4519 directOutputOpen = true;
4520 break;
4521 }
4522 }
4523 if (!directOutputOpen) {
4524 ALOGV("no direct outputs open, reset MSD patch");
4525 setMsdPatch();
4526 }
4527 }
Eric Laurent05b90f82014-08-27 15:32:29 -07004528}
4529
4530void AudioPolicyManager::closeInput(audio_io_handle_t input)
4531{
4532 ALOGV("closeInput(%d)", input);
4533
4534 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4535 if (inputDesc == NULL) {
4536 ALOGW("closeInput() unknown input %d", input);
4537 return;
4538 }
4539
Eric Laurent6a94d692014-05-20 11:18:06 -07004540 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004541
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004542 audio_devices_t device = inputDesc->mDevice;
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004543 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004544 if (index >= 0) {
4545 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004546 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004547 mAudioPatches.removeItemsAt(index);
4548 mpClientInterface->onAudioPatchListUpdate();
4549 }
4550
Eric Laurentfe231122017-11-17 17:48:06 -08004551 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004552 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004553
4554 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
4555 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
4556 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
4557 SoundTrigger::setCaptureState(false);
4558 }
Eric Laurente552edb2014-03-10 17:42:56 -07004559}
4560
Eric Laurentc75307b2015-03-17 15:29:32 -07004561SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4562 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004563 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004564{
4565 SortedVector<audio_io_handle_t> outputs;
4566
4567 ALOGVV("getOutputsForDevice() device %04x", device);
4568 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004569 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004570 i, openOutputs.valueAt(i)->isDuplicated(),
4571 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004572 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4573 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4574 outputs.add(openOutputs.keyAt(i));
4575 }
4576 }
4577 return outputs;
4578}
4579
Mikhail Naganov37977152018-07-11 15:54:44 -07004580void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
4581{
4582 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
4583 // output is suspended before any tracks are moved to it
4584 checkA2dpSuspend();
4585 checkOutputForAllStrategies();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004586 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07004587 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00004588 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004589 setMsdPatch();
4590 }
Mikhail Naganov37977152018-07-11 15:54:44 -07004591}
4592
Eric Laurente0720872014-03-11 09:30:41 -07004593void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004594{
4595 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4596 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4597 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4598 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4599
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004600 // also take into account external policy-related changes: add all outputs which are
4601 // associated with policies in the "before" and "after" output vectors
4602 ALOGVV("checkOutputForStrategy(): policy related outputs");
4603 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004604 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004605 if (desc != 0 && desc->mPolicyMix != NULL) {
4606 srcOutputs.add(desc->mIoHandle);
4607 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4608 }
4609 }
4610 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004611 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004612 if (desc != 0 && desc->mPolicyMix != NULL) {
4613 dstOutputs.add(desc->mIoHandle);
4614 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4615 }
4616 }
4617
Mikhail Naganov9de8bd12018-07-23 16:41:31 -07004618 if (srcOutputs != dstOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004619 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4620 // audio from invalidated tracks will be rendered when unmuting
4621 uint32_t maxLatency = 0;
4622 for (audio_io_handle_t srcOut : srcOutputs) {
4623 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4624 if (desc != 0 && maxLatency < desc->latency()) {
4625 maxLatency = desc->latency();
4626 }
4627 }
Eric Laurente552edb2014-03-10 17:42:56 -07004628 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4629 strategy, srcOutputs[0], dstOutputs[0]);
4630 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004631 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004632 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4633 if (desc != 0 && isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004634 setStrategyMute(strategy, true, desc);
Eric Laurentac3a6902018-05-11 16:39:10 -07004635 setStrategyMute(strategy, false, desc, maxLatency * LATENCY_MUTE_FACTOR, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004636 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004637 sp<SourceClientDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004638 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004639 if (source != 0){
4640 connectAudioSource(source);
4641 }
Eric Laurente552edb2014-03-10 17:42:56 -07004642 }
4643
4644 // Move effects associated to this strategy from previous output to new output
4645 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004646 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004647 }
4648 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004649 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004650 if (getStrategy((audio_stream_type_t)i) == strategy) {
4651 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004652 }
4653 }
4654 }
4655}
4656
Eric Laurente0720872014-03-11 09:30:41 -07004657void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004658{
François Gaffie2110e042015-03-24 08:41:51 +01004659 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004660 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004661 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004662 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004663 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004664 checkOutputForStrategy(STRATEGY_SONIFICATION);
4665 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004666 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004667 checkOutputForStrategy(STRATEGY_MEDIA);
4668 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004669 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004670}
4671
Eric Laurente0720872014-03-11 09:30:41 -07004672void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004673{
François Gaffie53615e22015-03-19 09:24:12 +01004674 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004675 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004676 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004677 return;
4678 }
4679
Eric Laurent3a4311c2014-03-17 12:00:47 -07004680 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004681 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4682 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4683 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004684
4685 // if suspended, restore A2DP output if:
4686 // ((SCO device is NOT connected) ||
4687 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4688 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004689 //
Eric Laurentf732e072016-08-03 19:30:28 -07004690 // if not suspended, suspend A2DP output if:
4691 // (SCO device is connected) &&
4692 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4693 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004694 //
4695 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004696 if (!isScoConnected ||
4697 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4698 AUDIO_POLICY_FORCE_BT_SCO) &&
4699 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4700 AUDIO_POLICY_FORCE_BT_SCO) &&
4701 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004702 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004703
4704 mpClientInterface->restoreOutput(a2dpOutput);
4705 mA2dpSuspended = false;
4706 }
4707 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004708 if (isScoConnected &&
4709 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4710 AUDIO_POLICY_FORCE_BT_SCO) ||
4711 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4712 AUDIO_POLICY_FORCE_BT_SCO) ||
4713 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004714 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004715
4716 mpClientInterface->suspendOutput(a2dpOutput);
4717 mA2dpSuspended = true;
4718 }
4719 }
4720}
4721
Eric Laurent97ac8712018-07-27 18:59:02 -07004722template <class IoDescriptor, class Filter>
4723sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4724 IoDescriptor& desc, Filter filter, bool& active, const DeviceVector& devices)
4725{
4726 auto activeClients = desc->clientsList(true /*activeOnly*/);
4727 auto activeClientsWithRoute =
4728 desc->clientsList(true /*activeOnly*/, filter, true /*preferredDevice*/);
4729 active = activeClients.size() > 0;
4730 if (active && activeClients.size() == activeClientsWithRoute.size()) {
4731 return devices.getDeviceFromId(activeClientsWithRoute[0]->preferredDeviceId());
4732 }
4733 return nullptr;
4734}
4735
4736template <class IoCollection, class Filter>
4737sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4738 IoCollection& ioCollection, Filter filter, const DeviceVector& devices)
4739{
4740 sp<DeviceDescriptor> device;
4741 for (size_t i = 0; i < ioCollection.size(); i++) {
4742 auto desc = ioCollection.valueAt(i);
4743 bool active;
4744 sp<DeviceDescriptor> curDevice = findPreferredDevice(desc, filter, active, devices);
4745 if (active && curDevice == nullptr) {
4746 return nullptr;
4747 } else if (curDevice != nullptr) {
4748 device = curDevice;
4749 }
4750 }
4751 return device;
4752}
4753
Eric Laurentc75307b2015-03-17 15:29:32 -07004754audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4755 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004756{
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004757 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004758 if (index >= 0) {
4759 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4760 if (patchDesc->mUid != mUidCached) {
4761 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004762 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004763 return outputDesc->device();
4764 }
4765 }
4766
Eric Laurent97ac8712018-07-27 18:59:02 -07004767 // Honor explicit routing requests only if no client using default routing is active on this
4768 // input: a specific app can not force routing for other apps by setting a preferred device.
4769 bool active; // unused
4770 sp<DeviceDescriptor> deviceDesc =
4771 findPreferredDevice(outputDesc, STRATEGY_NONE, active, mAvailableOutputDevices);
4772 if (deviceDesc != nullptr) {
4773 return deviceDesc->type();
Eric Laurentf3a5a602018-05-22 18:42:55 -07004774 }
4775
Eric Laurente552edb2014-03-10 17:42:56 -07004776 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004777 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004778 // use device for strategy enforced audible
4779 // 2: we are in call or the strategy phone is active on the output:
4780 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004781 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004782 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004783 // 4: the strategy for enforced audible is active but not enforced on the output:
4784 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004785 // 5: the strategy accessibility is active on the output:
4786 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004787 // 6: the strategy "respectful" sonification is active on the output:
4788 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004789 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004790 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004791 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004792 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004793 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004794 // use device for strategy t-t-s
Eric Laurent484e9272018-06-07 17:29:23 -07004795
4796 // FIXME: extend use of isStrategyActiveOnSameModule() to all strategies
4797 // with a refined rule considering mutually exclusive devices (using same backend)
4798 // as opposed to all streams on the same audio HAL module.
Eric Laurent97ac8712018-07-27 18:59:02 -07004799 audio_devices_t device = AUDIO_DEVICE_NONE;
François Gaffiead3183e2015-03-18 16:55:35 +01004800 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004801 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004802 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4803 } else if (isInCall() ||
Eric Laurent484e9272018-06-07 17:29:23 -07004804 isStrategyActiveOnSameModule(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004805 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
Yung Ti Su3e7eb5e2018-06-13 11:48:42 +08004806 } else if (isStrategyActiveOnSameModule(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004807 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004808 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
4809 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004810 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4811 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004812 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004813 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004814 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004815 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004816 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004817 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004818 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004819 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004820 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004821 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004822 }
4823
Eric Laurent1c333e22014-05-20 10:48:17 -07004824 ALOGV("getNewOutputDevice() selected device %x", device);
4825 return device;
4826}
4827
Eric Laurentfb66dd92016-01-28 18:32:03 -08004828audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004829{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004830 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004831
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004832 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004833 if (index >= 0) {
4834 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4835 if (patchDesc->mUid != mUidCached) {
4836 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004837 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004838 return inputDesc->mDevice;
4839 }
4840 }
4841
Eric Laurent97ac8712018-07-27 18:59:02 -07004842 // Honor explicit routing requests only if no client using default routing is active on this
4843 // input: a specific app can not force routing for other apps by setting a preferred device.
4844 bool active;
4845 sp<DeviceDescriptor> deviceDesc =
4846 findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
4847 if (deviceDesc != nullptr) {
4848 return deviceDesc->type();
4849 }
4850
Eric Laurentdc95a252018-04-12 12:46:56 -07004851 // If we are not in call and no client is active on this input, this methods returns
4852 // AUDIO_DEVICE_NONE, causing the patch on the input stream to be released.
Eric Laurent4eb58f12018-12-07 16:41:02 -08004853 audio_source_t source = inputDesc->source();
Eric Laurentdc95a252018-04-12 12:46:56 -07004854 if (source == AUDIO_SOURCE_DEFAULT && isInCall()) {
4855 source = AUDIO_SOURCE_VOICE_COMMUNICATION;
4856 }
4857 if (source != AUDIO_SOURCE_DEFAULT) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08004858 device = getDeviceAndMixForInputSource(source);
4859 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004860
Eric Laurente552edb2014-03-10 17:42:56 -07004861 return device;
4862}
4863
Eric Laurent794fde22016-03-11 09:50:45 -08004864bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4865 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004866 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004867}
4868
Eric Laurente0720872014-03-11 09:30:41 -07004869uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004870 return (uint32_t)getStrategy(stream);
4871}
4872
Eric Laurente0720872014-03-11 09:30:41 -07004873audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004874 // By checking the range of stream before calling getStrategy, we avoid
4875 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4876 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004877 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004878 return AUDIO_DEVICE_NONE;
4879 }
Eric Laurentb0688d62018-08-14 15:49:18 -07004880 audio_devices_t activeDevices = AUDIO_DEVICE_NONE;
Eric Laurent28d09f02016-03-08 10:43:05 -08004881 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004882 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4883 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004884 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004885 }
Eric Laurent794fde22016-03-11 09:50:45 -08004886 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004887 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004888 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Eric Laurentb0688d62018-08-14 15:49:18 -07004889 devices |= curDevices;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004890 for (audio_io_handle_t output : getOutputsForDevice(curDevices, mOutputs)) {
4891 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08004892 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurentb0688d62018-08-14 15:49:18 -07004893 activeDevices |= outputDesc->device();
Eric Laurent28d09f02016-03-08 10:43:05 -08004894 }
4895 }
Eric Laurente552edb2014-03-10 17:42:56 -07004896 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004897
Eric Laurentb0688d62018-08-14 15:49:18 -07004898 // Favor devices selected on active streams if any to report correct device in case of
4899 // explicit device selection
4900 if (activeDevices != AUDIO_DEVICE_NONE) {
4901 devices = activeDevices;
4902 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004903 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4904 and doesn't really need to.*/
4905 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4906 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4907 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4908 }
Eric Laurente552edb2014-03-10 17:42:56 -07004909 return devices;
4910}
4911
François Gaffie2110e042015-03-24 08:41:51 +01004912routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4913{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004914 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004915 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004916}
4917
Eric Laurent97ac8712018-07-27 18:59:02 -07004918routing_strategy AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004919 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004920 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004921 return STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004922 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004923 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004924 return STRATEGY_ENFORCED_AUDIBLE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004925 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004926 // usage to strategy mapping
Eric Laurent97ac8712018-07-27 18:59:02 -07004927 return mEngine->getStrategyForUsage(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004928}
4929
Eric Laurente0720872014-03-11 09:30:41 -07004930void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004931 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004932 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004933 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4934 updateDevicesAndOutputs();
4935 break;
4936 default:
4937 break;
4938 }
4939}
4940
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004941uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004942
4943 // skip beacon mute management if a dedicated TTS output is available
4944 if (mTtsOutputAvailable) {
4945 return 0;
4946 }
4947
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004948 switch(event) {
4949 case STARTING_OUTPUT:
4950 mBeaconMuteRefCount++;
4951 break;
4952 case STOPPING_OUTPUT:
4953 if (mBeaconMuteRefCount > 0) {
4954 mBeaconMuteRefCount--;
4955 }
4956 break;
4957 case STARTING_BEACON:
4958 mBeaconPlayingRefCount++;
4959 break;
4960 case STOPPING_BEACON:
4961 if (mBeaconPlayingRefCount > 0) {
4962 mBeaconPlayingRefCount--;
4963 }
4964 break;
4965 }
4966
4967 if (mBeaconMuteRefCount > 0) {
4968 // any playback causes beacon to be muted
4969 return setBeaconMute(true);
4970 } else {
4971 // no other playback: unmute when beacon starts playing, mute when it stops
4972 return setBeaconMute(mBeaconPlayingRefCount == 0);
4973 }
4974}
4975
4976uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4977 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4978 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4979 // keep track of muted state to avoid repeating mute/unmute operations
4980 if (mBeaconMuted != mute) {
4981 // mute/unmute AUDIO_STREAM_TTS on all outputs
4982 ALOGV("\t muting %d", mute);
4983 uint32_t maxLatency = 0;
4984 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004985 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004986 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07004987 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004988 0 /*delay*/, AUDIO_DEVICE_NONE);
4989 const uint32_t latency = desc->latency() * 2;
4990 if (latency > maxLatency) {
4991 maxLatency = latency;
4992 }
4993 }
4994 mBeaconMuted = mute;
4995 return maxLatency;
4996 }
4997 return 0;
4998}
4999
Eric Laurente0720872014-03-11 09:30:41 -07005000audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01005001 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005002{
Eric Laurent97ac8712018-07-27 18:59:02 -07005003 // Honor explicit routing requests only if all active clients have a preferred route in which
5004 // case the last active client route is used
5005 sp<DeviceDescriptor> deviceDesc = findPreferredDevice(mOutputs, strategy, mAvailableOutputDevices);
5006 if (deviceDesc != nullptr) {
5007 return deviceDesc->type();
Paul McLeanaa981192015-03-21 09:55:15 -07005008 }
5009
Eric Laurente552edb2014-03-10 17:42:56 -07005010 if (fromCache) {
5011 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
5012 strategy, mDeviceForStrategy[strategy]);
5013 return mDeviceForStrategy[strategy];
5014 }
François Gaffie2110e042015-03-24 08:41:51 +01005015 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07005016}
5017
Eric Laurente0720872014-03-11 09:30:41 -07005018void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005019{
5020 for (int i = 0; i < NUM_STRATEGIES; i++) {
5021 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
5022 }
5023 mPreviousOutputs = mOutputs;
5024}
5025
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005026uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005027 audio_devices_t prevDevice,
5028 uint32_t delayMs)
5029{
5030 // mute/unmute strategies using an incompatible device combination
5031 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5032 // if unmuting, unmute only after the specified delay
5033 if (outputDesc->isDuplicated()) {
5034 return 0;
5035 }
5036
5037 uint32_t muteWaitMs = 0;
5038 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07005039 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005040
5041 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
5042 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07005043 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07005044 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
5045 bool doMute = false;
5046
5047 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
5048 doMute = true;
5049 outputDesc->mStrategyMutedByDevice[i] = true;
5050 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
5051 doMute = true;
5052 outputDesc->mStrategyMutedByDevice[i] = false;
5053 }
Eric Laurent99401132014-05-07 19:48:15 -07005054 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005055 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005056 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005057 // skip output if it does not share any device with current output
5058 if ((desc->supportedDevices() & outputDesc->supportedDevices())
5059 == AUDIO_DEVICE_NONE) {
5060 continue;
5061 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005062 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07005063 mute ? "muting" : "unmuting", i, curDevice);
5064 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005065 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005066 if (mute) {
5067 // FIXME: should not need to double latency if volume could be applied
5068 // immediately by the audioflinger mixer. We must account for the delay
5069 // between now and the next time the audioflinger thread for this output
5070 // will process a buffer (which corresponds to one buffer size,
5071 // usually 1/2 or 1/4 of the latency).
5072 if (muteWaitMs < desc->latency() * 2) {
5073 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005074 }
5075 }
5076 }
5077 }
5078 }
5079 }
5080
Eric Laurent99401132014-05-07 19:48:15 -07005081 // temporary mute output if device selection changes to avoid volume bursts due to
5082 // different per device volumes
5083 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005084 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5085 // temporary mute duration is conservatively set to 4 times the reported latency
5086 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5087 if (muteWaitMs < tempMuteWaitMs) {
5088 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005089 }
Eric Laurentdc462862016-07-19 12:29:53 -07005090
Eric Laurent99401132014-05-07 19:48:15 -07005091 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005092 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005093 // make sure that we do not start the temporary mute period too early in case of
5094 // delayed device change
5095 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005096 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07005097 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07005098 }
5099 }
5100 }
5101
Eric Laurente552edb2014-03-10 17:42:56 -07005102 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5103 if (muteWaitMs > delayMs) {
5104 muteWaitMs -= delayMs;
5105 usleep(muteWaitMs * 1000);
5106 return muteWaitMs;
5107 }
5108 return 0;
5109}
5110
Eric Laurentc75307b2015-03-17 15:29:32 -07005111uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005112 audio_devices_t device,
5113 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07005114 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005115 audio_patch_handle_t *patchHandle,
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005116 const char *address,
5117 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005118{
Eric Laurentc75307b2015-03-17 15:29:32 -07005119 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005120 AudioParameter param;
5121 uint32_t muteWaitMs;
5122
5123 if (outputDesc->isDuplicated()) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005124 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs,
5125 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
5126 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs,
5127 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005128 return muteWaitMs;
5129 }
5130 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5131 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07005132 if ((device != AUDIO_DEVICE_NONE) &&
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005133 ((device & outputDesc->supportedDevices()) == AUDIO_DEVICE_NONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005134 return 0;
5135 }
5136
5137 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07005138 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07005139
5140 audio_devices_t prevDevice = outputDesc->mDevice;
5141
Paul McLeanaa981192015-03-21 09:55:15 -07005142 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005143
5144 if (device != AUDIO_DEVICE_NONE) {
5145 outputDesc->mDevice = device;
5146 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005147
5148 // if the outputs are not materially active, there is no need to mute.
5149 if (requiresMuteCheck) {
5150 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
5151 } else {
5152 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5153 muteWaitMs = 0;
5154 }
Eric Laurente552edb2014-03-10 17:42:56 -07005155
5156 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005157 // the requested device is AUDIO_DEVICE_NONE
5158 // OR the requested device is the same as current device
5159 // AND force is not specified
5160 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07005161 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07005162 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
5163 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005164 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005165 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005166 return muteWaitMs;
5167 }
5168
5169 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07005170
Eric Laurente552edb2014-03-10 17:42:56 -07005171 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07005172 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005173 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005174 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07005175 DeviceVector deviceList;
5176 if ((address == NULL) || (strlen(address) == 0)) {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005177 deviceList = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurentc40d9692016-04-13 19:14:13 -07005178 } else {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005179 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
5180 device, String8(address));
5181 if (deviceDesc) deviceList.add(deviceDesc);
Eric Laurentc40d9692016-04-13 19:14:13 -07005182 }
5183
Eric Laurent1c333e22014-05-20 10:48:17 -07005184 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005185 PatchBuilder patchBuilder;
5186 patchBuilder.addSource(outputDesc);
Eric Laurent1c333e22014-05-20 10:48:17 -07005187 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005188 patchBuilder.addSink(deviceList.itemAt(i));
Eric Laurent1c333e22014-05-20 10:48:17 -07005189 }
Mikhail Naganovdc769682018-05-04 15:34:08 -07005190 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005191 }
5192 }
Eric Laurente552edb2014-03-10 17:42:56 -07005193
5194 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07005195 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005196
5197 return muteWaitMs;
5198}
5199
Eric Laurentc75307b2015-03-17 15:29:32 -07005200status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005201 int delayMs,
5202 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005203{
Eric Laurent6a94d692014-05-20 11:18:06 -07005204 ssize_t index;
5205 if (patchHandle) {
5206 index = mAudioPatches.indexOfKey(*patchHandle);
5207 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005208 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005209 }
5210 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005211 return INVALID_OPERATION;
5212 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005213 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5214 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005215 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005216 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005217 removeAudioPatch(patchDesc->mHandle);
5218 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005219 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005220 return status;
5221}
5222
5223status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5224 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005225 bool force,
5226 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005227{
5228 status_t status = NO_ERROR;
5229
Eric Laurent1f2f2232014-06-02 12:01:23 -07005230 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005231 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5232 inputDesc->mDevice = device;
5233
Mikhail Naganov708e0382018-05-30 09:53:04 -07005234 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005235 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005236 PatchBuilder patchBuilder;
5237 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005238 // AUDIO_SOURCE_HOTWORD is for internal use only:
5239 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07005240 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5241 auto result = usecase;
5242 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5243 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5244 }
5245 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07005246 //only one input device for now
Mikhail Naganovdc769682018-05-04 15:34:08 -07005247 addSource(deviceList.itemAt(0));
5248 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005249 }
5250 }
5251 return status;
5252}
5253
Eric Laurent6a94d692014-05-20 11:18:06 -07005254status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5255 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005256{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005257 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005258 ssize_t index;
5259 if (patchHandle) {
5260 index = mAudioPatches.indexOfKey(*patchHandle);
5261 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005262 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005263 }
5264 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005265 return INVALID_OPERATION;
5266 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005267 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5268 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005269 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005270 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005271 removeAudioPatch(patchDesc->mHandle);
5272 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005273 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005274 return status;
5275}
5276
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005277sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005278 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005279 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005280 audio_format_t& format,
5281 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005282 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005283{
5284 // Choose an input profile based on the requested capture parameters: select the first available
5285 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005286 //
5287 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5288 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005289
Glenn Kasten730b9262018-03-29 15:01:26 -07005290 sp<IOProfile> firstInexact;
5291 uint32_t updatedSamplingRate = 0;
5292 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5293 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005294 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005295 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005296 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005297 //updatedFormat = format;
Eric Laurent275e8e92014-11-30 15:14:47 -08005298 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005299 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005300 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005301 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005302 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005303 &channelMask /*updatedChannelMask*/,
5304 // FIXME ugly cast
5305 (audio_output_flags_t) flags,
5306 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005307 return profile;
5308 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005309 if (firstInexact == nullptr && profile->isCompatibleProfile(device, address,
5310 samplingRate,
5311 &updatedSamplingRate,
5312 format,
5313 &updatedFormat,
5314 channelMask,
5315 &updatedChannelMask,
5316 // FIXME ugly cast
5317 (audio_output_flags_t) flags,
5318 false /*exactMatchRequiredForInputFlags*/)) {
5319 firstInexact = profile;
5320 }
5321
Eric Laurente552edb2014-03-10 17:42:56 -07005322 }
5323 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005324 if (firstInexact != nullptr) {
5325 samplingRate = updatedSamplingRate;
5326 format = updatedFormat;
5327 channelMask = updatedChannelMask;
5328 return firstInexact;
5329 }
Eric Laurente552edb2014-03-10 17:42:56 -07005330 return NULL;
5331}
5332
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005333
5334audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005335 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005336{
Eric Laurent97ac8712018-07-27 18:59:02 -07005337 // Honor explicit routing requests only if all active clients have a preferred route in which
5338 // case the last active client route is used
5339 sp<DeviceDescriptor> deviceDesc =
5340 findPreferredDevice(mInputs, inputSource, mAvailableInputDevices);
5341 if (deviceDesc != nullptr) {
5342 return deviceDesc->type();
5343 }
5344
5345
François Gaffie036e1e92015-03-19 10:16:24 +01005346 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5347 audio_devices_t selectedDeviceFromMix =
5348 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005349
François Gaffie036e1e92015-03-19 10:16:24 +01005350 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5351 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005352 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005353 return getDeviceForInputSource(inputSource);
5354}
5355
5356audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5357{
Eric Laurent97ac8712018-07-27 18:59:02 -07005358 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005359}
5360
Eric Laurente0720872014-03-11 09:30:41 -07005361float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005362 int index,
5363 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005364{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005365 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005366
5367 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5368 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5369 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5370 // the ringtone volume
5371 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5372 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5373 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5374 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5375 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5376 }
5377
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005378 // in-call: always cap volume by voice volume + some low headroom
5379 if ((stream != AUDIO_STREAM_VOICE_CALL) &&
Eric Laurent7731b5a2018-04-06 15:47:22 -07005380 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005381 switch (stream) {
5382 case AUDIO_STREAM_SYSTEM:
5383 case AUDIO_STREAM_RING:
5384 case AUDIO_STREAM_MUSIC:
5385 case AUDIO_STREAM_ALARM:
5386 case AUDIO_STREAM_NOTIFICATION:
5387 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5388 case AUDIO_STREAM_DTMF:
5389 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005390 int voiceVolumeIndex =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005391 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, device);
Eric Laurent7731b5a2018-04-06 15:47:22 -07005392 const float maxVoiceVolDb =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005393 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, device)
Eric Laurent7731b5a2018-04-06 15:47:22 -07005394 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005395 if (volumeDB > maxVoiceVolDb) {
5396 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5397 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5398 volumeDB = maxVoiceVolDb;
5399 }
5400 } break;
5401 default:
5402 break;
5403 }
5404 }
5405
Eric Laurente552edb2014-03-10 17:42:56 -07005406 // if a headset is connected, apply the following rules to ring tones and notifications
5407 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005408 // - always attenuate notifications volume by 6dB
5409 // - attenuate ring tones volume by 6dB unless music is not playing and
5410 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005411 // - if music is playing, always limit the volume to current music volume,
5412 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005413 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005414 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5415 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5416 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005417 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005418 AUDIO_DEVICE_OUT_USB_HEADSET |
5419 AUDIO_DEVICE_OUT_HEARING_AID)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005420 ((stream_strategy == STRATEGY_SONIFICATION)
5421 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005422 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005423 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005424 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005425 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005426 // when the phone is ringing we must consider that music could have been paused just before
5427 // by the music application and behave as if music was active if the last music track was
5428 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005429 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005430 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005431 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005432 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005433 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005434 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5435 musicDevice),
5436 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005437 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5438 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005439 if (volumeDB > minVolDB) {
5440 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005441 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005442 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005443 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5444 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5445 // on A2DP, also ensure notification volume is not too low compared to media when
5446 // intended to be played
5447 if ((volumeDB > -96.0f) &&
5448 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5449 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5450 stream, device,
5451 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5452 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5453 }
5454 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005455 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5456 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005457 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005458 }
5459 }
5460
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005461 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005462}
5463
Eric Laurent3839bc02018-07-10 18:33:34 -07005464int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
5465 audio_stream_type_t srcStream,
5466 audio_stream_type_t dstStream)
5467{
5468 if (srcStream == dstStream) {
5469 return srcIndex;
5470 }
5471 float minSrc = (float)mVolumeCurves->getVolumeIndexMin(srcStream);
5472 float maxSrc = (float)mVolumeCurves->getVolumeIndexMax(srcStream);
5473 float minDst = (float)mVolumeCurves->getVolumeIndexMin(dstStream);
5474 float maxDst = (float)mVolumeCurves->getVolumeIndexMax(dstStream);
5475
5476 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
5477}
5478
Eric Laurente0720872014-03-11 09:30:41 -07005479status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005480 int index,
5481 const sp<AudioOutputDescriptor>& outputDesc,
5482 audio_devices_t device,
5483 int delayMs,
5484 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005485{
Eric Laurente552edb2014-03-10 17:42:56 -07005486 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005487 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005488 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005489 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005490 return NO_ERROR;
5491 }
François Gaffie2110e042015-03-24 08:41:51 +01005492 audio_policy_forced_cfg_t forceUseForComm =
5493 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005494 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005495 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5496 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005497 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005498 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005499 return INVALID_OPERATION;
5500 }
5501
Eric Laurentc75307b2015-03-17 15:29:32 -07005502 if (device == AUDIO_DEVICE_NONE) {
5503 device = outputDesc->device();
5504 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005505
Eric Laurentffbc80f2015-03-18 18:30:19 -07005506 float volumeDb = computeVolume(stream, index, device);
HW Leeda7581e2018-05-22 18:31:34 +08005507 if (outputDesc->isFixedVolume(device) ||
5508 // Force VoIP volume to max for bluetooth SCO
5509 ((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
5510 (device & AUDIO_DEVICE_OUT_ALL_SCO) != 0)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005511 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005512 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005513
Eric Laurentffbc80f2015-03-18 18:30:19 -07005514 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005515
Eric Laurent3b73df72014-03-11 09:06:29 -07005516 if (stream == AUDIO_STREAM_VOICE_CALL ||
5517 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005518 float voiceVolume;
5519 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005520 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurent3839bc02018-07-10 18:33:34 -07005521 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005522 } else {
5523 voiceVolume = 1.0;
5524 }
5525
Eric Laurent18fba842016-03-31 14:41:26 -07005526 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005527 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5528 mLastVoiceVolume = voiceVolume;
5529 }
5530 }
5531
5532 return NO_ERROR;
5533}
5534
Eric Laurentc75307b2015-03-17 15:29:32 -07005535void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5536 audio_devices_t device,
5537 int delayMs,
5538 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005539{
Eric Laurentc75307b2015-03-17 15:29:32 -07005540 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005541
Eric Laurent794fde22016-03-11 09:50:45 -08005542 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005543 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005544 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005545 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005546 device,
5547 delayMs,
5548 force);
5549 }
5550}
5551
Eric Laurente0720872014-03-11 09:30:41 -07005552void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005553 bool on,
5554 const sp<AudioOutputDescriptor>& outputDesc,
5555 int delayMs,
5556 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005557{
Eric Laurent72249d52015-06-08 11:12:15 -07005558 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5559 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005560 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005561 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005562 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005563 }
5564 }
5565}
5566
Eric Laurente0720872014-03-11 09:30:41 -07005567void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005568 bool on,
5569 const sp<AudioOutputDescriptor>& outputDesc,
5570 int delayMs,
5571 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005572{
Eric Laurente552edb2014-03-10 17:42:56 -07005573 if (device == AUDIO_DEVICE_NONE) {
5574 device = outputDesc->device();
5575 }
5576
Eric Laurentc75307b2015-03-17 15:29:32 -07005577 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5578 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005579
5580 if (on) {
5581 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005582 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005583 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005584 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005585 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005586 }
5587 }
5588 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5589 outputDesc->mMuteCount[stream]++;
5590 } else {
5591 if (outputDesc->mMuteCount[stream] == 0) {
5592 ALOGV("setStreamMute() unmuting non muted stream!");
5593 return;
5594 }
5595 if (--outputDesc->mMuteCount[stream] == 0) {
5596 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005597 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005598 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005599 device,
5600 delayMs);
5601 }
5602 }
5603}
5604
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005605audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5606{
5607 // flags to stream type mapping
5608 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5609 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5610 }
5611 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5612 return AUDIO_STREAM_BLUETOOTH_SCO;
5613 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005614 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5615 return AUDIO_STREAM_TTS;
5616 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005617
Ari Hausman-Cohen5c00d012018-06-26 17:09:11 -07005618 return audio_usage_to_stream_type(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005619}
Eric Laurente83b55d2014-11-14 10:06:21 -08005620
François Gaffie53615e22015-03-19 09:24:12 +01005621bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5622{
Eric Laurente83b55d2014-11-14 10:06:21 -08005623 // has flags that map to a strategy?
5624 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5625 return true;
5626 }
5627
5628 // has known usage?
5629 switch (paa->usage) {
5630 case AUDIO_USAGE_UNKNOWN:
5631 case AUDIO_USAGE_MEDIA:
5632 case AUDIO_USAGE_VOICE_COMMUNICATION:
5633 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5634 case AUDIO_USAGE_ALARM:
5635 case AUDIO_USAGE_NOTIFICATION:
5636 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5637 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5638 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5639 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5640 case AUDIO_USAGE_NOTIFICATION_EVENT:
5641 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5642 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5643 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5644 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005645 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005646 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005647 break;
5648 default:
5649 return false;
5650 }
5651 return true;
5652}
5653
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005654bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005655 routing_strategy strategy, uint32_t inPastMs,
5656 nsecs_t sysTime) const
5657{
5658 if ((sysTime == 0) && (inPastMs != 0)) {
5659 sysTime = systemTime();
5660 }
Eric Laurent794fde22016-03-11 09:50:45 -08005661 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005662 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurent97ac8712018-07-27 18:59:02 -07005663 (STRATEGY_NONE == strategy)) &&
François Gaffiead3183e2015-03-18 16:55:35 +01005664 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5665 return true;
5666 }
5667 }
5668 return false;
5669}
5670
Eric Laurent484e9272018-06-07 17:29:23 -07005671bool AudioPolicyManager::isStrategyActiveOnSameModule(const sp<AudioOutputDescriptor>& outputDesc,
5672 routing_strategy strategy, uint32_t inPastMs,
5673 nsecs_t sysTime) const
5674{
5675 for (size_t i = 0; i < mOutputs.size(); i++) {
5676 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5677 if (outputDesc->sharesHwModuleWith(desc)
5678 && isStrategyActive(desc, strategy, inPastMs, sysTime)) {
5679 return true;
5680 }
5681 }
5682 return false;
5683}
5684
François Gaffie2110e042015-03-24 08:41:51 +01005685audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5686{
5687 return mEngine->getForceUse(usage);
5688}
5689
5690bool AudioPolicyManager::isInCall()
5691{
5692 return isStateInCall(mEngine->getPhoneState());
5693}
5694
5695bool AudioPolicyManager::isStateInCall(int state)
5696{
5697 return is_state_in_call(state);
5698}
5699
Eric Laurentd60560a2015-04-10 11:31:20 -07005700void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5701{
5702 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005703 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5704 if (sourceDesc->srcDevice()->equals(deviceDesc)) {
5705 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->portId());
5706 stopAudioSource(sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005707 }
5708 }
5709
5710 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5711 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5712 bool release = false;
5713 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5714 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5715 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5716 source->ext.device.type == deviceDesc->type()) {
5717 release = true;
5718 }
5719 }
5720 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5721 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5722 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5723 sink->ext.device.type == deviceDesc->type()) {
5724 release = true;
5725 }
5726 }
5727 if (release) {
5728 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5729 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5730 }
5731 }
5732}
5733
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005734void AudioPolicyManager::modifySurroundFormats(
5735 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005736 std::unordered_set<audio_format_t> enforcedSurround(
5737 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08005738 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
5739 for (const auto& pair : mConfig.getSurroundFormats()) {
5740 allSurround.insert(pair.first);
5741 for (const auto& subformat : pair.second) allSurround.insert(subformat);
5742 }
Phil Burk09bc4612016-02-24 15:58:15 -08005743
5744 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5745 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005746 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005747 // This is the resulting set of formats depending on the surround mode:
5748 // 'all surround' = allSurround
5749 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
5750 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
5751 // 'manual surround' = mManualSurroundFormats
5752 // AUTO: formats v 'enforced surround'
5753 // ALWAYS: formats v 'all surround' v 'enforced surround'
5754 // NEVER: formats ^ 'non-surround'
5755 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08005756
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005757 std::unordered_set<audio_format_t> formatSet;
5758 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
5759 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005760 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005761 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005762 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005763 formatSet.insert(*formatIter);
5764 }
5765 }
5766 } else {
5767 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
5768 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005769 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005770
jiabin81772902018-04-02 17:52:27 -07005771 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005772 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005773 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
5774 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
5775 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08005776 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005777 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
5778 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5779 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07005780 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005781 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08005782 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005783 for (const auto& format : formatSet) {
5784 formatsPtr->push(format);
5785 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005786}
5787
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005788void AudioPolicyManager::modifySurroundChannelMasks(ChannelsVector *channelMasksPtr) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005789 ChannelsVector &channelMasks = *channelMasksPtr;
5790 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5791 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5792
5793 // If NEVER, then remove support for channelMasks > stereo.
5794 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5795 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5796 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5797 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5798 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5799 channelMasks.removeAt(maskIndex);
5800 } else {
5801 maskIndex++;
5802 }
5803 }
jiabin81772902018-04-02 17:52:27 -07005804 // If ALWAYS or MANUAL, then make sure we at least support 5.1
5805 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
5806 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005807 bool supports5dot1 = false;
5808 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005809 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005810 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5811 supports5dot1 = true;
5812 break;
5813 }
5814 }
5815 // If not then add 5.1 support.
5816 if (!supports5dot1) {
5817 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005818 ALOGI("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07005819 }
Phil Burk09bc4612016-02-24 15:58:15 -08005820 }
5821}
5822
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005823void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07005824 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005825 AudioProfileVector &profiles)
5826{
5827 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005828 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07005829
François Gaffie112b0af2015-11-19 16:13:25 +01005830 // Format MUST be checked first to update the list of AudioProfile
5831 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005832 reply = mpClientInterface->getParameters(
5833 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07005834 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005835 AudioParameter repliedParameters(reply);
5836 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005837 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005838 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5839 return;
5840 }
Phil Burk09bc4612016-02-24 15:58:15 -08005841 FormatVector formats = formatsFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08005842 if (device == AUDIO_DEVICE_OUT_HDMI
5843 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005844 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005845 }
Phil Burk09bc4612016-02-24 15:58:15 -08005846 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005847 }
François Gaffie112b0af2015-11-19 16:13:25 +01005848
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005849 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08005850 ChannelsVector channelMasks;
5851 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005852 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07005853 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01005854
5855 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005856 reply = mpClientInterface->getParameters(
5857 ioHandle,
5858 requestedParameters.toString() + ";" +
5859 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01005860 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005861 AudioParameter repliedParameters(reply);
5862 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005863 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005864 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005865 }
5866 }
5867 if (profiles.hasDynamicChannelsFor(format)) {
5868 reply = mpClientInterface->getParameters(ioHandle,
5869 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07005870 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01005871 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005872 AudioParameter repliedParameters(reply);
5873 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005874 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005875 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08005876 if (device == AUDIO_DEVICE_OUT_HDMI
5877 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005878 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07005879 }
François Gaffie112b0af2015-11-19 16:13:25 +01005880 }
5881 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08005882 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01005883 }
5884}
Eric Laurentd60560a2015-04-10 11:31:20 -07005885
Mikhail Naganovdc769682018-05-04 15:34:08 -07005886status_t AudioPolicyManager::installPatch(const char *caller,
5887 audio_patch_handle_t *patchHandle,
5888 AudioIODescriptorInterface *ioDescriptor,
5889 const struct audio_patch *patch,
5890 int delayMs)
5891{
5892 ssize_t index = mAudioPatches.indexOfKey(
5893 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
5894 *patchHandle : ioDescriptor->getPatchHandle());
5895 sp<AudioPatch> patchDesc;
5896 status_t status = installPatch(
5897 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
5898 if (status == NO_ERROR) {
5899 ioDescriptor->setPatchHandle(patchDesc->mHandle);
5900 }
5901 return status;
5902}
5903
5904status_t AudioPolicyManager::installPatch(const char *caller,
5905 ssize_t index,
5906 audio_patch_handle_t *patchHandle,
5907 const struct audio_patch *patch,
5908 int delayMs,
5909 uid_t uid,
5910 sp<AudioPatch> *patchDescPtr)
5911{
5912 sp<AudioPatch> patchDesc;
5913 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
5914 if (index >= 0) {
5915 patchDesc = mAudioPatches.valueAt(index);
5916 afPatchHandle = patchDesc->mAfPatchHandle;
5917 }
5918
5919 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
5920 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
5921 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
5922 if (status == NO_ERROR) {
5923 if (index < 0) {
5924 patchDesc = new AudioPatch(patch, uid);
5925 addAudioPatch(patchDesc->mHandle, patchDesc);
5926 } else {
5927 patchDesc->mPatch = *patch;
5928 }
5929 patchDesc->mAfPatchHandle = afPatchHandle;
5930 if (patchHandle) {
5931 *patchHandle = patchDesc->mHandle;
5932 }
5933 nextAudioPortGeneration();
5934 mpClientInterface->onAudioPatchListUpdate();
5935 }
5936 if (patchDescPtr) *patchDescPtr = patchDesc;
5937 return status;
5938}
5939
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08005940} // namespace android