blob: 21f893a10cf5e1c2cc33237045057819e1d0e135 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070017#define LOG_TAG "APM_AudioPolicyManager"
Eric Laurente552edb2014-03-10 17:42:56 -070018//#define LOG_NDEBUG 0
19
20//#define VERY_VERBOSE_LOGGING
21#ifdef VERY_VERBOSE_LOGGING
22#define ALOGVV ALOGV
23#else
24#define ALOGVV(a...) do { } while(0)
25#endif
26
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +090027#define AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH 128
28#define AUDIO_POLICY_XML_CONFIG_FILE_NAME "audio_policy_configuration.xml"
Petri Gyntherf497f292018-04-17 18:46:10 -070029#define AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME \
30 "audio_policy_configuration_a2dp_offload_disabled.xml"
François Gaffief4ad6e52015-11-19 16:59:57 +010031
Eric Laurentd4692962014-05-05 18:13:44 -070032#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070033#include <math.h>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110034#include <vector>
Eric Laurentd4692962014-05-05 18:13:44 -070035
François Gaffie2110e042015-03-24 08:41:51 +010036#include <AudioPolicyManagerInterface.h>
37#include <AudioPolicyEngineInstance.h>
Eric Laurente552edb2014-03-10 17:42:56 -070038#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070039#include <utils/Log.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070040#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080041#include <media/AudioPolicyHelper.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070042#include <private/android_filesystem_config.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070043#include <soundtrigger/SoundTrigger.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070044#include <system/audio.h>
Mikhail Naganov9ee05402016-10-13 15:58:17 -070045#include <audio_policy_conf.h>
Eric Laurentd4692962014-05-05 18:13:44 -070046#include "AudioPolicyManager.h"
François Gaffied1ab2bd2015-12-02 18:20:06 +010047#ifndef USE_XML_AUDIO_POLICY_CONF
François Gaffie53615e22015-03-19 09:24:12 +010048#include <ConfigParsingUtils.h>
François Gaffied1ab2bd2015-12-02 18:20:06 +010049#include <StreamDescriptor.h>
François Gaffief4ad6e52015-11-19 16:59:57 +010050#endif
François Gaffied1ab2bd2015-12-02 18:20:06 +010051#include <Serializer.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010052#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010053#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070054
Eric Laurent3b73df72014-03-11 09:06:29 -070055namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070056
Eric Laurentdc462862016-07-19 12:29:53 -070057//FIXME: workaround for truncated touch sounds
58// to be removed when the problem is handled by system UI
59#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070060
61// Largest difference in dB on earpiece in call between the voice volume and another
62// media / notification / system volume.
63constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
64
jiabin81772902018-04-02 17:52:27 -070065#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
66// Array of all surround formats.
67static const audio_format_t SURROUND_FORMATS[] = {
68 AUDIO_FORMAT_AC3,
69 AUDIO_FORMAT_E_AC3,
70 AUDIO_FORMAT_DTS,
71 AUDIO_FORMAT_DTS_HD,
72 AUDIO_FORMAT_AAC_LC,
73 AUDIO_FORMAT_DOLBY_TRUEHD,
74 AUDIO_FORMAT_E_AC3_JOC,
75};
76// Array of all AAC formats. When AAC is enabled by users, all AAC formats should be enabled.
77static const audio_format_t AAC_FORMATS[] = {
78 AUDIO_FORMAT_AAC_LC,
79 AUDIO_FORMAT_AAC_HE_V1,
80 AUDIO_FORMAT_AAC_HE_V2,
81 AUDIO_FORMAT_AAC_ELD,
82 AUDIO_FORMAT_AAC_XHE,
83};
84
Mikhail Naganov15be9d22017-11-08 14:18:13 +110085// Compressed formats for MSD module, ordered from most preferred to least preferred.
86static const std::vector<audio_format_t> compressedFormatsOrder = {{
87 AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
88 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
89// Channel masks for MSD module, 3D > 2D > 1D ordering (most preferred to least preferred).
90static const std::vector<audio_channel_mask_t> surroundChannelMasksOrder = {{
91 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
92 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
93 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
94
Eric Laurente552edb2014-03-10 17:42:56 -070095// ----------------------------------------------------------------------------
96// AudioPolicyInterface implementation
97// ----------------------------------------------------------------------------
98
Eric Laurente0720872014-03-11 09:30:41 -070099status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -0800100 audio_policy_dev_state_t state,
101 const char *device_address,
102 const char *device_name)
Eric Laurente552edb2014-03-10 17:42:56 -0700103{
jiabina7b43792018-02-15 16:04:46 -0800104 status_t status = setDeviceConnectionStateInt(device, state, device_address, device_name);
105 nextAudioPortGeneration();
106 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800107}
108
François Gaffie44481e72016-04-20 07:49:57 +0200109void AudioPolicyManager::broadcastDeviceConnectionState(audio_devices_t device,
110 audio_policy_dev_state_t state,
111 const String8 &device_address)
112{
113 AudioParameter param(device_address);
114 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganov388360c2016-10-17 17:09:41 -0700115 AudioParameter::keyStreamConnect : AudioParameter::keyStreamDisconnect);
François Gaffie44481e72016-04-20 07:49:57 +0200116 param.addInt(key, device);
117 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
118}
119
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800120status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800121 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -0800122 const char *device_address,
123 const char *device_name)
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800124{
Paul McLeane743a472015-01-28 11:07:31 -0800125 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s",
Mikhail Naganov7e22e942017-12-07 10:04:29 -0800126 device, state, device_address, device_name);
Eric Laurente552edb2014-03-10 17:42:56 -0700127
128 // connect/disconnect only 1 device at a time
129 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
130
François Gaffie53615e22015-03-19 09:24:12 +0100131 sp<DeviceDescriptor> devDesc =
132 mHwModules.getDeviceDescriptor(device, device_address, device_name);
Paul McLeane743a472015-01-28 11:07:31 -0800133
Eric Laurente552edb2014-03-10 17:42:56 -0700134 // handle output devices
135 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700136 SortedVector <audio_io_handle_t> outputs;
137
Eric Laurent3a4311c2014-03-17 12:00:47 -0700138 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
139
Eric Laurente552edb2014-03-10 17:42:56 -0700140 // save a copy of the opened output descriptors before any output is opened or closed
141 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
142 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700143 switch (state)
144 {
145 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800146 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700147 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700148 ALOGW("setDeviceConnectionState() device already connected: %x", device);
149 return INVALID_OPERATION;
150 }
151 ALOGV("setDeviceConnectionState() connecting device %x", device);
152
Eric Laurente552edb2014-03-10 17:42:56 -0700153 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700154 index = mAvailableOutputDevices.add(devDesc);
155 if (index >= 0) {
François Gaffie53615e22015-03-19 09:24:12 +0100156 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700157 if (module == 0) {
158 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
159 device);
160 mAvailableOutputDevices.remove(devDesc);
161 return INVALID_OPERATION;
162 }
Paul McLeane743a472015-01-28 11:07:31 -0800163 mAvailableOutputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700164 } else {
165 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700166 }
167
François Gaffie44481e72016-04-20 07:49:57 +0200168 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
169 // parameters on newly connected devices (instead of opening the outputs...)
170 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
171
Eric Laurenta1d525f2015-01-29 13:36:45 -0800172 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700173 mAvailableOutputDevices.remove(devDesc);
François Gaffie44481e72016-04-20 07:49:57 +0200174
175 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
176 devDesc->mAddress);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700177 return INVALID_OPERATION;
178 }
François Gaffie2110e042015-03-24 08:41:51 +0100179 // Propagate device availability to Engine
180 mEngine->setDeviceConnectionState(devDesc, state);
181
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700182 // outputs should never be empty here
183 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
184 "checkOutputsForDevice() returned no outputs but status OK");
185 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
186 outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800187
Eric Laurent3ae5f312015-02-03 17:12:08 -0800188 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700189 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700190 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700191 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700192 ALOGW("setDeviceConnectionState() device not connected: %x", device);
193 return INVALID_OPERATION;
194 }
195
Paul McLean5c477aa2014-08-20 16:47:57 -0700196 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
197
Paul McLeane743a472015-01-28 11:07:31 -0800198 // Send Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200199 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700200
Eric Laurente552edb2014-03-10 17:42:56 -0700201 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700202 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700203
Eric Laurenta1d525f2015-01-29 13:36:45 -0800204 checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress);
François Gaffie2110e042015-03-24 08:41:51 +0100205
206 // Propagate device availability to Engine
207 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700208 } break;
209
210 default:
211 ALOGE("setDeviceConnectionState() invalid state: %x", state);
212 return BAD_VALUE;
213 }
214
Mikhail Naganov37977152018-07-11 15:54:44 -0700215 checkForDeviceAndOutputChanges([&]() {
216 // outputs must be closed after checkOutputForAllStrategies() is executed
217 if (!outputs.isEmpty()) {
218 for (audio_io_handle_t output : outputs) {
219 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
220 // close unused outputs after device disconnection or direct outputs that have been
221 // opened by checkOutputsForDevice() to query dynamic parameters
222 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
223 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
224 (desc->mDirectOpenCount == 0))) {
225 closeOutput(output);
226 }
Eric Laurente552edb2014-03-10 17:42:56 -0700227 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700228 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
229 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700230 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700231 return false;
232 });
Eric Laurente552edb2014-03-10 17:42:56 -0700233
Eric Laurent87ffa392015-05-22 10:32:38 -0700234 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700235 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
236 updateCallRouting(newDevice);
237 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100238 const audio_devices_t msdOutDevice = getMsdAudioOutDeviceTypes();
Eric Laurente552edb2014-03-10 17:42:56 -0700239 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700240 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
241 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
242 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700243 // do not force device change on duplicated output because if device is 0, it will
244 // also force a device 0 for the two outputs it is duplicated to which may override
245 // a valid device selection on those outputs.
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100246 bool force = (msdOutDevice == AUDIO_DEVICE_NONE || msdOutDevice != desc->device())
247 && !desc->isDuplicated()
François Gaffie53615e22015-03-19 09:24:12 +0100248 && (!device_distinguishes_on_address(device)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700249 // always force when disconnecting (a non-duplicated device)
250 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
Eric Laurentc75307b2015-03-17 15:29:32 -0700251 setOutputDevice(desc, newDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700252 }
Eric Laurente552edb2014-03-10 17:42:56 -0700253 }
254
Eric Laurentd60560a2015-04-10 11:31:20 -0700255 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
256 cleanUpForDevice(devDesc);
257 }
258
Eric Laurent72aa32f2014-05-30 18:51:48 -0700259 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700260 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700261 } // end if is output device
262
Eric Laurente552edb2014-03-10 17:42:56 -0700263 // handle input devices
264 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700265 SortedVector <audio_io_handle_t> inputs;
266
Eric Laurent3a4311c2014-03-17 12:00:47 -0700267 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700268 switch (state)
269 {
270 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700271 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700272 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700273 ALOGW("setDeviceConnectionState() device already connected: %d", device);
274 return INVALID_OPERATION;
275 }
François Gaffie53615e22015-03-19 09:24:12 +0100276 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700277 if (module == NULL) {
278 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
279 device);
280 return INVALID_OPERATION;
281 }
François Gaffie44481e72016-04-20 07:49:57 +0200282
283 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
284 // parameters on newly connected devices (instead of opening the inputs...)
285 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
286
Paul McLean9080a4c2015-06-18 08:24:02 -0700287 if (checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress) != NO_ERROR) {
François Gaffie44481e72016-04-20 07:49:57 +0200288 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
289 devDesc->mAddress);
Eric Laurentd4692962014-05-05 18:13:44 -0700290 return INVALID_OPERATION;
291 }
292
Eric Laurent3a4311c2014-03-17 12:00:47 -0700293 index = mAvailableInputDevices.add(devDesc);
294 if (index >= 0) {
Paul McLeane743a472015-01-28 11:07:31 -0800295 mAvailableInputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700296 } else {
297 return NO_MEMORY;
298 }
Eric Laurent3ae5f312015-02-03 17:12:08 -0800299
François Gaffie2110e042015-03-24 08:41:51 +0100300 // Propagate device availability to Engine
301 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700302 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700303
304 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700305 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700306 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700307 ALOGW("setDeviceConnectionState() device not connected: %d", device);
308 return INVALID_OPERATION;
309 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700310
311 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
312
313 // Set Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200314 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700315
Paul McLean9080a4c2015-06-18 08:24:02 -0700316 checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700317 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700318
François Gaffie2110e042015-03-24 08:41:51 +0100319 // Propagate device availability to Engine
320 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700321 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700322
323 default:
324 ALOGE("setDeviceConnectionState() invalid state: %x", state);
325 return BAD_VALUE;
326 }
327
Eric Laurentd4692962014-05-05 18:13:44 -0700328 closeAllInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700329 // As the input device list can impact the output device selection, update
330 // getDeviceForStrategy() cache
331 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700332
Eric Laurent87ffa392015-05-22 10:32:38 -0700333 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700334 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
335 updateCallRouting(newDevice);
336 }
337
Eric Laurentd60560a2015-04-10 11:31:20 -0700338 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
339 cleanUpForDevice(devDesc);
340 }
341
Eric Laurentb52c1522014-05-20 11:27:36 -0700342 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700343 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700344 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700345
346 ALOGW("setDeviceConnectionState() invalid device: %x", device);
347 return BAD_VALUE;
348}
349
Eric Laurente0720872014-03-11 09:30:41 -0700350audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100351 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700352{
Eric Laurent634b7142016-04-20 13:48:02 -0700353 sp<DeviceDescriptor> devDesc =
354 mHwModules.getDeviceDescriptor(device, device_address, "",
355 (strlen(device_address) != 0)/*matchAddress*/);
356
357 if (devDesc == 0) {
358 ALOGW("getDeviceConnectionState() undeclared device, type %08x, address: %s",
359 device, device_address);
360 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
361 }
François Gaffie53615e22015-03-19 09:24:12 +0100362
Eric Laurent3a4311c2014-03-17 12:00:47 -0700363 DeviceVector *deviceVector;
364
Eric Laurente552edb2014-03-10 17:42:56 -0700365 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700366 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700367 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700368 deviceVector = &mAvailableInputDevices;
369 } else {
370 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
371 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700372 }
Eric Laurent634b7142016-04-20 13:48:02 -0700373
374 return (deviceVector->getDevice(device, String8(device_address)) != 0) ?
375 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800376}
377
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800378status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
379 const char *device_address,
380 const char *device_name)
381{
382 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700383 String8 reply;
384 AudioParameter param;
385 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800386
387 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s",
388 device, device_address, device_name);
389
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800390 // connect/disconnect only 1 device at a time
391 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
392
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800393 // Check if the device is currently connected
394 sp<DeviceDescriptor> devDesc =
395 mHwModules.getDeviceDescriptor(device, device_address, device_name);
396 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
397 if (index < 0) {
398 // Nothing to do: device is not connected
399 return NO_ERROR;
400 }
401
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700402 // For offloaded A2DP, Hw modules may have the capability to
403 // configure codecs. Check if any of the loaded hw modules
404 // supports this.
405 // If supported, send a set parameter to configure A2DP codecs
406 // and return. No need to toggle device state.
407 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
408 reply = mpClientInterface->getParameters(
409 AUDIO_IO_HANDLE_NONE,
410 String8(AudioParameter::keyReconfigA2dpSupported));
411 AudioParameter repliedParameters(reply);
412 repliedParameters.getInt(
413 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
414 if (isReconfigA2dpSupported) {
415 const String8 key(AudioParameter::keyReconfigA2dp);
416 param.add(key, String8("true"));
417 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
418 return NO_ERROR;
419 }
420 }
421
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800422 // Toggle the device state: UNAVAILABLE -> AVAILABLE
423 // This will force reading again the device configuration
424 status = setDeviceConnectionState(device,
425 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
426 device_address, device_name);
427 if (status != NO_ERROR) {
428 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
429 status);
430 return status;
431 }
432
433 status = setDeviceConnectionState(device,
434 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
435 device_address, device_name);
436 if (status != NO_ERROR) {
437 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
438 status);
439 return status;
440 }
441
442 return NO_ERROR;
443}
444
Eric Laurentdc462862016-07-19 12:29:53 -0700445uint32_t AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700446{
447 bool createTxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700448 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700449
Andy Hunga76c7de2016-12-13 19:14:31 -0800450 if(!hasPrimaryOutput() || mPrimaryOutput->device() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurentdc462862016-07-19 12:29:53 -0700451 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700452 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800453 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700454 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
455
456 // release existing RX patch if any
457 if (mCallRxPatch != 0) {
458 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
459 mCallRxPatch.clear();
460 }
461 // release TX patch if any
462 if (mCallTxPatch != 0) {
463 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
464 mCallTxPatch.clear();
465 }
466
467 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
468 // via setOutputDevice() on primary output.
469 // Otherwise, create two audio patches for TX and RX path.
470 if (availablePrimaryOutputDevices() & rxDevice) {
Eric Laurentdc462862016-07-19 12:29:53 -0700471 muteWaitMs = setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700472 // If the TX device is also on the primary HW module, setOutputDevice() will take care
473 // of it due to legacy implementation. If not, create a patch.
474 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
475 == AUDIO_DEVICE_NONE) {
476 createTxPatch = true;
477 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700478 } else { // create RX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800479 mCallRxPatch = createTelephonyPatch(true /*isRx*/, rxDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700480 createTxPatch = true;
481 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700482 if (createTxPatch) { // create TX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800483 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txDevice, delayMs);
484 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700485
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800486 return muteWaitMs;
487}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700488
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800489sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
490 bool isRx, audio_devices_t device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700491 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700492
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800493 sp<DeviceDescriptor> txSourceDeviceDesc;
494 if (isRx) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700495 patchBuilder.addSink(findDevice(mAvailableOutputDevices, device)).
496 addSource(findDevice(mAvailableInputDevices, AUDIO_DEVICE_IN_TELEPHONY_RX));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800497 } else {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700498 patchBuilder.addSource(txSourceDeviceDesc = findDevice(mAvailableInputDevices, device)).
499 addSink(findDevice(mAvailableOutputDevices, AUDIO_DEVICE_OUT_TELEPHONY_TX));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800500 }
501
502 audio_devices_t outputDevice = isRx ? device : AUDIO_DEVICE_OUT_TELEPHONY_TX;
503 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(outputDevice, mOutputs);
504 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
505 // request to reuse existing output stream if one is already opened to reach the target device
506 if (output != AUDIO_IO_HANDLE_NONE) {
507 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
508 ALOG_ASSERT(!outputDesc->isDuplicated(),
509 "%s() %#x device output %d is duplicated", __func__, outputDevice, output);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700510 patchBuilder.addSource(outputDesc, { .stream = AUDIO_STREAM_PATCH });
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800511 }
512
513 if (!isRx) {
Eric Laurentc0a889f2015-10-14 14:36:34 -0700514 // terminate active capture if on the same HW module as the call TX source device
515 // FIXME: would be better to refine to only inputs whose profile connects to the
516 // call TX device but this information is not in the audio patch and logic here must be
517 // symmetric to the one in startInput()
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800518 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800519 if (activeDesc->hasSameHwModuleAs(txSourceDeviceDesc)) {
Eric Laurent8f42ea12018-08-08 09:08:25 -0700520 closeActiveClients(activeDesc);
Eric Laurentc0a889f2015-10-14 14:36:34 -0700521 }
522 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700523 }
Eric Laurentdc462862016-07-19 12:29:53 -0700524
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800525 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Mikhail Naganovdc769682018-05-04 15:34:08 -0700526 status_t status = mpClientInterface->createAudioPatch(
527 patchBuilder.patch(), &afPatchHandle, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800528 ALOGW_IF(status != NO_ERROR,
529 "%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
530 sp<AudioPatch> audioPatch;
531 if (status == NO_ERROR) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700532 audioPatch = new AudioPatch(patchBuilder.patch(), mUidCached);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800533 audioPatch->mAfPatchHandle = afPatchHandle;
534 audioPatch->mUid = mUidCached;
535 }
536 return audioPatch;
537}
538
Mikhail Naganovdc769682018-05-04 15:34:08 -0700539sp<DeviceDescriptor> AudioPolicyManager::findDevice(
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100540 const DeviceVector& devices, audio_devices_t device) const {
Mikhail Naganov708e0382018-05-30 09:53:04 -0700541 DeviceVector deviceList = devices.getDevicesFromTypeMask(device);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800542 ALOG_ASSERT(!deviceList.isEmpty(),
543 "%s() selected device type %#x is not in devices list", __func__, device);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700544 return deviceList.itemAt(0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700545}
546
Eric Laurente0720872014-03-11 09:30:41 -0700547void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700548{
549 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100550 // store previous phone state for management of sonification strategy below
551 int oldState = mEngine->getPhoneState();
552
553 if (mEngine->setPhoneState(state) != NO_ERROR) {
554 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700555 return;
556 }
François Gaffie2110e042015-03-24 08:41:51 +0100557 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700558 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700559 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700560 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800561 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700562 }
563
François Gaffie2110e042015-03-24 08:41:51 +0100564 /**
565 * Switching to or from incall state or switching between telephony and VoIP lead to force
566 * routing command.
567 */
568 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
569 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700570
571 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700572 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700573
Eric Laurente552edb2014-03-10 17:42:56 -0700574 int delayMs = 0;
575 if (isStateInCall(state)) {
576 nsecs_t sysTime = systemTime();
577 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700578 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700579 // mute media and sonification strategies and delay device switch by the largest
580 // latency of any output where either strategy is active.
581 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100582 if ((isStrategyActive(desc, STRATEGY_MEDIA,
583 SONIFICATION_HEADSET_MUSIC_DELAY,
584 sysTime) ||
585 isStrategyActive(desc, STRATEGY_SONIFICATION,
586 SONIFICATION_HEADSET_MUSIC_DELAY,
587 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700588 (delayMs < (int)desc->latency()*2)) {
589 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700590 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700591 setStrategyMute(STRATEGY_MEDIA, true, desc);
592 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700593 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700594 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
595 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700596 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
597 }
598 }
599
Eric Laurent87ffa392015-05-22 10:32:38 -0700600 if (hasPrimaryOutput()) {
601 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
602 // the device returned is not necessarily reachable via this output
603 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
604 // force routing command to audio hardware when ending call
605 // even if no device change is needed
606 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
607 rxDevice = mPrimaryOutput->device();
608 }
Eric Laurente552edb2014-03-10 17:42:56 -0700609
Eric Laurent87ffa392015-05-22 10:32:38 -0700610 if (state == AUDIO_MODE_IN_CALL) {
611 updateCallRouting(rxDevice, delayMs);
612 } else if (oldState == AUDIO_MODE_IN_CALL) {
613 if (mCallRxPatch != 0) {
614 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
615 mCallRxPatch.clear();
616 }
617 if (mCallTxPatch != 0) {
618 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
619 mCallTxPatch.clear();
620 }
621 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
622 } else {
623 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700624 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700625 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700626
627 // reevaluate routing on all outputs in case tracks have been started during the call
628 for (size_t i = 0; i < mOutputs.size(); i++) {
629 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
630 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
631 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
Yung Ti Suf60c8242018-05-10 18:07:26 +0800632 setOutputDevice(desc, newDevice, (newDevice != AUDIO_DEVICE_NONE), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700633 }
634 }
635
Eric Laurente552edb2014-03-10 17:42:56 -0700636 if (isStateInCall(state)) {
637 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700638 // force reevaluating accessibility routing when call starts
639 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700640 }
641
642 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700643 if (state == AUDIO_MODE_RINGTONE &&
644 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700645 mLimitRingtoneVolume = true;
646 } else {
647 mLimitRingtoneVolume = false;
648 }
649}
650
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700651audio_mode_t AudioPolicyManager::getPhoneState() {
652 return mEngine->getPhoneState();
653}
654
Eric Laurente0720872014-03-11 09:30:41 -0700655void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700656 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700657{
François Gaffie2110e042015-03-24 08:41:51 +0100658 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700659 if (config == mEngine->getForceUse(usage)) {
660 return;
661 }
Eric Laurente552edb2014-03-10 17:42:56 -0700662
François Gaffie2110e042015-03-24 08:41:51 +0100663 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
664 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
665 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700666 }
François Gaffie2110e042015-03-24 08:41:51 +0100667 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
668 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
669 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700670
671 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700672 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800673
Eric Laurentdc462862016-07-19 12:29:53 -0700674 //FIXME: workaround for truncated touch sounds
675 // to be removed when the problem is handled by system UI
676 uint32_t delayMs = 0;
677 uint32_t waitMs = 0;
678 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
679 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
680 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700681 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700682 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
Eric Laurentdc462862016-07-19 12:29:53 -0700683 waitMs = updateCallRouting(newDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700684 }
Eric Laurente552edb2014-03-10 17:42:56 -0700685 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700686 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
687 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
688 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700689 waitMs = setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE),
690 delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700691 }
Eric Laurente552edb2014-03-10 17:42:56 -0700692 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700693 applyStreamVolumes(outputDesc, newDevice, waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700694 }
695 }
696
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800697 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800698 audio_devices_t newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700699 // Force new input selection if the new device can not be reached via current input
Eric Laurentfb66dd92016-01-28 18:32:03 -0800700 if (activeDesc->mProfile->getSupportedDevices().types() &
701 (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
702 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700703 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800704 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700705 }
Eric Laurente552edb2014-03-10 17:42:56 -0700706 }
Eric Laurente552edb2014-03-10 17:42:56 -0700707}
708
Eric Laurente0720872014-03-11 09:30:41 -0700709void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700710{
711 ALOGV("setSystemProperty() property %s, value %s", property, value);
712}
713
714// Find a direct output profile compatible with the parameters passed, even if the input flags do
715// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800716sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700717 audio_devices_t device,
718 uint32_t samplingRate,
719 audio_format_t format,
720 audio_channel_mask_t channelMask,
721 audio_output_flags_t flags)
722{
Eric Laurent861a6282015-05-18 15:40:16 -0700723 // only retain flags that will drive the direct output profile selection
724 // if explicitly requested
725 static const uint32_t kRelevantFlags =
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700726 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
727 AUDIO_OUTPUT_FLAG_VOIP_RX);
Eric Laurent861a6282015-05-18 15:40:16 -0700728 flags =
729 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
730
731 sp<IOProfile> profile;
732
Mikhail Naganovd4120142017-12-06 15:49:22 -0800733 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800734 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent861a6282015-05-18 15:40:16 -0700735 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700736 samplingRate, NULL /*updatedSamplingRate*/,
737 format, NULL /*updatedFormat*/,
738 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700739 flags)) {
740 continue;
741 }
742 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100743 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700744 continue;
745 }
746 // if several profiles are compatible, give priority to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100747 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700748 continue;
749 }
750 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100751 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700752 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700753 }
Eric Laurente552edb2014-03-10 17:42:56 -0700754 }
755 }
Eric Laurent861a6282015-05-18 15:40:16 -0700756 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700757}
758
Eric Laurentf4e63452017-11-06 19:31:46 +0000759audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700760{
Eric Laurent3b73df72014-03-11 09:06:29 -0700761 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700762 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800763
764 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
765 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
766 // format, flags, etc. This may result in some discrepancy for functions that utilize
767 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
768 // and AudioSystem::getOutputSamplingRate().
769
Eric Laurentf4e63452017-11-06 19:31:46 +0000770 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
771 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
Eric Laurente552edb2014-03-10 17:42:56 -0700772
Eric Laurentf4e63452017-11-06 19:31:46 +0000773 ALOGV("getOutput() stream %d selected device %08x, output %d", stream, device, output);
774 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700775}
776
Eric Laurente83b55d2014-11-14 10:06:21 -0800777status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
778 audio_io_handle_t *output,
779 audio_session_t session,
780 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700781 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800782 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200783 audio_output_flags_t *flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700784 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800785 audio_port_handle_t *portId)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700786{
Eric Laurente83b55d2014-11-14 10:06:21 -0800787 audio_attributes_t attributes;
Eric Laurent8fc147b2018-07-22 19:13:55 -0700788 DeviceVector outputDevices;
789 routing_strategy strategy;
790 audio_devices_t device;
Eric Laurent97ac8712018-07-27 18:59:02 -0700791 const audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100792 audio_devices_t msdDevice = getMsdAudioOutDeviceTypes();
Eric Laurent8fc147b2018-07-22 19:13:55 -0700793
Eric Laurent8f42ea12018-08-08 09:08:25 -0700794 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
795 if (*portId != AUDIO_PORT_HANDLE_NONE) {
796 return INVALID_OPERATION;
797 }
798
Eric Laurente83b55d2014-11-14 10:06:21 -0800799 if (attr != NULL) {
800 if (!isValidAttributes(attr)) {
801 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
802 attr->usage, attr->content_type, attr->flags,
803 attr->tags);
804 return BAD_VALUE;
805 }
806 attributes = *attr;
807 } else {
808 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
809 ALOGE("getOutputForAttr(): invalid stream type");
810 return BAD_VALUE;
811 }
812 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700813 }
Eric Laurent20b9ef02016-12-05 11:03:16 -0800814
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700815 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
Eric Laurent97ac8712018-07-27 18:59:02 -0700816 " session %d selectedDeviceId %d",
817 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
818 session, requestedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700819
Eric Laurent97ac8712018-07-27 18:59:02 -0700820 *stream = streamTypefromAttributesInt(&attributes);
821
822 strategy = getStrategyForAttr(&attributes);
823
Scott Randolph7b1fd232018-06-18 15:33:03 -0700824 // First check for explicit routing (eg. setPreferredDevice)
Eric Laurent97ac8712018-07-27 18:59:02 -0700825 if (requestedDeviceId != AUDIO_PORT_HANDLE_NONE) {
826 sp<DeviceDescriptor> deviceDesc =
827 mAvailableOutputDevices.getDeviceFromId(requestedDeviceId);
828 device = deviceDesc->type();
Scott Randolph7b1fd232018-06-18 15:33:03 -0700829 } else {
830 // If no explict route, is there a matching dynamic policy that applies?
831 sp<SwAudioOutputDescriptor> desc;
832 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
833 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
834 if (!audio_has_proportional_frames(config->format)) {
835 return BAD_VALUE;
836 }
837 *stream = streamTypefromAttributesInt(&attributes);
838 *output = desc->mIoHandle;
Eric Laurent97ac8712018-07-27 18:59:02 -0700839 AudioMix *mix = desc->mPolicyMix;
840 sp<DeviceDescriptor> deviceDesc =
841 mAvailableOutputDevices.getDevice(mix->mDeviceType, mix->mDeviceAddress);
842 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Scott Randolph7b1fd232018-06-18 15:33:03 -0700843 ALOGV("getOutputForAttr() returns output %d", *output);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700844 goto exit;
Scott Randolph7b1fd232018-06-18 15:33:03 -0700845 }
846
847 // Virtual sources must always be dynamicaly or explicitly routed
848 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
849 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
850 return BAD_VALUE;
851 }
Eric Laurent97ac8712018-07-27 18:59:02 -0700852 device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700853 }
Scott Randolph7b1fd232018-06-18 15:33:03 -0700854
Eric Laurente83b55d2014-11-14 10:06:21 -0800855 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200856 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -0700857 }
858
Nadav Barb2f18162018-07-18 13:01:53 +0300859 // Set incall music only if device was explicitly set, and fallback to the device which is
860 // chosen by the engine if not.
861 // FIXME: provide a more generic approach which is not device specific and move this back
862 // to getOutputForDevice.
863 if (device == AUDIO_DEVICE_OUT_TELEPHONY_TX &&
864 *stream == AUDIO_STREAM_MUSIC &&
865 audio_is_linear_pcm(config->format) &&
866 isInCall()) {
Eric Laurent97ac8712018-07-27 18:59:02 -0700867 if (requestedDeviceId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +0300868 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
869 } else {
Eric Laurent97ac8712018-07-27 18:59:02 -0700870 // Get the devce type directly from the engine to bypass preferred route logic
Nadav Barb2f18162018-07-18 13:01:53 +0300871 device = mEngine->getDeviceForStrategy(strategy);
872 }
873 }
874
Glenn Kasten49f36ba2017-12-06 13:02:02 -0800875 ALOGV("getOutputForAttr() device 0x%x, sampling rate %d, format %#x, channel mask %#x, "
876 "flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +0200877 device, config->sample_rate, config->format, config->channel_mask, *flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700878
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100879 *output = AUDIO_IO_HANDLE_NONE;
880 if (msdDevice != AUDIO_DEVICE_NONE) {
881 *output = getOutputForDevice(msdDevice, session, *stream, config, flags);
882 if (*output != AUDIO_IO_HANDLE_NONE && setMsdPatch(device) == NO_ERROR) {
883 ALOGV("%s() Using MSD device 0x%x instead of device 0x%x",
884 __func__, msdDevice, device);
885 device = msdDevice;
886 } else {
887 *output = AUDIO_IO_HANDLE_NONE;
888 }
889 }
890 if (*output == AUDIO_IO_HANDLE_NONE) {
891 *output = getOutputForDevice(device, session, *stream, config, flags);
892 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800893 if (*output == AUDIO_IO_HANDLE_NONE) {
894 return INVALID_OPERATION;
895 }
Paul McLeanaa981192015-03-21 09:55:15 -0700896
Eric Laurent8fc147b2018-07-22 19:13:55 -0700897 outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -0700898 *selectedDeviceId = outputDevices.size() > 0 ? outputDevices.itemAt(0)->getId()
899 : AUDIO_PORT_HANDLE_NONE;
900
Eric Laurent8fc147b2018-07-22 19:13:55 -0700901exit:
902 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
903 .format = config->format,
904 .channel_mask = config->channel_mask };
Eric Laurent8f42ea12018-08-08 09:08:25 -0700905 *portId = AudioPort::getNextUniqueId();
906
Eric Laurent8fc147b2018-07-22 19:13:55 -0700907 sp<TrackClientDescriptor> clientDesc =
Eric Laurent97ac8712018-07-27 18:59:02 -0700908 new TrackClientDescriptor(*portId, uid, session, attributes, clientConfig,
909 requestedDeviceId, *stream,
910 getStrategyForAttr(&attributes),
911 *flags);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700912 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Andy Hung39efb7a2018-09-26 15:39:28 -0700913 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700914
915 ALOGV(" getOutputForAttr() returns output %d selectedDeviceId %d for port ID %d",
916 *output, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -0700917
Eric Laurente83b55d2014-11-14 10:06:21 -0800918 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700919}
920
921audio_io_handle_t AudioPolicyManager::getOutputForDevice(
922 audio_devices_t device,
Kevin Rocard169753c2017-03-06 14:18:23 -0800923 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700924 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -0800925 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200926 audio_output_flags_t *flags)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700927{
Andy Hungc88b0642018-04-27 15:42:35 -0700928 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700929 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700930
Eric Laurente552edb2014-03-10 17:42:56 -0700931 // open a direct output if required by specified parameters
932 //force direct flag if offload flag is set: offloading implies a direct output stream
933 // and all common behaviors are driven by checking only the direct flag
934 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +0200935 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
936 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700937 }
Nadav Bar766fb022018-01-07 12:18:03 +0200938 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
939 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -0700940 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800941 // only allow deep buffering for music stream type
942 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +0200943 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700944 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +0200945 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700946 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
947 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +0200948 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800949 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700950 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +0200951 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700952 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Eric Laurentfe231122017-11-17 17:48:06 -0800953 audio_is_linear_pcm(config->format)) {
Nadav Bar766fb022018-01-07 12:18:03 +0200954 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700955 AUDIO_OUTPUT_FLAG_DIRECT);
956 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700957 }
Eric Laurente552edb2014-03-10 17:42:56 -0700958
Nadav Bar766fb022018-01-07 12:18:03 +0200959
Eric Laurentb732cf52014-09-24 19:08:21 -0700960 sp<IOProfile> profile;
961
962 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700963 // and not explicitly requested
Nadav Bar766fb022018-01-07 12:18:03 +0200964 if (((*flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Eric Laurentfe231122017-11-17 17:48:06 -0800965 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
966 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
Eric Laurentb732cf52014-09-24 19:08:21 -0700967 goto non_direct_output;
968 }
969
Andy Hung2ddee192015-12-18 17:34:44 -0800970 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
971 // This prevents creating an offloaded track and tearing it down immediately after start
972 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700973 // FIXME: We should check the audio session here but we do not have it in this context.
974 // This may prevent offloading in rare situations where effects are left active by apps
975 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700976
Nadav Bar766fb022018-01-07 12:18:03 +0200977 if (((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800978 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700979 profile = getProfileForDirectOutput(device,
Eric Laurentfe231122017-11-17 17:48:06 -0800980 config->sample_rate,
981 config->format,
982 config->channel_mask,
Nadav Bar766fb022018-01-07 12:18:03 +0200983 (audio_output_flags_t)*flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700984 }
985
Eric Laurent1c333e22014-05-20 10:48:17 -0700986 if (profile != 0) {
Andy Hungc88b0642018-04-27 15:42:35 -0700987 // exclusive outputs for MMAP and Offload are enforced by different session ids.
988 for (size_t i = 0; i < mOutputs.size(); i++) {
989 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
990 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
991 // reuse direct output if currently open by the same client
992 // and configured with same parameters
993 if ((config->sample_rate == desc->mSamplingRate) &&
Andy Hung5659ed52018-04-30 10:31:26 -0700994 (config->format == desc->mFormat) &&
Andy Hungc88b0642018-04-27 15:42:35 -0700995 (config->channel_mask == desc->mChannelMask) &&
996 (session == desc->mDirectClientSession)) {
997 desc->mDirectOpenCount++;
998 ALOGI("getOutputForDevice() reusing direct output %d for session %d",
999 mOutputs.keyAt(i), session);
1000 return mOutputs.keyAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001001 }
1002 }
1003 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08001004
1005 if (!profile->canOpenNewIo()) {
1006 goto non_direct_output;
Eric Laurente552edb2014-03-10 17:42:56 -07001007 }
Eric Laurent861a6282015-05-18 15:40:16 -07001008
Eric Laurent3974e3b2017-12-07 17:58:43 -08001009 sp<SwAudioOutputDescriptor> outputDesc =
1010 new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurent53b810e2017-12-10 17:25:10 -08001011
Mikhail Naganov708e0382018-05-30 09:53:04 -07001012 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -08001013 String8 address = outputDevices.size() > 0 ? outputDevices.itemAt(0)->mAddress
1014 : String8("");
1015
Dean Wheatley3023b382018-08-09 07:42:40 +10001016 // MSD patch may be using the only output stream that can service this request. Release
1017 // MSD patch to prioritize this request over any active output on MSD.
1018 AudioPatchCollection msdPatches = getMsdPatches();
1019 for (size_t i = 0; i < msdPatches.size(); i++) {
1020 const auto& patch = msdPatches[i];
1021 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1022 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1023 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
1024 (sink->ext.device.type & device) != AUDIO_DEVICE_NONE &&
1025 (address.isEmpty() || strncmp(sink->ext.device.address, address.string(),
1026 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
1027 releaseAudioPatch(patch->mHandle, mUidCached);
1028 break;
1029 }
1030 }
1031 }
1032
Nadav Bar766fb022018-01-07 12:18:03 +02001033 status = outputDesc->open(config, device, address, stream, *flags, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07001034
1035 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001036 if (status != NO_ERROR ||
Eric Laurentfe231122017-11-17 17:48:06 -08001037 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
Andy Hung5659ed52018-04-30 10:31:26 -07001038 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->mFormat) ||
Eric Laurentfe231122017-11-17 17:48:06 -08001039 (config->channel_mask != 0 && config->channel_mask != outputDesc->mChannelMask)) {
1040 ALOGV("getOutputForDevice() failed opening direct output: output %d sample rate %d %d,"
1041 "format %d %d, channel mask %04x %04x", output, config->sample_rate,
1042 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
1043 config->channel_mask, outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001044 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001045 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07001046 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001047 // fall back to mixer output if possible when the direct output could not be open
Eric Laurentfe231122017-11-17 17:48:06 -08001048 if (audio_is_linear_pcm(config->format) &&
1049 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -08001050 goto non_direct_output;
1051 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001052 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001053 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001054 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -08001055 outputDesc->mDirectClientSession = session;
1056
Eric Laurente552edb2014-03-10 17:42:56 -07001057 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001058 mPreviousOutputs = mOutputs;
Eric Laurentf4e63452017-11-06 19:31:46 +00001059 ALOGV("getOutputForDevice() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001060 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001061 return output;
1062 }
1063
Eric Laurentb732cf52014-09-24 19:08:21 -07001064non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001065
1066 // A request for HW A/V sync cannot fallback to a mixed output because time
1067 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001068 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001069 return AUDIO_IO_HANDLE_NONE;
1070 }
1071
Eric Laurente552edb2014-03-10 17:42:56 -07001072 // ignoring channel mask due to downmix capability in mixer
1073
1074 // open a non direct output
1075
1076 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001077 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001078 // get which output is suitable for the specified stream. The actual
1079 // routing change will happen when startOutput() will be called
1080 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1081
Eric Laurent8838a382014-09-08 16:44:28 -07001082 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001083 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1084 output = selectOutput(outputs, *flags, config->format);
Eric Laurente552edb2014-03-10 17:42:56 -07001085 }
Eric Laurentf4e63452017-11-06 19:31:46 +00001086 ALOGW_IF((output == 0), "getOutputForDevice() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001087 "sampling rate %d, format %#x, channels %#x, flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +02001088 stream, config->sample_rate, config->format, config->channel_mask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001089
Eric Laurente552edb2014-03-10 17:42:56 -07001090 return output;
1091}
1092
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001093sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
1094 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1095 if (msdModule != 0) {
1096 DeviceVector msdInputDevices = mAvailableInputDevices.getDevicesFromHwModule(
1097 msdModule->getHandle());
1098 if (!msdInputDevices.isEmpty()) return msdInputDevices.itemAt(0);
1099 }
1100 return 0;
1101}
1102
1103audio_devices_t AudioPolicyManager::getMsdAudioOutDeviceTypes() const {
1104 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1105 if (msdModule != 0) {
1106 return mAvailableOutputDevices.getDeviceTypesFromHwModule(msdModule->getHandle());
1107 }
1108 return AUDIO_DEVICE_NONE;
1109}
1110
1111const AudioPatchCollection AudioPolicyManager::getMsdPatches() const {
1112 AudioPatchCollection msdPatches;
1113 audio_module_handle_t msdModuleHandle = mHwModules.getModuleFromName(
1114 AUDIO_HARDWARE_MODULE_ID_MSD)->getHandle();
1115 if (msdModuleHandle == AUDIO_MODULE_HANDLE_NONE) return msdPatches;
1116 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1117 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1118 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1119 const struct audio_port_config *source = &patch->mPatch.sources[j];
1120 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1121 source->ext.device.hw_module == msdModuleHandle) {
1122 msdPatches.addAudioPatch(patch->mHandle, patch);
1123 }
1124 }
1125 }
1126 return msdPatches;
1127}
1128
1129status_t AudioPolicyManager::getBestMsdAudioProfileFor(audio_devices_t outputDevice,
1130 bool hwAvSync, audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1131{
1132 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1133 if (msdModule == nullptr) {
1134 ALOGE("%s() unable to get MSD module", __func__);
1135 return NO_INIT;
1136 }
1137 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(outputDevice);
1138 if (deviceModule == nullptr) {
1139 ALOGE("%s() unable to get module for %#x", __func__, outputDevice);
1140 return NO_INIT;
1141 }
1142 const InputProfileCollection &inputProfiles = msdModule->getInputProfiles();
1143 if (inputProfiles.isEmpty()) {
1144 ALOGE("%s() no input profiles for MSD module", __func__);
1145 return NO_INIT;
1146 }
1147 const OutputProfileCollection &outputProfiles = deviceModule->getOutputProfiles();
1148 if (outputProfiles.isEmpty()) {
1149 ALOGE("%s() no output profiles for device %#x", __func__, outputDevice);
1150 return NO_INIT;
1151 }
1152 AudioProfileVector msdProfiles;
1153 // Each IOProfile represents a MixPort from audio_policy_configuration.xml
1154 for (const auto &inProfile : inputProfiles) {
1155 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0)) {
1156 msdProfiles.appendVector(inProfile->getAudioProfiles());
1157 }
1158 }
1159 AudioProfileVector deviceProfiles;
1160 for (const auto &outProfile : outputProfiles) {
1161 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0)) {
1162 deviceProfiles.appendVector(outProfile->getAudioProfiles());
1163 }
1164 }
1165 struct audio_config_base bestSinkConfig;
1166 status_t result = msdProfiles.findBestMatchingOutputConfig(deviceProfiles,
1167 compressedFormatsOrder, surroundChannelMasksOrder, true /*preferHigherSamplingRates*/,
1168 &bestSinkConfig);
1169 if (result != NO_ERROR) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001170 ALOGD("%s() no matching profiles found for device: %#x, hwAvSync: %d",
1171 __func__, outputDevice, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001172 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001173 }
1174 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1175 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1176 sinkConfig->format = bestSinkConfig.format;
1177 // For encoded streams force direct flag to prevent downstream mixing.
1178 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1179 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
1180 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1181 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1182 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1183 sourceConfig->format = bestSinkConfig.format;
1184 // Copy input stream directly without any processing (e.g. resampling).
1185 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1186 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1187 if (hwAvSync) {
1188 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1189 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1190 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1191 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1192 }
1193 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1194 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1195 sinkConfig->config_mask |= config_mask;
1196 sourceConfig->config_mask |= config_mask;
1197 return NO_ERROR;
1198}
1199
1200PatchBuilder AudioPolicyManager::buildMsdPatch(audio_devices_t outputDevice) const
1201{
1202 PatchBuilder patchBuilder;
1203 patchBuilder.addSource(getMsdAudioInDevice()).
1204 addSink(findDevice(mAvailableOutputDevices, outputDevice));
1205 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1206 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
1207 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1208 // For now, we just forcefully try with HwAvSync first.
1209 status_t res = getBestMsdAudioProfileFor(outputDevice, true /*hwAvSync*/,
1210 &sourceConfig, &sinkConfig) == NO_ERROR ? NO_ERROR :
1211 getBestMsdAudioProfileFor(
1212 outputDevice, false /*hwAvSync*/, &sourceConfig, &sinkConfig);
1213 if (res == NO_ERROR) {
1214 // Found a matching profile for encoded audio. Re-create PatchBuilder with this config.
1215 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1216 }
1217 ALOGV("%s() no matching profile found. Fall through to default PCM patch"
1218 " supporting PCM format conversion.", __func__);
1219 return patchBuilder;
1220}
1221
1222status_t AudioPolicyManager::setMsdPatch(audio_devices_t outputDevice) {
1223 ALOGV("%s() for outputDevice %#x", __func__, outputDevice);
1224 if (outputDevice == AUDIO_DEVICE_NONE) {
1225 // Use media strategy for unspecified output device. This should only
1226 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1227 // therefore invalidate explicit routing requests.
1228 outputDevice = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
1229 }
1230 PatchBuilder patchBuilder = buildMsdPatch(outputDevice);
1231 const struct audio_patch* patch = patchBuilder.patch();
1232 const AudioPatchCollection msdPatches = getMsdPatches();
1233 if (!msdPatches.isEmpty()) {
1234 LOG_ALWAYS_FATAL_IF(msdPatches.size() > 1,
1235 "The current MSD prototype only supports one output patch");
1236 sp<AudioPatch> currentPatch = msdPatches.valueAt(0);
1237 if (audio_patches_are_equal(&currentPatch->mPatch, patch)) {
1238 return NO_ERROR;
1239 }
1240 releaseAudioPatch(currentPatch->mHandle, mUidCached);
1241 }
1242 status_t status = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1243 patch, 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1244 ALOGE_IF(status != NO_ERROR, "%s() error %d creating MSD audio patch", __func__, status);
1245 ALOGI_IF(status == NO_ERROR, "%s() Patch created from MSD_IN to "
1246 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__, outputDevice,
1247 patch->sources[0].format, patch->sources[0].channel_mask, patch->sources[0].sample_rate);
1248 return status;
1249}
1250
Eric Laurente0720872014-03-11 09:30:41 -07001251audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001252 audio_output_flags_t flags,
1253 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001254{
1255 // select one output among several that provide a path to a particular device or set of
1256 // devices (the list was previously build by getOutputsForDevice()).
1257 // The priority is as follows:
1258 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001259 // 2: the output with the bit depth the closest to the requested one
1260 // 3: the primary output
1261 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001262
1263 if (outputs.size() == 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001264 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001265 }
1266 if (outputs.size() == 1) {
1267 return outputs[0];
1268 }
1269
1270 int maxCommonFlags = 0;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001271 audio_io_handle_t outputForFlags = AUDIO_IO_HANDLE_NONE;
1272 audio_io_handle_t outputForPrimary = AUDIO_IO_HANDLE_NONE;
1273 audio_io_handle_t outputForFormat = AUDIO_IO_HANDLE_NONE;
Eric Laurente6930022016-02-11 10:20:40 -08001274 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1275 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001276
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001277 for (audio_io_handle_t output : outputs) {
1278 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001279 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001280 // if a valid format is specified, skip output if not compatible
1281 if (format != AUDIO_FORMAT_INVALID) {
1282 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Andy Hung5659ed52018-04-30 10:31:26 -07001283 if (format != outputDesc->mFormat) {
Eric Laurent8838a382014-09-08 16:44:28 -07001284 continue;
1285 }
1286 } else if (!audio_is_linear_pcm(format)) {
1287 continue;
1288 }
Eric Laurente6930022016-02-11 10:20:40 -08001289 if (AudioPort::isBetterFormatMatch(
1290 outputDesc->mFormat, bestFormat, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001291 outputForFormat = output;
Eric Laurente6930022016-02-11 10:20:40 -08001292 bestFormat = outputDesc->mFormat;
1293 }
Eric Laurent8838a382014-09-08 16:44:28 -07001294 }
1295
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001296 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001297 if (commonFlags >= maxCommonFlags) {
1298 if (commonFlags == maxCommonFlags) {
Andy Hungc9901522017-11-10 20:07:54 -08001299 if (format != AUDIO_FORMAT_INVALID
1300 && AudioPort::isBetterFormatMatch(
1301 outputDesc->mFormat, bestFormatForFlags, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001302 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001303 bestFormatForFlags = outputDesc->mFormat;
1304 }
1305 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001306 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001307 maxCommonFlags = commonFlags;
1308 bestFormatForFlags = outputDesc->mFormat;
1309 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001310 ALOGV("selectOutput() commonFlags for output %d, %04x", output, commonFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001311 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001312 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001313 outputForPrimary = output;
Eric Laurente552edb2014-03-10 17:42:56 -07001314 }
1315 }
1316 }
1317
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001318 if (outputForFlags != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001319 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001320 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001321 if (outputForFormat != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001322 return outputForFormat;
1323 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001324 if (outputForPrimary != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001325 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001326 }
1327
1328 return outputs[0];
1329}
1330
Eric Laurent8fc147b2018-07-22 19:13:55 -07001331status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001332{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001333 ALOGV("%s portId %d", __FUNCTION__, portId);
1334
1335 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1336 if (outputDesc == 0) {
1337 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001338 return BAD_VALUE;
1339 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001340 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001341
Eric Laurent8fc147b2018-07-22 19:13:55 -07001342 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001343 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001344
Eric Laurent733ce942017-12-07 12:18:25 -08001345 status_t status = outputDesc->start();
1346 if (status != NO_ERROR) {
1347 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001348 }
1349
Eric Laurent97ac8712018-07-27 18:59:02 -07001350 uint32_t delayMs;
1351 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001352
1353 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001354 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001355 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001356 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001357 if (delayMs != 0) {
1358 usleep(delayMs * 1000);
1359 }
1360
1361 return status;
1362}
1363
Eric Laurent97ac8712018-07-27 18:59:02 -07001364status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1365 const sp<TrackClientDescriptor>& client,
1366 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001367{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001368 // cannot start playback of STREAM_TTS if any other output is being used
1369 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001370
1371 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001372 audio_stream_type_t stream = client->stream();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001373 if (stream == AUDIO_STREAM_TTS) {
1374 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001375 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001376 return INVALID_OPERATION;
1377 } else {
1378 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1379 }
1380 } else {
1381 // some playback other than beacon starts
1382 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1383 }
1384
Eric Laurent77305a62016-07-25 16:39:22 -07001385 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001386 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001387 bool force = !outputDesc->isActive() &&
1388 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001389
Eric Laurent97ac8712018-07-27 18:59:02 -07001390 audio_devices_t device = AUDIO_DEVICE_NONE;
1391 AudioMix *policyMix = NULL;
1392 const char *address = NULL;
1393 if (outputDesc->mPolicyMix != NULL) {
1394 policyMix = outputDesc->mPolicyMix;
1395 address = policyMix->mDeviceAddress.string();
1396 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1397 device = policyMix->mDeviceType;
1398 } else {
1399 device = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1400 }
1401 }
1402
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001403 // requiresMuteCheck is false when we can bypass mute strategy.
1404 // It covers a common case when there is no materially active audio
1405 // and muting would result in unnecessary delay and dropped audio.
1406 const uint32_t outputLatencyMs = outputDesc->latency();
1407 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1408
Eric Laurente552edb2014-03-10 17:42:56 -07001409 // increment usage count for this stream on the requested output:
1410 // NOTE that the usage count is the same for duplicated output and hardware output which is
1411 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001412 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001413
1414 if (client->hasPreferredDevice(true)) {
1415 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
1416 if (device != outputDesc->device()) {
1417 checkStrategyRoute(getStrategy(stream), outputDesc->mIoHandle);
1418 }
1419 }
Eric Laurente552edb2014-03-10 17:42:56 -07001420
Eric Laurent36829f92017-04-07 19:04:42 -07001421 if (stream == AUDIO_STREAM_MUSIC) {
1422 selectOutputForMusicEffects();
1423 }
1424
Eric Laurent592dd7b2018-08-05 18:58:48 -07001425 if (outputDesc->streamActiveCount(stream) == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001426 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001427 if (device == AUDIO_DEVICE_NONE) {
1428 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001429 }
Eric Laurent36829f92017-04-07 19:04:42 -07001430
Eric Laurente552edb2014-03-10 17:42:56 -07001431 routing_strategy strategy = getStrategy(stream);
1432 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001433 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1434 (beaconMuteLatency > 0);
1435 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001436 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001437 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001438 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001439 // An output has a shared device if
1440 // - managed by the same hw module
1441 // - supports the currently selected device
1442 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
1443 && (desc->supportedDevices() & device) != AUDIO_DEVICE_NONE;
1444
Eric Laurent77305a62016-07-25 16:39:22 -07001445 // force a device change if any other output is:
1446 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001447 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001448 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001449 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001450 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001451 // change the device currently selected by the other output.
1452 if (sharedDevice &&
Eric Laurent77305a62016-07-25 16:39:22 -07001453 desc->device() != device &&
Eric Laurent77305a62016-07-25 16:39:22 -07001454 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001455 force = true;
1456 }
1457 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001458 // a notification so that audio focus effect can propagate, or that a mute/unmute
1459 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001460 const uint32_t latencyMs = desc->latency();
1461 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1462
1463 if (shouldWait && isActive && (waitMs < latencyMs)) {
1464 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001465 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001466
1467 // Require mute check if another output is on a shared device
1468 // and currently active to have proper drain and avoid pops.
1469 // Note restoring AudioTracks onto this output needs to invoke
1470 // a volume ramp if there is no mute.
1471 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001472 }
1473 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001474
1475 const uint32_t muteWaitMs =
1476 setOutputDevice(outputDesc, device, force, 0, NULL, address, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001477
Eric Laurente552edb2014-03-10 17:42:56 -07001478 // apply volume rules for current stream and device if necessary
1479 checkAndSetVolume(stream,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001480 mVolumeCurves->getVolumeIndex(stream, outputDesc->device()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001481 outputDesc,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001482 outputDesc->device());
Eric Laurente552edb2014-03-10 17:42:56 -07001483
1484 // update the outputs if starting an output with a stream that can affect notification
1485 // routing
1486 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001487
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001488 // force reevaluating accessibility routing when ringtone or alarm starts
1489 if (strategy == STRATEGY_SONIFICATION) {
1490 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1491 }
Eric Laurentdc462862016-07-19 12:29:53 -07001492
1493 if (waitMs > muteWaitMs) {
1494 *delayMs = waitMs - muteWaitMs;
1495 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001496
1497 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1498 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1499 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1500 // change occurs after the MixerThread starts and causes a stream volume
1501 // glitch.
1502 //
1503 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001504 }
Eric Laurentdc462862016-07-19 12:29:53 -07001505
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001506 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1507 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1508 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1509 }
1510
Eric Laurent97ac8712018-07-27 18:59:02 -07001511 // Automatically enable the remote submix input when output is started on a re routing mix
1512 // of type MIX_TYPE_RECORDERS
1513 if (audio_is_remote_submix_device(device) && policyMix != NULL &&
1514 policyMix->mMixType == MIX_TYPE_RECORDERS) {
1515 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1516 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1517 address,
1518 "remote-submix");
1519 }
1520
Eric Laurente552edb2014-03-10 17:42:56 -07001521 return NO_ERROR;
1522}
1523
Eric Laurent8fc147b2018-07-22 19:13:55 -07001524status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001525{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001526 ALOGV("%s portId %d", __FUNCTION__, portId);
1527
1528 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1529 if (outputDesc == 0) {
1530 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001531 return BAD_VALUE;
1532 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001533 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001534
Eric Laurent97ac8712018-07-27 18:59:02 -07001535 ALOGV("stopOutput() output %d, stream %d, session %d",
1536 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07001537
Eric Laurent97ac8712018-07-27 18:59:02 -07001538 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08001539
Eric Laurent733ce942017-12-07 12:18:25 -08001540 if (status == NO_ERROR ) {
1541 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001542 }
1543 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001544}
1545
Eric Laurent97ac8712018-07-27 18:59:02 -07001546status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1547 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07001548{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001549 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07001550 audio_stream_type_t stream = client->stream();
1551
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001552 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1553
Eric Laurent592dd7b2018-08-05 18:58:48 -07001554 if (outputDesc->streamActiveCount(stream) > 0) {
1555 if (outputDesc->streamActiveCount(stream) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001556 // Automatically disable the remote submix input when output is stopped on a
1557 // re routing mix of type MIX_TYPE_RECORDERS
1558 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1559 outputDesc->mPolicyMix != NULL &&
1560 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1561 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1562 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1563 outputDesc->mPolicyMix->mDeviceAddress,
1564 "remote-submix");
1565 }
1566 }
1567 bool forceDeviceUpdate = false;
1568 if (client->hasPreferredDevice(true)) {
1569 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1570 forceDeviceUpdate = true;
1571 }
1572
Eric Laurente552edb2014-03-10 17:42:56 -07001573 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07001574 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07001575
Eric Laurente552edb2014-03-10 17:42:56 -07001576 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001577 if (outputDesc->streamActiveCount(stream) == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001578 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001579 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001580 // delay the device switch by twice the latency because stopOutput() is executed when
1581 // the track stop() command is received and at that time the audio track buffer can
1582 // still contain data that needs to be drained. The latency only covers the audio HAL
1583 // and kernel buffers. Also the latency does not always include additional delay in the
1584 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001585 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001586
1587 // force restoring the device selection on other active outputs if it differs from the
1588 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001589 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001590 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001591 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001592 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001593 desc->isActive() &&
1594 outputDesc->sharesHwModuleWith(desc) &&
1595 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001596 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1597 bool force = desc->device() != newDevice2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001598
Eric Laurentc75307b2015-03-17 15:29:32 -07001599 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001600 newDevice2,
1601 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001602 delayMs);
1603 // re-apply device specific volume if not done by setOutputDevice()
1604 if (!force) {
1605 applyStreamVolumes(desc, newDevice2, delayMs);
1606 }
Eric Laurente552edb2014-03-10 17:42:56 -07001607 }
1608 }
1609 // update the outputs if stopping one with a stream that can affect notification routing
1610 handleNotificationRoutingForStream(stream);
1611 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001612
1613 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1614 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1615 setStrategyMute(STRATEGY_SONIFICATION, false, outputDesc);
1616 }
1617
Eric Laurent36829f92017-04-07 19:04:42 -07001618 if (stream == AUDIO_STREAM_MUSIC) {
1619 selectOutputForMusicEffects();
1620 }
Eric Laurente552edb2014-03-10 17:42:56 -07001621 return NO_ERROR;
1622 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001623 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001624 return INVALID_OPERATION;
1625 }
1626}
1627
Eric Laurent8fc147b2018-07-22 19:13:55 -07001628void AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001629{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001630 ALOGV("%s portId %d", __FUNCTION__, portId);
1631
1632 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1633 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07001634 // If an output descriptor is closed due to a device routing change,
1635 // then there are race conditions with releaseOutput from tracks
1636 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
1637 // destroyed shortly thereafter.
1638 //
1639 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07001640 ALOGW("releaseOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001641 return;
1642 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001643
1644 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001645
Eric Laurent8fc147b2018-07-22 19:13:55 -07001646 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1647 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001648 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07001649 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001650 return;
1651 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001652 if (--outputDesc->mDirectOpenCount == 0) {
1653 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07001654 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001655 }
1656 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001657 // stopOutput() needs to be successfully called before releaseOutput()
1658 // otherwise there may be inaccurate stream reference counts.
1659 // This is checked in outputDesc->removeClient below.
1660 outputDesc->removeClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001661}
1662
Eric Laurentcaf7f482014-11-25 17:50:47 -08001663status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1664 audio_io_handle_t *input,
1665 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001666 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001667 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001668 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001669 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001670 input_type_t *inputType,
1671 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001672{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001673 ALOGV("getInputForAttr() source %d, sampling rate %d, format %#x, channel mask %#x,"
Eric Laurentcaf7f482014-11-25 17:50:47 -08001674 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001675 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001676
Eric Laurentad2e7b92017-09-14 20:06:42 -07001677 status_t status = NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -08001678 // handle legacy remote submix case where the address was not always specified
1679 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001680 audio_source_t halInputSource;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001681 audio_source_t inputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001682 AudioMix *policyMix = NULL;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001683 DeviceVector inputDevices;
Eric Laurent8fc147b2018-07-22 19:13:55 -07001684 sp<AudioInputDescriptor> inputDesc;
1685 sp<RecordClientDescriptor> clientDesc;
1686 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001687 bool isSoundTrigger;
1688 audio_devices_t device;
1689
1690 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1691 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1692 return INVALID_OPERATION;
1693 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001694
Eric Laurentfe231122017-11-17 17:48:06 -08001695 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1696 inputSource = AUDIO_SOURCE_MIC;
1697 }
1698
Paul McLean466dc8e2015-04-17 13:15:36 -06001699 // Explicit routing?
1700 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -07001701 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
jiabinc0c831a2018-01-29 17:55:15 -08001702 deviceDesc = mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001703 }
Paul McLean466dc8e2015-04-17 13:15:36 -06001704
Eric Laurentad2e7b92017-09-14 20:06:42 -07001705 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1706 // possible
1707 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1708 *input != AUDIO_IO_HANDLE_NONE) {
1709 ssize_t index = mInputs.indexOfKey(*input);
1710 if (index < 0) {
1711 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1712 status = BAD_VALUE;
1713 goto error;
1714 }
1715 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001716 RecordClientVector clients = inputDesc->getClientsForSession(session);
1717 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001718 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1719 status = BAD_VALUE;
1720 goto error;
1721 }
1722 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1723 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001724 // corresponds to a new client and is only permitted from the same UID.
1725 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07001726 if (clients.size() > 1) {
1727 for (const auto& client : clients) {
1728 // The client map is ordered by key values (portId) and portIds are allocated
1729 // incrementaly. So the first client in this list is the one opened by audio flinger
1730 // when the mmap stream is created and should be ignored as it does not correspond
1731 // to an actual client
1732 if (client == *clients.cbegin()) {
1733 continue;
1734 }
1735 if (uid != client->uid() && !client->isSilenced()) {
1736 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
1737 uid, client->portId(), client->uid());
1738 status = INVALID_OPERATION;
1739 goto error;
1740 }
Eric Laurent331679c2018-04-16 17:03:16 -07001741 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001742 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001743 *inputType = API_INPUT_LEGACY;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001744 device = inputDesc->mDevice;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001745
Eric Laurent8f42ea12018-08-08 09:08:25 -07001746 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001747 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001748 }
1749
1750 *input = AUDIO_IO_HANDLE_NONE;
1751 *inputType = API_INPUT_INVALID;
1752
Eric Laurentad2e7b92017-09-14 20:06:42 -07001753 halInputSource = inputSource;
1754
Eric Laurentc447ded2015-01-06 08:47:05 -08001755 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001756 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001757 status = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
1758 if (status != NO_ERROR) {
1759 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001760 }
1761 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001762 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1763 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001764 } else {
Eric Laurent97ac8712018-07-27 18:59:02 -07001765 if (deviceDesc != 0) {
1766 device = deviceDesc->type();
1767 } else {
1768 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
1769 }
Eric Laurent275e8e92014-11-30 15:14:47 -08001770 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001771 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001772 status = BAD_VALUE;
1773 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001774 }
Eric Laurentc722f302014-12-10 11:21:49 -08001775 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001776 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001777 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1778 // there is an external policy, but this input is attached to a mix of recorders,
1779 // meaning it receives audio injected into the framework, so the recorder doesn't
1780 // know about it and is therefore considered "legacy"
1781 *inputType = API_INPUT_LEGACY;
1782 } else {
1783 // recording a mix of players defined by an external policy, we're rerouting for
1784 // an external policy
1785 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1786 }
Eric Laurentc722f302014-12-10 11:21:49 -08001787 } else if (audio_is_remote_submix_device(device)) {
1788 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001789 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001790 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1791 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001792 } else {
1793 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001794 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001795
Eric Laurent599c7582015-12-07 18:05:55 -08001796 }
1797
Eric Laurent8f42ea12018-08-08 09:08:25 -07001798 *input = getInputForDevice(device, address, session, inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001799 config, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001800 policyMix);
1801 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001802 status = INVALID_OPERATION;
1803 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001804 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001805
Eric Laurent8f42ea12018-08-08 09:08:25 -07001806exit:
1807
Mikhail Naganov708e0382018-05-30 09:53:04 -07001808 inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -07001809 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
Eric Laurent8f42ea12018-08-08 09:08:25 -07001810 : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07001811
Eric Laurent8f42ea12018-08-08 09:08:25 -07001812 isSoundTrigger = inputSource == AUDIO_SOURCE_HOTWORD &&
1813 mSoundTriggerSessions.indexOfKey(session) > 0;
1814 *portId = AudioPort::getNextUniqueId();
1815
Eric Laurent8fc147b2018-07-22 19:13:55 -07001816 clientDesc = new RecordClientDescriptor(*portId, uid, session,
Eric Laurent8f42ea12018-08-08 09:08:25 -07001817 *attr, *config, requestedDeviceId,
1818 inputSource,flags, isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001819 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07001820 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001821
1822 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
1823 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001824
Eric Laurent599c7582015-12-07 18:05:55 -08001825 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001826
1827error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07001828 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001829}
1830
1831
1832audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1833 String8 address,
1834 audio_session_t session,
Eric Laurent599c7582015-12-07 18:05:55 -08001835 audio_source_t inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001836 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08001837 audio_input_flags_t flags,
1838 AudioMix *policyMix)
1839{
1840 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1841 audio_source_t halInputSource = inputSource;
1842 bool isSoundTrigger = false;
1843
1844 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1845 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1846 if (index >= 0) {
1847 input = mSoundTriggerSessions.valueFor(session);
1848 isSoundTrigger = true;
1849 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1850 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1851 } else {
1852 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001853 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001854 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08001855 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001856 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001857 }
1858
Andy Hungf129b032015-04-07 13:45:50 -07001859 // find a compatible input profile (not necessarily identical in parameters)
1860 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08001861 // sampling rate and flags may be updated by getInputProfile
1862 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
1863 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07001864 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08001865 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07001866 audio_input_flags_t profileFlags = flags;
1867 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07001868 profileFormat = config->format; // reset each time through loop, in case it is updated
Eric Laurent275e8e92014-11-30 15:14:47 -08001869 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001870 profileSamplingRate, profileFormat, profileChannelMask,
1871 profileFlags);
1872 if (profile != 0) {
1873 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001874 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1875 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001876 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1877 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1878 } else { // fail
Glenn Kastenfaa10a62017-05-25 15:52:05 -07001879 ALOGW("getInputForDevice() could not find profile for device 0x%X, "
Eric Laurentfe231122017-11-17 17:48:06 -08001880 "sampling rate %u, format %#x, channel mask 0x%X, flags %#x",
1881 device, config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001882 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001883 }
Eric Laurente552edb2014-03-10 17:42:56 -07001884 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001885 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08001886 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08001887 if (samplingRate == 0) {
1888 samplingRate = profileSamplingRate;
1889 }
Eric Laurente552edb2014-03-10 17:42:56 -07001890
Eric Laurent322b4d22015-04-03 15:57:54 -07001891 if (profile->getModuleHandle() == 0) {
1892 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001893 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001894 }
1895
Eric Laurent3974e3b2017-12-07 17:58:43 -08001896 if (!profile->canOpenNewIo()) {
1897 return AUDIO_IO_HANDLE_NONE;
1898 }
1899
Eric Laurentfe231122017-11-17 17:48:06 -08001900 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001901
Eric Laurentfe231122017-11-17 17:48:06 -08001902 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
1903 lConfig.sample_rate = profileSamplingRate;
1904 lConfig.channel_mask = profileChannelMask;
1905 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07001906
Eric Laurent53b810e2017-12-10 17:25:10 -08001907 if (address == "") {
Mikhail Naganov708e0382018-05-30 09:53:04 -07001908 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -08001909 // the inputs vector must be of size >= 1, but we don't want to crash here
1910 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress : String8("");
1911 }
1912
Eric Laurentfe231122017-11-17 17:48:06 -08001913 status_t status = inputDesc->open(&lConfig, device, address,
1914 halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001915
1916 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001917 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08001918 (profileSamplingRate != lConfig.sample_rate) ||
1919 !audio_formats_match(profileFormat, lConfig.format) ||
1920 (profileChannelMask != lConfig.channel_mask)) {
1921 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001922 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08001923 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001924 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001925 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07001926 }
Eric Laurent599c7582015-12-07 18:05:55 -08001927 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001928 }
1929
Eric Laurentc722f302014-12-10 11:21:49 -08001930 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001931
Eric Laurent599c7582015-12-07 18:05:55 -08001932 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001933 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001934
Eric Laurent599c7582015-12-07 18:05:55 -08001935 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001936}
1937
Eric Laurentbb948092017-01-23 18:33:30 -08001938//static
1939bool AudioPolicyManager::isConcurrentSource(audio_source_t source)
1940{
1941 return (source == AUDIO_SOURCE_HOTWORD) ||
1942 (source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
1943 (source == AUDIO_SOURCE_FM_TUNER);
1944}
1945
Chris Thornton2b864642017-06-27 21:26:07 -07001946// FIXME: remove when concurrent capture is ready. This is a hack to work around bug b/63083537.
1947bool AudioPolicyManager::soundTriggerSupportsConcurrentCapture() {
1948 if (!mHasComputedSoundTriggerSupportsConcurrentCapture) {
1949 bool soundTriggerSupportsConcurrentCapture = false;
1950 unsigned int numModules = 0;
1951 struct sound_trigger_module_descriptor* nModules = NULL;
1952
1953 status_t status = SoundTrigger::listModules(nModules, &numModules);
1954 if (status == NO_ERROR && numModules != 0) {
1955 nModules = (struct sound_trigger_module_descriptor*) calloc(
1956 numModules, sizeof(struct sound_trigger_module_descriptor));
1957 if (nModules == NULL) {
1958 // We failed to malloc the buffer, so just say no for now, and hope that we have more
1959 // ram the next time this function is called.
1960 ALOGE("Failed to allocate buffer for module descriptors");
1961 return false;
1962 }
1963
1964 status = SoundTrigger::listModules(nModules, &numModules);
1965 if (status == NO_ERROR) {
1966 soundTriggerSupportsConcurrentCapture = true;
1967 for (size_t i = 0; i < numModules; ++i) {
1968 soundTriggerSupportsConcurrentCapture &=
1969 nModules[i].properties.concurrent_capture;
1970 }
1971 }
1972 free(nModules);
1973 }
1974 mSoundTriggerSupportsConcurrentCapture = soundTriggerSupportsConcurrentCapture;
1975 mHasComputedSoundTriggerSupportsConcurrentCapture = true;
1976 }
1977 return mSoundTriggerSupportsConcurrentCapture;
1978}
1979
Eric Laurentfb66dd92016-01-28 18:32:03 -08001980
Eric Laurent8fc147b2018-07-22 19:13:55 -07001981status_t AudioPolicyManager::startInput(audio_port_handle_t portId,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001982 bool silenced,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001983 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07001984{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001985 *concurrency = API_INPUT_CONCURRENCY_NONE;
1986
1987 ALOGV("%s portId %d", __FUNCTION__, portId);
1988
1989 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
1990 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07001991 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001992 return BAD_VALUE;
1993 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001994 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07001995 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001996 if (client->active()) {
1997 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
1998 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07001999 }
2000
Eric Laurent8f42ea12018-08-08 09:08:25 -07002001 audio_session_t session = client->session();
2002
2003 ALOGV("%s input:%d, session:%d, silenced:%d, concurrency:%d)",
2004 __FUNCTION__, input, session, silenced, *concurrency);
2005
Eric Laurent74708e72017-04-07 17:13:42 -07002006 if (!is_virtual_input_device(inputDesc->mDevice)) {
2007 if (mCallTxPatch != 0 &&
2008 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
2009 ALOGW("startInput(%d) failed: call in progress", input);
Ray Essick84e84a52018-05-03 18:45:07 -07002010 *concurrency |= API_INPUT_CONCURRENCY_CALL;
Eric Laurent74708e72017-04-07 17:13:42 -07002011 return INVALID_OPERATION;
2012 }
2013
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002014 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002015
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002016 // If a UID is idle and records silence and another not silenced recording starts
2017 // from another UID (idle or active) we stop the current idle UID recording in
2018 // favor of the new one - "There can be only one" TM
2019 if (!silenced) {
2020 for (const auto& activeDesc : activeInputs) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002021 if ((activeDesc->getAudioPort()->getFlags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002022 activeDesc->getId() == inputDesc->getId()) {
2023 continue;
2024 }
2025
Eric Laurent8f42ea12018-08-08 09:08:25 -07002026 RecordClientVector activeClients = activeDesc->clientsList(true /*activeOnly*/);
2027 for (const auto& activeClient : activeClients) {
2028 if (activeClient->isSilenced()) {
2029 closeClient(activeClient->portId());
2030 ALOGV("%s client %d stopping silenced client %d", __FUNCTION__,
2031 portId, activeClient->portId());
2032 activeInputs = mInputs.getActiveInputs();
2033 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002034 }
2035 }
2036 }
2037
2038 for (const auto& activeDesc : activeInputs) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002039 if ((client->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
Eric Laurentcb4dae22017-07-01 19:39:32 -07002040 activeDesc->getId() == inputDesc->getId()) {
2041 continue;
2042 }
2043
Eric Laurent74708e72017-04-07 17:13:42 -07002044 audio_source_t activeSource = activeDesc->inputSource(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002045 if (client->source() == AUDIO_SOURCE_HOTWORD) {
Eric Laurent74708e72017-04-07 17:13:42 -07002046 if (activeSource == AUDIO_SOURCE_HOTWORD) {
2047 if (activeDesc->hasPreemptedSession(session)) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002048 ALOGW("%s input %d failed for HOTWORD: "
2049 "other input %d already started for HOTWORD", __FUNCTION__,
Eric Laurent74708e72017-04-07 17:13:42 -07002050 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07002051 *concurrency |= API_INPUT_CONCURRENCY_HOTWORD;
Eric Laurent74708e72017-04-07 17:13:42 -07002052 return INVALID_OPERATION;
2053 }
2054 } else {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002055 ALOGV("%s input %d failed for HOTWORD: other input %d already started",
2056 __FUNCTION__, input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07002057 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07002058 return INVALID_OPERATION;
2059 }
2060 } else {
2061 if (activeSource != AUDIO_SOURCE_HOTWORD) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002062 ALOGW("%s input %d failed: other input %d already started", __FUNCTION__,
Eric Laurent74708e72017-04-07 17:13:42 -07002063 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07002064 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07002065 return INVALID_OPERATION;
2066 }
2067 }
2068 }
2069
Chris Thornton2b864642017-06-27 21:26:07 -07002070 // We only need to check if the sound trigger session supports concurrent capture if the
2071 // input is also a sound trigger input. Otherwise, we should preempt any hotword stream
2072 // that's running.
2073 const bool allowConcurrentWithSoundTrigger =
2074 inputDesc->isSoundTrigger() ? soundTriggerSupportsConcurrentCapture() : false;
2075
Eric Laurent74708e72017-04-07 17:13:42 -07002076 // if capture is allowed, preempt currently active HOTWORD captures
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002077 for (const auto& activeDesc : activeInputs) {
Chris Thornton2b864642017-06-27 21:26:07 -07002078 if (allowConcurrentWithSoundTrigger && activeDesc->isSoundTrigger()) {
2079 continue;
2080 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002081 RecordClientVector activeHotwordClients =
2082 activeDesc->clientsList(true, AUDIO_SOURCE_HOTWORD);
2083 if (activeHotwordClients.size() > 0) {
Eric Laurent74708e72017-04-07 17:13:42 -07002084 SortedVector<audio_session_t> sessions = activeDesc->getPreemptedSessions();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002085
2086 for (const auto& activeClient : activeHotwordClients) {
2087 *concurrency |= API_INPUT_CONCURRENCY_PREEMPT;
2088 sessions.add(activeClient->session());
2089 closeClient(activeClient->portId());
2090 ALOGV("%s input %d for HOTWORD preempting HOTWORD input %d", __FUNCTION__,
2091 input, activeDesc->mIoHandle);
2092 }
2093
Eric Laurent74708e72017-04-07 17:13:42 -07002094 inputDesc->setPreemptedSessions(sessions);
Eric Laurent74708e72017-04-07 17:13:42 -07002095 }
2096 }
2097 }
Eric Laurente552edb2014-03-10 17:42:56 -07002098
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002099 // Make sure we start with the correct silence state
Eric Laurent8f42ea12018-08-08 09:08:25 -07002100 client->setSilenced(silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002101
Eric Laurent313d1e72016-01-29 09:56:57 -08002102 // increment activity count before calling getNewInputDevice() below as only active sessions
2103 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002104 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002105
Eric Laurent8f42ea12018-08-08 09:08:25 -07002106 // indicate active capture to sound trigger service if starting capture from a mic on
2107 // primary HW module
2108 audio_devices_t device = getNewInputDevice(inputDesc);
2109 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002110
Eric Laurent8f42ea12018-08-08 09:08:25 -07002111 status_t status = inputDesc->start();
2112 if (status != NO_ERROR) {
2113 inputDesc->setClientActive(client, false);
2114 return status;
2115 }
2116
2117 if (inputDesc->activeCount() == 1) {
2118 // if input maps to a dynamic policy with an activity listener, notify of state change
2119 if ((inputDesc->mPolicyMix != NULL)
2120 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2121 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2122 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002123 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002124
Eric Laurent8f42ea12018-08-08 09:08:25 -07002125 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2126 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2127 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
2128 SoundTrigger::setCaptureState(true);
2129 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002130
Eric Laurent8f42ea12018-08-08 09:08:25 -07002131 // automatically enable the remote submix output when input is started if not
2132 // used by a policy mix of type MIX_TYPE_RECORDERS
2133 // For remote submix (a virtual device), we open only one input per capture request.
2134 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2135 String8 address = String8("");
2136 if (inputDesc->mPolicyMix == NULL) {
2137 address = String8("0");
2138 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2139 address = inputDesc->mPolicyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002140 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002141 if (address != "") {
2142 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2143 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2144 address, "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08002145 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002146 }
Eric Laurente552edb2014-03-10 17:42:56 -07002147 }
2148
Eric Laurent8f42ea12018-08-08 09:08:25 -07002149 ALOGV("%s input %d source = %d exit", __FUNCTION__, input, client->source());
Eric Laurente552edb2014-03-10 17:42:56 -07002150
Eric Laurente552edb2014-03-10 17:42:56 -07002151 return NO_ERROR;
2152}
2153
Eric Laurent8fc147b2018-07-22 19:13:55 -07002154status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002155{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002156 ALOGV("%s portId %d", __FUNCTION__, portId);
2157
2158 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2159 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002160 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002161 return BAD_VALUE;
2162 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002163 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002164 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002165 if (!client->active()) {
2166 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002167 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002168 }
2169
Eric Laurent8f42ea12018-08-08 09:08:25 -07002170 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002171
Eric Laurent8f42ea12018-08-08 09:08:25 -07002172 inputDesc->stop();
2173 if (inputDesc->isActive()) {
2174 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2175 } else {
2176 // if input maps to a dynamic policy with an activity listener, notify of state change
2177 if ((inputDesc->mPolicyMix != NULL)
2178 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2179 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2180 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002181 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002182
2183 // automatically disable the remote submix output when input is stopped if not
2184 // used by a policy mix of type MIX_TYPE_RECORDERS
2185 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2186 String8 address = String8("");
2187 if (inputDesc->mPolicyMix == NULL) {
2188 address = String8("0");
2189 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2190 address = inputDesc->mPolicyMix->mDeviceAddress;
2191 }
2192 if (address != "") {
2193 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2194 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2195 address, "remote-submix");
2196 }
2197 }
2198
2199 audio_devices_t device = inputDesc->mDevice;
2200 resetInputDevice(input);
2201
2202 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2203 // primary HW module
2204 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2205 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2206 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
2207 SoundTrigger::setCaptureState(false);
2208 }
2209 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002210 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002211 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002212}
2213
Eric Laurent8fc147b2018-07-22 19:13:55 -07002214void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002215{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002216 ALOGV("%s portId %d", __FUNCTION__, portId);
2217
2218 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2219 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002220 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002221 return;
2222 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002223 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002224 audio_io_handle_t input = inputDesc->mIoHandle;
2225
Eric Laurent8f42ea12018-08-08 09:08:25 -07002226 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002227
Andy Hung39efb7a2018-09-26 15:39:28 -07002228 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002229
Andy Hung39efb7a2018-09-26 15:39:28 -07002230 if (inputDesc->getClientCount() > 0) {
2231 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002232 return;
2233 }
2234
Eric Laurent05b90f82014-08-27 15:32:29 -07002235 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002236 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002237 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002238}
2239
Eric Laurent8f42ea12018-08-08 09:08:25 -07002240void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002241{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002242 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002243
2244 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002245 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002246 }
2247}
2248
Eric Laurent8f42ea12018-08-08 09:08:25 -07002249void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2250{
2251 stopInput(portId);
2252 releaseInput(portId);
2253}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002254
Eric Laurentd4692962014-05-05 18:13:44 -07002255void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002256 bool patchRemoved = false;
2257
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002258 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002259 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002260 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002261 if (patch_index >= 0) {
2262 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002263 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002264 mAudioPatches.removeItemsAt(patch_index);
2265 patchRemoved = true;
2266 }
Eric Laurentfe231122017-11-17 17:48:06 -08002267 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002268 }
2269 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002270 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002271 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002272
2273 if (patchRemoved) {
2274 mpClientInterface->onAudioPatchListUpdate();
2275 }
Eric Laurentd4692962014-05-05 18:13:44 -07002276}
2277
Eric Laurente0720872014-03-11 09:30:41 -07002278void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002279 int indexMin,
2280 int indexMax)
2281{
2282 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002283 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002284
2285 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002286 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2287 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002288 continue;
2289 }
2290 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002291 }
Eric Laurente552edb2014-03-10 17:42:56 -07002292}
2293
Eric Laurente0720872014-03-11 09:30:41 -07002294status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002295 int index,
2296 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002297{
2298
Nadav Bar7c605f62017-12-25 00:01:52 +02002299 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2300 // app that has MODIFY_PHONE_STATE permission.
2301 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
2302 !(stream == AUDIO_STREAM_VOICE_CALL && index == 0)) ||
François Gaffied1ab2bd2015-12-02 18:20:06 +01002303 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002304 return BAD_VALUE;
2305 }
2306 if (!audio_is_output_device(device)) {
2307 return BAD_VALUE;
2308 }
2309
2310 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002311 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002312
Eric Laurent1fd372e2016-04-06 14:23:53 -07002313 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002314 stream, device, index);
2315
Eric Laurent28d09f02016-03-08 10:43:05 -08002316 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002317 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2318 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002319 continue;
2320 }
2321 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2322 }
Eric Laurente552edb2014-03-10 17:42:56 -07002323
Eric Laurent1fd372e2016-04-06 14:23:53 -07002324 // update volume on all outputs and streams matching the following:
2325 // - The requested stream (or a stream matching for volume control) is active on the output
2326 // - The device (or devices) selected by the strategy corresponding to this stream includes
2327 // the requested device
2328 // - For non default requested device, currently selected device on the output is either the
2329 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002330 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2331 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002332 status_t status = NO_ERROR;
2333 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002334 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2335 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08002336 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
Eric Laurent3839bc02018-07-10 18:33:34 -07002337 if (!(streamsMatchForvolume(stream, (audio_stream_type_t)curStream))) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002338 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002339 }
Eric Laurentdcd4ab12018-06-29 17:45:13 -07002340 if (!(desc->isStreamActive((audio_stream_type_t)curStream) || isInCall())) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002341 continue;
2342 }
Eric Laurent794fde22016-03-11 09:50:45 -08002343 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002344 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2345 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002346 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2347 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002348 continue;
2349 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002350 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002351 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002352 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07002353 applyVolume = (curDevice & curStreamDevice) != 0;
2354 } else {
2355 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002356 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002357 }
Eric Laurent3839bc02018-07-10 18:33:34 -07002358 // rescale index before applying to curStream as ranges may be different for
2359 // stream and curStream
2360 int idx = rescaleVolumeIndex(index, stream, (audio_stream_type_t)curStream);
Eric Laurente76f29c2016-09-14 17:17:53 -07002361 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002362 //FIXME: workaround for truncated touch sounds
2363 // delayed volume change for system stream to be removed when the problem is
2364 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002365 status_t volStatus =
Eric Laurent3839bc02018-07-10 18:33:34 -07002366 checkAndSetVolume((audio_stream_type_t)curStream, idx, desc, curDevice,
Eric Laurentdc462862016-07-19 12:29:53 -07002367 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002368 if (volStatus != NO_ERROR) {
2369 status = volStatus;
2370 }
2371 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002372 }
Eric Laurente552edb2014-03-10 17:42:56 -07002373 }
2374 return status;
2375}
2376
Eric Laurente0720872014-03-11 09:30:41 -07002377status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002378 int *index,
2379 audio_devices_t device)
2380{
2381 if (index == NULL) {
2382 return BAD_VALUE;
2383 }
2384 if (!audio_is_output_device(device)) {
2385 return BAD_VALUE;
2386 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002387 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002388 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002389 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002390 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2391 }
François Gaffiedfd74092015-03-19 12:10:59 +01002392 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002393
François Gaffied1ab2bd2015-12-02 18:20:06 +01002394 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002395 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2396 return NO_ERROR;
2397}
2398
Eric Laurent36829f92017-04-07 19:04:42 -07002399audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002400{
2401 // select one output among several suitable for global effects.
2402 // The priority is as follows:
2403 // 1: An offloaded output. If the effect ends up not being offloadable,
2404 // AudioFlinger will invalidate the track and the offloaded output
2405 // will be closed causing the effect to be moved to a PCM output.
2406 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002407 // 3: The primary output
2408 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002409
Eric Laurent3b73df72014-03-11 09:06:29 -07002410 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002411 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent36829f92017-04-07 19:04:42 -07002412 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002413
Eric Laurent36829f92017-04-07 19:04:42 -07002414 if (outputs.size() == 0) {
2415 return AUDIO_IO_HANDLE_NONE;
2416 }
Eric Laurente552edb2014-03-10 17:42:56 -07002417
Eric Laurent36829f92017-04-07 19:04:42 -07002418 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2419 bool activeOnly = true;
2420
2421 while (output == AUDIO_IO_HANDLE_NONE) {
2422 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2423 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2424 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2425
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002426 for (audio_io_handle_t output : outputs) {
2427 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002428 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2429 continue;
2430 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002431 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2432 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002433 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002434 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002435 }
2436 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002437 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002438 }
2439 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002440 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002441 }
2442 }
2443 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2444 output = outputOffloaded;
2445 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2446 output = outputDeepBuffer;
2447 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2448 output = outputPrimary;
2449 } else {
2450 output = outputs[0];
2451 }
2452 activeOnly = false;
2453 }
2454
2455 if (output != mMusicEffectOutput) {
2456 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2457 mMusicEffectOutput = output;
2458 }
2459
2460 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002461 return output;
2462}
2463
Eric Laurent36829f92017-04-07 19:04:42 -07002464audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2465{
2466 return selectOutputForMusicEffects();
2467}
2468
Eric Laurente0720872014-03-11 09:30:41 -07002469status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002470 audio_io_handle_t io,
2471 uint32_t strategy,
2472 int session,
2473 int id)
2474{
2475 ssize_t index = mOutputs.indexOfKey(io);
2476 if (index < 0) {
2477 index = mInputs.indexOfKey(io);
2478 if (index < 0) {
2479 ALOGW("registerEffect() unknown io %d", io);
2480 return INVALID_OPERATION;
2481 }
2482 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002483 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002484}
2485
Eric Laurentc75307b2015-03-17 15:29:32 -07002486bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2487{
Eric Laurent28d09f02016-03-08 10:43:05 -08002488 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002489 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2490 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002491 continue;
2492 }
2493 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2494 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002495 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002496}
2497
2498bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2499{
2500 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2501}
2502
Eric Laurente0720872014-03-11 09:30:41 -07002503bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002504{
2505 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002506 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002507 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002508 return true;
2509 }
2510 }
2511 return false;
2512}
2513
Eric Laurent275e8e92014-11-30 15:14:47 -08002514// Register a list of custom mixes with their attributes and format.
2515// When a mix is registered, corresponding input and output profiles are
2516// added to the remote submix hw module. The profile contains only the
2517// parameters (sampling rate, format...) specified by the mix.
2518// The corresponding input remote submix device is also connected.
2519//
2520// When a remote submix device is connected, the address is checked to select the
2521// appropriate profile and the corresponding input or output stream is opened.
2522//
2523// When capture starts, getInputForAttr() will:
2524// - 1 look for a mix matching the address passed in attribtutes tags if any
2525// - 2 if none found, getDeviceForInputSource() will:
2526// - 2.1 look for a mix matching the attributes source
2527// - 2.2 if none found, default to device selection by policy rules
2528// At this time, the corresponding output remote submix device is also connected
2529// and active playback use cases can be transferred to this mix if needed when reconnecting
2530// after AudioTracks are invalidated
2531//
2532// When playback starts, getOutputForAttr() will:
2533// - 1 look for a mix matching the address passed in attribtutes tags if any
2534// - 2 if none found, look for a mix matching the attributes usage
2535// - 3 if none found, default to device and output selection by policy rules.
2536
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002537status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002538{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002539 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2540 status_t res = NO_ERROR;
2541
2542 sp<HwModule> rSubmixModule;
2543 // examine each mix's route type
2544 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002545 AudioMix mix = mixes[i];
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002546 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
Eric Laurent97ac8712018-07-27 18:59:02 -07002547 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002548 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002549 break;
2550 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002551 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002552 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002553 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002554 rSubmixModule = mHwModules.getModuleFromName(
2555 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2556 if (rSubmixModule == 0) {
2557 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2558 i);
2559 res = INVALID_OPERATION;
2560 break;
2561 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002562 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002563
Eric Laurent97ac8712018-07-27 18:59:02 -07002564 String8 address = mix.mDeviceAddress;
2565 if (mix.mMixType == MIX_TYPE_PLAYERS) {
2566 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2567 } else {
2568 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
2569 }
François Gaffie036e1e92015-03-19 10:16:24 +01002570
Eric Laurent97ac8712018-07-27 18:59:02 -07002571 if (mPolicyMixes.registerMix(address, mix, 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002572 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002573 res = INVALID_OPERATION;
2574 break;
2575 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002576 audio_config_t outputConfig = mix.mFormat;
2577 audio_config_t inputConfig = mix.mFormat;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002578 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2579 // stereo and let audio flinger do the channel conversion if needed.
2580 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2581 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2582 rSubmixModule->addOutputProfile(address, &outputConfig,
2583 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2584 rSubmixModule->addInputProfile(address, &inputConfig,
2585 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002586
Eric Laurent97ac8712018-07-27 18:59:02 -07002587 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002588 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2589 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2590 address.string(), "remote-submix");
2591 } else {
2592 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2593 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2594 address.string(), "remote-submix");
2595 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002596 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2597 String8 address = mix.mDeviceAddress;
2598 audio_devices_t device = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002599 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2600 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002601
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002602 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002603 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2604 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2605 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2606 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2607 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2608 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002609 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2610 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002611 if (mPolicyMixes.registerMix(address, mix, desc) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002612 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002613 } else {
2614 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002615 }
2616 break;
2617 }
2618 }
2619
2620 if (res != NO_ERROR) {
2621 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002622 i, device, address.string());
2623 res = INVALID_OPERATION;
2624 break;
2625 } else if (!foundOutput) {
2626 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2627 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002628 res = INVALID_OPERATION;
2629 break;
2630 }
Eric Laurentc722f302014-12-10 11:21:49 -08002631 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002632 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002633 if (res != NO_ERROR) {
2634 unregisterPolicyMixes(mixes);
2635 }
2636 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002637}
2638
2639status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2640{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002641 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002642 status_t res = NO_ERROR;
2643 sp<HwModule> rSubmixModule;
2644 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002645 for (const auto& mix : mixes) {
2646 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002647
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002648 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002649 rSubmixModule = mHwModules.getModuleFromName(
2650 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2651 if (rSubmixModule == 0) {
2652 res = INVALID_OPERATION;
2653 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002654 }
2655 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002656
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002657 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002658
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002659 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2660 res = INVALID_OPERATION;
2661 continue;
2662 }
2663
2664 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2665 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2666 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2667 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2668 address.string(), "remote-submix");
2669 }
2670 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2671 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2672 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2673 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2674 address.string(), "remote-submix");
2675 }
2676 rSubmixModule->removeOutputProfile(address);
2677 rSubmixModule->removeInputProfile(address);
2678
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002679 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2680 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002681 res = INVALID_OPERATION;
2682 continue;
2683 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002684 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002685 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002686 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002687}
2688
Eric Laurente552edb2014-03-10 17:42:56 -07002689
Eric Laurente0720872014-03-11 09:30:41 -07002690status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002691{
Eric Laurente552edb2014-03-10 17:42:56 -07002692 String8 result;
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002693 result.appendFormat("\nAudioPolicyManager Dump: %p\n", this);
2694 result.appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07002695 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002696 std::string stateLiteral;
2697 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002698 result.appendFormat(" Phone state: %s\n", stateLiteral.c_str());
2699 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
2700 "communications", "media", "record", "dock", "system",
2701 "HDMI system audio", "encoded surround output", "vibrate ringing" };
2702 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
2703 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
2704 result.appendFormat(" Force use for %s: %d\n",
2705 forceUses[i], mEngine->getForceUse(i));
2706 }
2707 result.appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
2708 result.appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
2709 result.appendFormat(" Config source: %s\n", getConfig().getSource().c_str());
Andy Hungbb54e202018-10-05 11:42:02 -07002710 mAvailableOutputDevices.dump(&result, String8("Available output"));
2711 mAvailableInputDevices.dump(&result, String8("Available input"));
2712 mHwModulesAll.dump(&result);
2713 mOutputs.dump(&result);
2714 mInputs.dump(&result);
François Gaffie2110e042015-03-24 08:41:51 +01002715 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002716
Andy Hungbb54e202018-10-05 11:42:02 -07002717 // TODO convert these to dump to string.
François Gaffied1ab2bd2015-12-02 18:20:06 +01002718 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002719 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002720 mAudioPatches.dump(fd);
Mikhail Naganov44344b02016-12-13 11:21:02 -08002721 mPolicyMixes.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002722
Andy Hungbb54e202018-10-05 11:42:02 -07002723 result.clear();
2724 mAudioSources.dump(&result);
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002725 if (!mSurroundFormats.empty()) {
Andy Hungbb54e202018-10-05 11:42:02 -07002726 result.append("\nEnabled Surround Formats:\n");
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002727 size_t i = 0;
2728 for (const auto& fmt : mSurroundFormats) {
2729 result.append(i++ == 0 ? " " : ", ");
2730 std::string sfmt;
2731 FormatConverter::toString(fmt, sfmt);
Andy Hungbb54e202018-10-05 11:42:02 -07002732 result.append(sfmt.c_str());
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002733 }
2734 result.append("\n");
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002735 }
Andy Hungbb54e202018-10-05 11:42:02 -07002736 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002737 return NO_ERROR;
2738}
2739
2740// This function checks for the parameters which can be offloaded.
2741// This can be enhanced depending on the capability of the DSP and policy
2742// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002743bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002744{
2745 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002746 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002747 offloadInfo.sample_rate, offloadInfo.channel_mask,
2748 offloadInfo.format,
2749 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2750 offloadInfo.has_video);
2751
Andy Hung2ddee192015-12-18 17:34:44 -08002752 if (mMasterMono) {
2753 return false; // no offloading if mono is set.
2754 }
2755
Eric Laurente552edb2014-03-10 17:42:56 -07002756 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07002757 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
2758 ALOGV("offload disabled by audio.offload.disable");
2759 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002760 }
2761
2762 // Check if stream type is music, then only allow offload as of now.
2763 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2764 {
2765 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2766 return false;
2767 }
2768
2769 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002770 const bool allowOffloadWithVideo =
2771 property_get_bool("audio.offload.video", false /* default_value */);
2772 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002773 ALOGV("isOffloadSupported: has_video == true, returning false");
2774 return false;
2775 }
2776
2777 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07002778 const int min_duration_secs = property_get_int32(
2779 "audio.offload.min.duration.secs", -1 /* default_value */);
2780 if (min_duration_secs >= 0) {
2781 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
2782 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%d)",
2783 min_duration_secs);
Eric Laurente552edb2014-03-10 17:42:56 -07002784 return false;
2785 }
2786 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2787 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2788 return false;
2789 }
2790
2791 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2792 // creating an offloaded track and tearing it down immediately after start when audioflinger
2793 // detects there is an active non offloadable effect.
2794 // FIXME: We should check the audio session here but we do not have it in this context.
2795 // This may prevent offloading in rare situations where effects are left active by apps
2796 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002797 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002798 return false;
2799 }
2800
2801 // See if there is a profile to support this.
2802 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002803 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002804 offloadInfo.sample_rate,
2805 offloadInfo.format,
2806 offloadInfo.channel_mask,
2807 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002808 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2809 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002810}
2811
Eric Laurent6a94d692014-05-20 11:18:06 -07002812status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2813 audio_port_type_t type,
2814 unsigned int *num_ports,
2815 struct audio_port *ports,
2816 unsigned int *generation)
2817{
2818 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2819 generation == NULL) {
2820 return BAD_VALUE;
2821 }
2822 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2823 if (ports == NULL) {
2824 *num_ports = 0;
2825 }
2826
2827 size_t portsWritten = 0;
2828 size_t portsMax = *num_ports;
2829 *num_ports = 0;
2830 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002831 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2832 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002833 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002834 for (const auto& dev : mAvailableOutputDevices) {
2835 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002836 continue;
2837 }
2838 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002839 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002840 }
2841 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002842 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002843 }
2844 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002845 for (const auto& dev : mAvailableInputDevices) {
2846 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002847 continue;
2848 }
2849 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002850 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002851 }
2852 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002853 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002854 }
2855 }
2856 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2857 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2858 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2859 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2860 }
2861 *num_ports += mInputs.size();
2862 }
2863 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002864 size_t numOutputs = 0;
2865 for (size_t i = 0; i < mOutputs.size(); i++) {
2866 if (!mOutputs[i]->isDuplicated()) {
2867 numOutputs++;
2868 if (portsWritten < portsMax) {
2869 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2870 }
2871 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002872 }
Eric Laurent84c70242014-06-23 08:46:27 -07002873 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002874 }
2875 }
2876 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002877 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002878 return NO_ERROR;
2879}
2880
Eric Laurent99fcae42018-05-17 16:59:18 -07002881status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07002882{
Eric Laurent99fcae42018-05-17 16:59:18 -07002883 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
2884 return BAD_VALUE;
2885 }
2886 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
2887 if (dev != 0) {
2888 dev->toAudioPort(port);
2889 return NO_ERROR;
2890 }
2891 dev = mAvailableInputDevices.getDeviceFromId(port->id);
2892 if (dev != 0) {
2893 dev->toAudioPort(port);
2894 return NO_ERROR;
2895 }
2896 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
2897 if (out != 0) {
2898 out->toAudioPort(port);
2899 return NO_ERROR;
2900 }
2901 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
2902 if (in != 0) {
2903 in->toAudioPort(port);
2904 return NO_ERROR;
2905 }
2906 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002907}
2908
Eric Laurent6a94d692014-05-20 11:18:06 -07002909status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2910 audio_patch_handle_t *handle,
2911 uid_t uid)
2912{
2913 ALOGV("createAudioPatch()");
2914
2915 if (handle == NULL || patch == NULL) {
2916 return BAD_VALUE;
2917 }
2918 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2919
Mikhail Naganovac9858b2018-06-15 13:12:37 -07002920 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07002921 return BAD_VALUE;
2922 }
2923 // only one source per audio patch supported for now
2924 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002925 return INVALID_OPERATION;
2926 }
Eric Laurent874c42872014-08-08 15:13:39 -07002927
2928 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002929 return INVALID_OPERATION;
2930 }
Eric Laurent874c42872014-08-08 15:13:39 -07002931 for (size_t i = 0; i < patch->num_sinks; i++) {
2932 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2933 return INVALID_OPERATION;
2934 }
2935 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002936
2937 sp<AudioPatch> patchDesc;
2938 ssize_t index = mAudioPatches.indexOfKey(*handle);
2939
Eric Laurent6a94d692014-05-20 11:18:06 -07002940 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2941 patch->sources[0].role,
2942 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002943#if LOG_NDEBUG == 0
2944 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002945 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002946 patch->sinks[i].role,
2947 patch->sinks[i].type);
2948 }
2949#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002950
2951 if (index >= 0) {
2952 patchDesc = mAudioPatches.valueAt(index);
2953 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2954 mUidCached, patchDesc->mUid, uid);
2955 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2956 return INVALID_OPERATION;
2957 }
2958 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002959 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002960 }
2961
2962 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002963 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002964 if (outputDesc == NULL) {
2965 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2966 return BAD_VALUE;
2967 }
Eric Laurent84c70242014-06-23 08:46:27 -07002968 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2969 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002970 if (patchDesc != 0) {
2971 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2972 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2973 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2974 return BAD_VALUE;
2975 }
2976 }
Eric Laurent874c42872014-08-08 15:13:39 -07002977 DeviceVector devices;
2978 for (size_t i = 0; i < patch->num_sinks; i++) {
2979 // Only support mix to devices connection
2980 // TODO add support for mix to mix connection
2981 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2982 ALOGV("createAudioPatch() source mix but sink is not a device");
2983 return INVALID_OPERATION;
2984 }
2985 sp<DeviceDescriptor> devDesc =
2986 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2987 if (devDesc == 0) {
2988 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2989 return BAD_VALUE;
2990 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002991
François Gaffie53615e22015-03-19 09:24:12 +01002992 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002993 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002994 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002995 NULL, // updatedSamplingRate
2996 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002997 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002998 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002999 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01003000 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07003001 ALOGV("createAudioPatch() profile not supported for device %08x",
3002 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07003003 return INVALID_OPERATION;
3004 }
3005 devices.add(devDesc);
3006 }
3007 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003008 return INVALID_OPERATION;
3009 }
Eric Laurent874c42872014-08-08 15:13:39 -07003010
Eric Laurent6a94d692014-05-20 11:18:06 -07003011 // TODO: reconfigure output format and channels here
3012 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07003013 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07003014 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003015 index = mAudioPatches.indexOfKey(*handle);
3016 if (index >= 0) {
3017 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3018 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
3019 }
3020 patchDesc = mAudioPatches.valueAt(index);
3021 patchDesc->mUid = uid;
3022 ALOGV("createAudioPatch() success");
3023 } else {
3024 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
3025 return INVALID_OPERATION;
3026 }
3027 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3028 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3029 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003030 // only one sink supported when connecting an input device to a mix
3031 if (patch->num_sinks > 1) {
3032 return INVALID_OPERATION;
3033 }
François Gaffie53615e22015-03-19 09:24:12 +01003034 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003035 if (inputDesc == NULL) {
3036 return BAD_VALUE;
3037 }
3038 if (patchDesc != 0) {
3039 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3040 return BAD_VALUE;
3041 }
3042 }
3043 sp<DeviceDescriptor> devDesc =
3044 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
3045 if (devDesc == 0) {
3046 return BAD_VALUE;
3047 }
3048
François Gaffie53615e22015-03-19 09:24:12 +01003049 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08003050 devDesc->mAddress,
3051 patch->sinks[0].sample_rate,
3052 NULL, /*updatedSampleRate*/
3053 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003054 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003055 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003056 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003057 // FIXME for the parameter type,
3058 // and the NONE
3059 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003060 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003061 return INVALID_OPERATION;
3062 }
3063 // TODO: reconfigure output format and channels here
3064 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01003065 devDesc->type(), inputDesc->mIoHandle);
3066 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003067 index = mAudioPatches.indexOfKey(*handle);
3068 if (index >= 0) {
3069 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3070 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
3071 }
3072 patchDesc = mAudioPatches.valueAt(index);
3073 patchDesc->mUid = uid;
3074 ALOGV("createAudioPatch() success");
3075 } else {
3076 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
3077 return INVALID_OPERATION;
3078 }
3079 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3080 // device to device connection
3081 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003082 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003083 return BAD_VALUE;
3084 }
3085 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003086 sp<DeviceDescriptor> srcDeviceDesc =
3087 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07003088 if (srcDeviceDesc == 0) {
3089 return BAD_VALUE;
3090 }
Eric Laurent874c42872014-08-08 15:13:39 -07003091
Eric Laurent6a94d692014-05-20 11:18:06 -07003092 //update source and sink with our own data as the data passed in the patch may
3093 // be incomplete.
3094 struct audio_patch newPatch = *patch;
3095 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003096
Eric Laurent874c42872014-08-08 15:13:39 -07003097 for (size_t i = 0; i < patch->num_sinks; i++) {
3098 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3099 ALOGV("createAudioPatch() source device but one sink is not a device");
3100 return INVALID_OPERATION;
3101 }
3102
3103 sp<DeviceDescriptor> sinkDeviceDesc =
3104 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3105 if (sinkDeviceDesc == 0) {
3106 return BAD_VALUE;
3107 }
3108 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
3109
Eric Laurent3bcf8592015-04-03 12:13:24 -07003110 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003111 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003112 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08003113 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003114 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003115 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003116 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003117 return INVALID_OPERATION;
3118 }
Eric Laurent874c42872014-08-08 15:13:39 -07003119 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01003120 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003121 // if the sink device is reachable via an opened output stream, request to go via
3122 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07003123 audio_io_handle_t output = selectOutput(outputs,
3124 AUDIO_OUTPUT_FLAG_NONE,
3125 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07003126 if (output != AUDIO_IO_HANDLE_NONE) {
3127 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3128 if (outputDesc->isDuplicated()) {
3129 return INVALID_OPERATION;
3130 }
3131 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003132 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003133 newPatch.num_sources = 2;
3134 }
Eric Laurent83b88082014-06-20 18:31:16 -07003135 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003136 }
3137 // TODO: check from routing capabilities in config file and other conflicting patches
3138
Mikhail Naganovdc769682018-05-04 15:34:08 -07003139 status_t status = installPatch(__func__, index, handle, &newPatch, 0, uid, &patchDesc);
3140 if (status != NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003141 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3142 status);
3143 return INVALID_OPERATION;
3144 }
3145 } else {
3146 return BAD_VALUE;
3147 }
3148 } else {
3149 return BAD_VALUE;
3150 }
3151 return NO_ERROR;
3152}
3153
3154status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3155 uid_t uid)
3156{
3157 ALOGV("releaseAudioPatch() patch %d", handle);
3158
3159 ssize_t index = mAudioPatches.indexOfKey(handle);
3160
3161 if (index < 0) {
3162 return BAD_VALUE;
3163 }
3164 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3165 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3166 mUidCached, patchDesc->mUid, uid);
3167 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3168 return INVALID_OPERATION;
3169 }
3170
3171 struct audio_patch *patch = &patchDesc->mPatch;
3172 patchDesc->mUid = mUidCached;
3173 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003174 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003175 if (outputDesc == NULL) {
3176 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3177 return BAD_VALUE;
3178 }
3179
Eric Laurentc75307b2015-03-17 15:29:32 -07003180 setOutputDevice(outputDesc,
3181 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07003182 true,
3183 0,
3184 NULL);
3185 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3186 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003187 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003188 if (inputDesc == NULL) {
3189 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3190 return BAD_VALUE;
3191 }
3192 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003193 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003194 true,
3195 NULL);
3196 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003197 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3198 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3199 status, patchDesc->mAfPatchHandle);
3200 removeAudioPatch(patchDesc->mHandle);
3201 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003202 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003203 } else {
3204 return BAD_VALUE;
3205 }
3206 } else {
3207 return BAD_VALUE;
3208 }
3209 return NO_ERROR;
3210}
3211
3212status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3213 struct audio_patch *patches,
3214 unsigned int *generation)
3215{
François Gaffie53615e22015-03-19 09:24:12 +01003216 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003217 return BAD_VALUE;
3218 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003219 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003220 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003221}
3222
Eric Laurente1715a42014-05-20 11:30:42 -07003223status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003224{
Eric Laurente1715a42014-05-20 11:30:42 -07003225 ALOGV("setAudioPortConfig()");
3226
3227 if (config == NULL) {
3228 return BAD_VALUE;
3229 }
3230 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3231 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003232 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3233 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003234 }
3235
Eric Laurenta121f902014-06-03 13:32:54 -07003236 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003237 if (config->type == AUDIO_PORT_TYPE_MIX) {
3238 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003239 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003240 if (outputDesc == NULL) {
3241 return BAD_VALUE;
3242 }
Eric Laurent84c70242014-06-23 08:46:27 -07003243 ALOG_ASSERT(!outputDesc->isDuplicated(),
3244 "setAudioPortConfig() called on duplicated output %d",
3245 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003246 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003247 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003248 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003249 if (inputDesc == NULL) {
3250 return BAD_VALUE;
3251 }
Eric Laurenta121f902014-06-03 13:32:54 -07003252 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003253 } else {
3254 return BAD_VALUE;
3255 }
3256 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3257 sp<DeviceDescriptor> deviceDesc;
3258 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3259 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3260 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3261 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3262 } else {
3263 return BAD_VALUE;
3264 }
3265 if (deviceDesc == NULL) {
3266 return BAD_VALUE;
3267 }
Eric Laurenta121f902014-06-03 13:32:54 -07003268 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003269 } else {
3270 return BAD_VALUE;
3271 }
3272
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003273 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003274 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3275 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003276 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003277 audioPortConfig->toAudioPortConfig(&newConfig, config);
3278 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003279 }
Eric Laurenta121f902014-06-03 13:32:54 -07003280 if (status != NO_ERROR) {
3281 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003282 }
Eric Laurente1715a42014-05-20 11:30:42 -07003283
3284 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003285}
3286
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003287void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3288{
Eric Laurentd60560a2015-04-10 11:31:20 -07003289 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003290 clearAudioPatches(uid);
3291 clearSessionRoutes(uid);
3292}
3293
Eric Laurent6a94d692014-05-20 11:18:06 -07003294void AudioPolicyManager::clearAudioPatches(uid_t uid)
3295{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003296 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003297 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3298 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003299 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003300 }
3301 }
3302}
3303
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003304void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3305 audio_io_handle_t ouptutToSkip)
3306{
3307 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3308 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3309 for (size_t j = 0; j < mOutputs.size(); j++) {
3310 if (mOutputs.keyAt(j) == ouptutToSkip) {
3311 continue;
3312 }
3313 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3314 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3315 continue;
3316 }
3317 // If the default device for this strategy is on another output mix,
3318 // invalidate all tracks in this strategy to force re connection.
3319 // Otherwise select new device on the output mix.
3320 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003321 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003322 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3323 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3324 }
3325 }
3326 } else {
3327 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3328 setOutputDevice(outputDesc, newDevice, false);
3329 }
3330 }
3331}
3332
3333void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3334{
3335 // remove output routes associated with this uid
3336 SortedVector<routing_strategy> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07003337 for (size_t i = 0; i < mOutputs.size(); i++) {
3338 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003339 for (const auto& client : outputDesc->getClientIterable()) {
3340 if (client->hasPreferredDevice() && client->uid() == uid) {
3341 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3342 affectedStrategies.add(getStrategy(client->stream()));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003343 }
3344 }
3345 }
3346 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003347 for (const auto& strategy : affectedStrategies) {
3348 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003349 }
3350
3351 // remove input routes associated with this uid
3352 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07003353 for (size_t i = 0; i < mInputs.size(); i++) {
3354 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003355 for (const auto& client : inputDesc->getClientIterable()) {
3356 if (client->hasPreferredDevice() && client->uid() == uid) {
3357 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3358 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003359 }
3360 }
3361 }
3362 // reroute inputs if necessary
3363 SortedVector<audio_io_handle_t> inputsToClose;
3364 for (size_t i = 0; i < mInputs.size(); i++) {
3365 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003366 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003367 inputsToClose.add(inputDesc->mIoHandle);
3368 }
3369 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003370 for (const auto& input : inputsToClose) {
3371 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003372 }
3373}
3374
Eric Laurentd60560a2015-04-10 11:31:20 -07003375void AudioPolicyManager::clearAudioSources(uid_t uid)
3376{
3377 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003378 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3379 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07003380 stopAudioSource(mAudioSources.keyAt(i));
3381 }
3382 }
3383}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003384
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003385status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3386 audio_io_handle_t *ioHandle,
3387 audio_devices_t *device)
3388{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003389 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3390 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003391 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003392
François Gaffiedf372692015-03-19 10:43:27 +01003393 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003394}
3395
Eric Laurentd60560a2015-04-10 11:31:20 -07003396status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003397 const audio_attributes_t *attributes,
3398 audio_port_handle_t *portId,
3399 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003400{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003401 ALOGV("%s", __FUNCTION__);
3402 *portId = AUDIO_PORT_HANDLE_NONE;
3403
3404 if (source == NULL || attributes == NULL || portId == NULL) {
3405 ALOGW("%s invalid argument: source %p attributes %p handle %p",
3406 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003407 return BAD_VALUE;
3408 }
3409
Eric Laurentd60560a2015-04-10 11:31:20 -07003410 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3411 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003412 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
3413 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003414 return INVALID_OPERATION;
3415 }
3416
3417 sp<DeviceDescriptor> srcDeviceDesc =
3418 mAvailableInputDevices.getDevice(source->ext.device.type,
3419 String8(source->ext.device.address));
3420 if (srcDeviceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003421 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003422 return BAD_VALUE;
3423 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003424
3425 *portId = AudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07003426
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003427 struct audio_patch dummyPatch = {};
Eric Laurentd60560a2015-04-10 11:31:20 -07003428 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003429
3430 sp<SourceClientDescriptor> sourceDesc =
3431 new SourceClientDescriptor(*portId, uid, *attributes, patchDesc, srcDeviceDesc,
Eric Laurent97ac8712018-07-27 18:59:02 -07003432 streamTypefromAttributesInt(attributes),
3433 getStrategyForAttr(attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07003434
3435 status_t status = connectAudioSource(sourceDesc);
3436 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003437 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003438 }
3439 return status;
3440}
3441
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003442status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003443{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003444 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003445
3446 // make sure we only have one patch per source.
3447 disconnectAudioSource(sourceDesc);
3448
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003449 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003450 routing_strategy strategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003451 audio_stream_type_t stream = sourceDesc->stream();
3452 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->srcDevice();
Eric Laurentd60560a2015-04-10 11:31:20 -07003453
3454 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3455 sp<DeviceDescriptor> sinkDeviceDesc =
3456 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3457
3458 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003459
3460 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3461 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003462 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003463 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3464 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3465 // create patch between src device and output device
3466 // create Hwoutput and add to mHwOutputs
3467 } else {
3468 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3469 audio_io_handle_t output =
3470 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3471 if (output == AUDIO_IO_HANDLE_NONE) {
3472 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3473 return INVALID_OPERATION;
3474 }
3475 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3476 if (outputDesc->isDuplicated()) {
3477 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3478 return INVALID_OPERATION;
3479 }
Eric Laurent733ce942017-12-07 12:18:25 -08003480 status_t status = outputDesc->start();
3481 if (status != NO_ERROR) {
3482 return status;
3483 }
3484
Eric Laurentd60560a2015-04-10 11:31:20 -07003485 // create a special patch with no sink and two sources:
3486 // - the second source indicates to PatchPanel through which output mix this patch should
3487 // be connected as well as the stream type for volume control
3488 // - the sink is defined by whatever output device is currently selected for the output
3489 // though which this patch is routed.
Mikhail Naganovdc769682018-05-04 15:34:08 -07003490 PatchBuilder patchBuilder;
3491 patchBuilder.addSource(srcDeviceDesc).addSource(outputDesc, { .stream = stream });
3492 status = mpClientInterface->createAudioPatch(patchBuilder.patch(),
Eric Laurentd60560a2015-04-10 11:31:20 -07003493 &afPatchHandle,
3494 0);
3495 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3496 status, afPatchHandle);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003497 sourceDesc->patchDesc()->mPatch = *patchBuilder.patch();
Eric Laurentd60560a2015-04-10 11:31:20 -07003498 if (status != NO_ERROR) {
3499 ALOGW("%s patch panel could not connect device patch, error %d",
3500 __FUNCTION__, status);
3501 return INVALID_OPERATION;
3502 }
3503 uint32_t delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07003504 status = startSource(outputDesc, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003505
3506 if (status != NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003507 mpClientInterface->releaseAudioPatch(sourceDesc->patchDesc()->mAfPatchHandle, 0);
Eric Laurentd60560a2015-04-10 11:31:20 -07003508 return status;
3509 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003510 sourceDesc->setSwOutput(outputDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003511 if (delayMs != 0) {
3512 usleep(delayMs * 1000);
3513 }
3514 }
3515
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003516 sourceDesc->patchDesc()->mAfPatchHandle = afPatchHandle;
3517 addAudioPatch(sourceDesc->patchDesc()->mHandle, sourceDesc->patchDesc());
Eric Laurentd60560a2015-04-10 11:31:20 -07003518
3519 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003520}
3521
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003522status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07003523{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003524 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
3525 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003526 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003527 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003528 return BAD_VALUE;
3529 }
3530 status_t status = disconnectAudioSource(sourceDesc);
3531
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003532 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003533 return status;
3534}
3535
Andy Hung2ddee192015-12-18 17:34:44 -08003536status_t AudioPolicyManager::setMasterMono(bool mono)
3537{
3538 if (mMasterMono == mono) {
3539 return NO_ERROR;
3540 }
3541 mMasterMono = mono;
3542 // if enabling mono we close all offloaded devices, which will invalidate the
3543 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3544 // for recreating the new AudioTrack as non-offloaded PCM.
3545 //
3546 // If disabling mono, we leave all tracks as is: we don't know which clients
3547 // and tracks are able to be recreated as offloaded. The next "song" should
3548 // play back offloaded.
3549 if (mMasterMono) {
3550 Vector<audio_io_handle_t> offloaded;
3551 for (size_t i = 0; i < mOutputs.size(); ++i) {
3552 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3553 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3554 offloaded.push(desc->mIoHandle);
3555 }
3556 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003557 for (const auto& handle : offloaded) {
3558 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003559 }
3560 }
3561 // update master mono for all remaining outputs
3562 for (size_t i = 0; i < mOutputs.size(); ++i) {
3563 updateMono(mOutputs.keyAt(i));
3564 }
3565 return NO_ERROR;
3566}
3567
3568status_t AudioPolicyManager::getMasterMono(bool *mono)
3569{
3570 *mono = mMasterMono;
3571 return NO_ERROR;
3572}
3573
Eric Laurentac9cef52017-06-09 15:46:26 -07003574float AudioPolicyManager::getStreamVolumeDB(
3575 audio_stream_type_t stream, int index, audio_devices_t device)
3576{
3577 return computeVolume(stream, index, device);
3578}
3579
jiabin81772902018-04-02 17:52:27 -07003580status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3581 audio_format_t *surroundFormats,
3582 bool *surroundFormatsEnabled,
3583 bool reported)
3584{
3585 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3586 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3587 return BAD_VALUE;
3588 }
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003589 ALOGV("getSurroundFormats() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p"
3590 " reported %d", *numSurroundFormats, surroundFormats, surroundFormatsEnabled, reported);
jiabin81772902018-04-02 17:52:27 -07003591
3592 // Only return value if there is HDMI output.
3593 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3594 return INVALID_OPERATION;
3595 }
3596
3597 size_t formatsWritten = 0;
3598 size_t formatsMax = *numSurroundFormats;
3599 *numSurroundFormats = 0;
Mikhail Naganov2563f232018-09-27 14:48:01 -07003600 std::unordered_set<audio_format_t> formats;
jiabin81772902018-04-02 17:52:27 -07003601 if (reported) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003602 // Return formats from HDMI profiles, that have already been resolved by
3603 // checkOutputsForDevice().
3604 DeviceVector hdmiOutputDevs = mAvailableOutputDevices.getDevicesFromTypeMask(
3605 AUDIO_DEVICE_OUT_HDMI);
3606 for (size_t i = 0; i < hdmiOutputDevs.size(); i++) {
3607 FormatVector supportedFormats =
3608 hdmiOutputDevs[i]->getAudioPort()->getAudioProfiles().getSupportedFormats();
3609 for (size_t j = 0; j < supportedFormats.size(); j++) {
3610 if (std::find(std::begin(SURROUND_FORMATS),
3611 std::end(SURROUND_FORMATS),
3612 supportedFormats[j]) != std::end(SURROUND_FORMATS)) {
3613 formats.insert(supportedFormats[j]);
3614 } else if (std::find(std::begin(AAC_FORMATS),
3615 std::end(AAC_FORMATS),
3616 supportedFormats[j]) != std::end(AAC_FORMATS)) {
3617 // if any format in AAC_FORMATS is reported, insert AUDIO_FORMAT_AAC_LC as this
3618 // is the only AAC format used in the TvSettings UI for all AAC formats.
3619 formats.insert(AUDIO_FORMAT_AAC_LC);
3620 }
3621 }
jiabin81772902018-04-02 17:52:27 -07003622 }
3623 } else {
3624 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003625 formats.insert(SURROUND_FORMATS[i]);
jiabin81772902018-04-02 17:52:27 -07003626 }
3627 }
Mikhail Naganov2563f232018-09-27 14:48:01 -07003628 for (const auto& format: formats) {
jiabin81772902018-04-02 17:52:27 -07003629 if (formatsWritten < formatsMax) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003630 surroundFormats[formatsWritten] = format;
jiabin81772902018-04-02 17:52:27 -07003631 bool formatEnabled = false;
Mikhail Naganov2563f232018-09-27 14:48:01 -07003632 if (format == AUDIO_FORMAT_AAC_LC) {
3633 for (size_t j = 0; j < ARRAY_SIZE(AAC_FORMATS) && !formatEnabled; j++) {
jiabin81772902018-04-02 17:52:27 -07003634 formatEnabled =
Mikhail Naganov2563f232018-09-27 14:48:01 -07003635 mSurroundFormats.find(AAC_FORMATS[j]) != mSurroundFormats.end();
jiabin81772902018-04-02 17:52:27 -07003636 }
3637 } else {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003638 formatEnabled = mSurroundFormats.find(format) != mSurroundFormats.end();
jiabin81772902018-04-02 17:52:27 -07003639 }
3640 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3641 }
3642 (*numSurroundFormats)++;
3643 }
3644 return NO_ERROR;
3645}
3646
3647status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3648{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003649 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
jiabin81772902018-04-02 17:52:27 -07003650 // Check if audio format is a surround formats.
3651 bool isSurroundFormat = false;
3652 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3653 if (audioFormat == SURROUND_FORMATS[i]) {
3654 isSurroundFormat = true;
3655 break;
3656 }
3657 }
3658 if (!isSurroundFormat) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003659 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07003660 return BAD_VALUE;
3661 }
3662
3663 // Should only be called when MANUAL.
3664 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3665 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
3666 if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003667 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07003668 return INVALID_OPERATION;
3669 }
3670
3671 if ((mSurroundFormats.find(audioFormat) != mSurroundFormats.end() && enabled)
3672 || (mSurroundFormats.find(audioFormat) == mSurroundFormats.end() && !enabled)) {
3673 return NO_ERROR;
3674 }
3675
3676 // The operation is valid only when there is HDMI output available.
3677 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003678 ALOGW("%s() no HDMI out devices found", __func__);
jiabin81772902018-04-02 17:52:27 -07003679 return INVALID_OPERATION;
3680 }
3681
Mikhail Naganov2563f232018-09-27 14:48:01 -07003682 std::unordered_set<audio_format_t> surroundFormatsBackup(mSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07003683 if (enabled) {
3684 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3685 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3686 mSurroundFormats.insert(AAC_FORMATS[i]);
3687 }
3688 } else {
3689 mSurroundFormats.insert(audioFormat);
3690 }
3691 } else {
3692 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3693 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3694 mSurroundFormats.erase(AAC_FORMATS[i]);
3695 }
3696 } else {
3697 mSurroundFormats.erase(audioFormat);
3698 }
3699 }
3700
3701 sp<SwAudioOutputDescriptor> outputDesc;
3702 bool profileUpdated = false;
Mikhail Naganov708e0382018-05-30 09:53:04 -07003703 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003704 AUDIO_DEVICE_OUT_HDMI);
3705 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3706 // Simulate reconnection to update enabled surround sound formats.
3707 String8 address = hdmiOutputDevices[i]->mAddress;
3708 String8 name = hdmiOutputDevices[i]->getName();
3709 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3710 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3711 address.c_str(),
3712 name.c_str());
3713 if (status != NO_ERROR) {
3714 continue;
3715 }
3716 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3717 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3718 address.c_str(),
3719 name.c_str());
3720 profileUpdated |= (status == NO_ERROR);
3721 }
Mikhail Naganov708e0382018-05-30 09:53:04 -07003722 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003723 AUDIO_DEVICE_IN_HDMI);
3724 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3725 // Simulate reconnection to update enabled surround sound formats.
3726 String8 address = hdmiInputDevices[i]->mAddress;
3727 String8 name = hdmiInputDevices[i]->getName();
3728 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3729 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3730 address.c_str(),
3731 name.c_str());
3732 if (status != NO_ERROR) {
3733 continue;
3734 }
3735 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3736 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3737 address.c_str(),
3738 name.c_str());
3739 profileUpdated |= (status == NO_ERROR);
3740 }
3741
3742 // Undo the surround formats change due to no audio profiles updated.
3743 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003744 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov2563f232018-09-27 14:48:01 -07003745 mSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07003746 }
3747
3748 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3749}
3750
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003751void AudioPolicyManager::setRecordSilenced(uid_t uid, bool silenced)
3752{
3753 ALOGV("AudioPolicyManager:setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
3754
3755 Vector<sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
3756 for (size_t i = 0; i < activeInputs.size(); i++) {
3757 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
Eric Laurent8f42ea12018-08-08 09:08:25 -07003758 RecordClientVector clients = activeDesc->clientsList(true /*activeOnly*/);
3759 for (const auto& client : clients) {
3760 if (uid == client->uid()) {
3761 client->setSilenced(silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003762 }
3763 }
3764 }
3765}
3766
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003767status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003768{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003769 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003770
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003771 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003772 if (patchDesc == 0) {
3773 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003774 sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003775 return BAD_VALUE;
3776 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003777 removeAudioPatch(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003778
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003779 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003780 if (swOutputDesc != 0) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003781 status_t status = stopSource(swOutputDesc, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08003782 if (status == NO_ERROR) {
3783 swOutputDesc->stop();
3784 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003785 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3786 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003787 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003788 if (hwOutputDesc != 0) {
3789 // release patch between src device and output device
3790 // close Hwoutput and remove from mHwOutputs
3791 } else {
3792 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3793 }
3794 }
3795 return NO_ERROR;
3796}
3797
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003798sp<SourceClientDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
Eric Laurentd60560a2015-04-10 11:31:20 -07003799 audio_io_handle_t output, routing_strategy strategy)
3800{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003801 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07003802 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003803 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3804 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003805 routing_strategy sourceStrategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003806 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003807 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3808 source = sourceDesc;
3809 break;
3810 }
3811 }
3812 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003813}
3814
Eric Laurente552edb2014-03-10 17:42:56 -07003815// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003816// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003817// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003818uint32_t AudioPolicyManager::nextAudioPortGeneration()
3819{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003820 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003821}
3822
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003823#ifdef USE_XML_AUDIO_POLICY_CONF
3824// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3825static const char *kConfigLocationList[] =
3826 {"/odm/etc", "/vendor/etc", "/system/etc"};
3827static const int kConfigLocationListSize =
3828 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3829
3830static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3831 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07003832 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003833 status_t ret;
3834
Petri Gyntherf497f292018-04-17 18:46:10 -07003835 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
3836 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
3837 // A2DP offload supported but disabled: try to use special XML file
3838 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
3839 }
3840 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3841
3842 for (const char* fileName : fileNames) {
3843 for (int i = 0; i < kConfigLocationListSize; i++) {
Petri Gyntherf497f292018-04-17 18:46:10 -07003844 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
3845 "%s/%s", kConfigLocationList[i], fileName);
Mikhail Naganova289aea2018-09-17 15:26:23 -07003846 ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile, &config);
Petri Gyntherf497f292018-04-17 18:46:10 -07003847 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003848 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07003849 return ret;
3850 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003851 }
3852 }
3853 return ret;
3854}
3855#endif
3856
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003857AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
3858 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07003859 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07003860 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003861 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07003862 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003863 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003864#ifdef USE_XML_AUDIO_POLICY_CONF
3865 mVolumeCurves(new VolumeCurvesCollection()),
3866 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08003867 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003868#else
3869 mVolumeCurves(new StreamDescriptorCollection()),
3870 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
3871 mDefaultOutputDevice),
3872#endif
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003873 mAudioPortGeneration(1),
3874 mBeaconMuteRefCount(0),
3875 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003876 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003877 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003878 mMasterMono(false),
Chris Thornton2b864642017-06-27 21:26:07 -07003879 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE),
3880 mHasComputedSoundTriggerSupportsConcurrentCapture(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003881{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003882}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003883
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003884AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
3885 : AudioPolicyManager(clientInterface, false /*forTesting*/)
3886{
3887 loadConfig();
3888 initialize();
3889}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003890
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003891void AudioPolicyManager::loadConfig() {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003892#ifdef USE_XML_AUDIO_POLICY_CONF
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003893 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003894#else
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003895 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, getConfig()) != NO_ERROR)
3896 && (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, getConfig()) != NO_ERROR)) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003897#endif
3898 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003899 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01003900 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003901}
3902
3903status_t AudioPolicyManager::initialize() {
3904 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01003905
3906 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003907 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3908 if (!engineInstance) {
3909 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003910 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003911 }
3912 // Retrieve the Policy Manager Interface
3913 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3914 if (mEngine == NULL) {
3915 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003916 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003917 }
3918 mEngine->setObserver(this);
3919 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003920 if (status != NO_ERROR) {
3921 LOG_FATAL("Policy engine not initialized(err=%d)", status);
3922 return status;
3923 }
François Gaffie2110e042015-03-24 08:41:51 +01003924
Eric Laurent3a4311c2014-03-17 12:00:47 -07003925 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003926 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003927 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3928 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Mikhail Naganovd4120142017-12-06 15:49:22 -08003929 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003930 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08003931 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
3932 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003933 continue;
3934 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08003935 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07003936 // open all output streams needed to access attached devices
3937 // except for direct output streams that are only opened when they are actually
3938 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003939 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003940 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003941 if (!outProfile->canOpenNewIo()) {
3942 ALOGE("Invalid Output profile max open count %u for profile %s",
3943 outProfile->maxOpenCount, outProfile->getTagName().c_str());
3944 continue;
3945 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003946 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003947 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003948 continue;
3949 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003950 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003951 mTtsOutputAvailable = true;
3952 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003953
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003954 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003955 continue;
3956 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003957 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003958 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3959 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003960 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003961 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003962 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003963 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003964 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003965 if ((profileType & outputDeviceTypes) == 0) {
3966 continue;
3967 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003968 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3969 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003970 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov708e0382018-05-30 09:53:04 -07003971 const DeviceVector &devicesForType = supportedDevices.getDevicesFromTypeMask(
3972 profileType);
Eric Laurentc40d9692016-04-13 19:14:13 -07003973 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3974 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003975 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08003976 status_t status = outputDesc->open(nullptr, profileType, address,
3977 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07003978
3979 if (status != NO_ERROR) {
3980 ALOGW("Cannot open output stream for device %08x on hw module %s",
3981 outputDesc->mDevice,
Mikhail Naganovd4120142017-12-06 15:49:22 -08003982 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003983 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003984 for (const auto& dev : supportedDevices) {
3985 ssize_t index = mAvailableOutputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07003986 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003987 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003988 mAvailableOutputDevices[index]->attach(hwModule);
Eric Laurentd78f1532014-09-16 16:38:20 -07003989 }
3990 }
3991 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003992 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003993 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003994 }
3995 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003996 setOutputDevice(outputDesc,
Eric Laurentfe231122017-11-17 17:48:06 -08003997 profileType,
Eric Laurentc40d9692016-04-13 19:14:13 -07003998 true,
3999 0,
4000 NULL,
Eric Laurentfe231122017-11-17 17:48:06 -08004001 address);
Eric Laurentd78f1532014-09-16 16:38:20 -07004002 }
Eric Laurente552edb2014-03-10 17:42:56 -07004003 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004004 // open input streams needed to access attached devices to validate
4005 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004006 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004007 if (!inProfile->canOpenNewIo()) {
4008 ALOGE("Invalid Input profile max open count %u for profile %s",
4009 inProfile->maxOpenCount, inProfile->getTagName().c_str());
4010 continue;
4011 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004012 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004013 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004014 continue;
4015 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004016 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07004017 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004018 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
4019
Eric Laurentd78f1532014-09-16 16:38:20 -07004020 if ((profileType & inputDeviceTypes) == 0) {
4021 continue;
4022 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08004023 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08004024 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004025
Mikhail Naganov708e0382018-05-30 09:53:04 -07004026 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(profileType);
Eric Laurent53b810e2017-12-10 17:25:10 -08004027 // the inputs vector must be of size >= 1, but we don't want to crash here
4028 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
4029 : String8("");
4030 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
4031 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
4032
Eric Laurentd78f1532014-09-16 16:38:20 -07004033 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004034 status_t status = inputDesc->open(nullptr,
4035 profileType,
Eric Laurent53b810e2017-12-10 17:25:10 -08004036 address,
Eric Laurentfe231122017-11-17 17:48:06 -08004037 AUDIO_SOURCE_MIC,
4038 AUDIO_INPUT_FLAG_NONE,
4039 &input);
Eric Laurentd78f1532014-09-16 16:38:20 -07004040
4041 if (status == NO_ERROR) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004042 for (const auto& dev : inProfile->getSupportedDevices()) {
4043 ssize_t index = mAvailableInputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07004044 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07004045 if (index >= 0) {
4046 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
4047 if (!devDesc->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004048 devDesc->attach(hwModule);
Eric Laurent83efe1c2017-07-09 16:51:08 -07004049 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07004050 }
Eric Laurentd78f1532014-09-16 16:38:20 -07004051 }
4052 }
Eric Laurentfe231122017-11-17 17:48:06 -08004053 inputDesc->close();
Eric Laurentd78f1532014-09-16 16:38:20 -07004054 } else {
4055 ALOGW("Cannot open input stream for device %08x on hw module %s",
Eric Laurentfe231122017-11-17 17:48:06 -08004056 profileType,
Mikhail Naganovd4120142017-12-06 15:49:22 -08004057 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07004058 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004059 }
4060 }
4061 // make sure all attached devices have been allocated a unique ID
4062 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004063 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004064 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004065 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
4066 continue;
4067 }
François Gaffie2110e042015-03-24 08:41:51 +01004068 // The device is now validated and can be appended to the available devices of the engine
4069 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
4070 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004071 i++;
4072 }
4073 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004074 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01004075 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004076 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
4077 continue;
4078 }
François Gaffie2110e042015-03-24 08:41:51 +01004079 // The device is now validated and can be appended to the available devices of the engine
4080 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
4081 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004082 i++;
4083 }
4084 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004085 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01004086 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004087 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004088 }
jiabin9ff780e2018-03-19 18:19:52 -07004089 // If microphones address is empty, set it according to device type
4090 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
4091 if (mAvailableInputDevices[i]->mAddress.isEmpty()) {
4092 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
4093 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
4094 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
4095 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BACK_MICROPHONE_ADDRESS);
4096 }
4097 }
4098 }
Eric Laurente552edb2014-03-10 17:42:56 -07004099
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004100 if (mPrimaryOutput == 0) {
4101 ALOGE("Failed to open primary output");
4102 status = NO_INIT;
4103 }
Eric Laurente552edb2014-03-10 17:42:56 -07004104
4105 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004106 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004107}
4108
Eric Laurente0720872014-03-11 09:30:41 -07004109AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004110{
Eric Laurente552edb2014-03-10 17:42:56 -07004111 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004112 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004113 }
4114 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004115 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004116 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004117 mAvailableOutputDevices.clear();
4118 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004119 mOutputs.clear();
4120 mInputs.clear();
4121 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004122 mHwModulesAll.clear();
jiabin81772902018-04-02 17:52:27 -07004123 mSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004124}
4125
Eric Laurente0720872014-03-11 09:30:41 -07004126status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004127{
Eric Laurent87ffa392015-05-22 10:32:38 -07004128 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004129}
4130
Eric Laurente552edb2014-03-10 17:42:56 -07004131// ---
4132
Eric Laurent98e38192018-02-15 18:31:53 -08004133void AudioPolicyManager::addOutput(audio_io_handle_t output,
4134 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004135{
Eric Laurent1c333e22014-05-20 10:48:17 -07004136 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08004137 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004138 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004139 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004140 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004141}
4142
François Gaffie53615e22015-03-19 09:24:12 +01004143void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4144{
4145 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004146 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004147}
4148
Eric Laurent98e38192018-02-15 18:31:53 -08004149void AudioPolicyManager::addInput(audio_io_handle_t input,
4150 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004151{
Eric Laurent1c333e22014-05-20 10:48:17 -07004152 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004153 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004154}
Eric Laurente552edb2014-03-10 17:42:56 -07004155
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004156void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08004157 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004158 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004159 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08004160 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004161 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08004162 if (devDesc != 0) {
4163 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
4164 desc->mIoHandle, address.string());
4165 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004166 }
4167}
4168
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004169status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004170 audio_policy_dev_state_t state,
4171 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004172 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07004173{
François Gaffie53615e22015-03-19 09:24:12 +01004174 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07004175 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004176
4177 if (audio_device_is_digital(device)) {
4178 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004179 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004180 }
Eric Laurente552edb2014-03-10 17:42:56 -07004181
Eric Laurent3b73df72014-03-11 09:06:29 -07004182 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004183 // first list already open outputs that can be routed to this device
4184 for (size_t i = 0; i < mOutputs.size(); i++) {
4185 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07004186 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004187 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004188 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
4189 outputs.add(mOutputs.keyAt(i));
4190 } else {
4191 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08004192 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004193 }
Eric Laurente552edb2014-03-10 17:42:56 -07004194 }
4195 }
4196 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004197 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004198 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004199 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4200 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004201 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004202 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004203 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004204 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004205 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4206 j, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004207 }
Eric Laurente552edb2014-03-10 17:42:56 -07004208 }
4209 }
4210 }
4211
Eric Laurent7b279bb2015-12-14 10:18:23 -08004212 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004213
Eric Laurente552edb2014-03-10 17:42:56 -07004214 if (profiles.isEmpty() && outputs.isEmpty()) {
4215 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4216 return BAD_VALUE;
4217 }
4218
4219 // open outputs for matching profiles if needed. Direct outputs are also opened to
4220 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4221 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004222 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004223
4224 // nothing to do if one output is already opened for this profile
4225 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004226 for (j = 0; j < outputs.size(); j++) {
4227 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004228 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004229 // matching profile: save the sample rates, format and channel masks supported
4230 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07004231 if (audio_device_is_digital(device)) {
4232 devDesc->importAudioPort(profile);
4233 }
Eric Laurente552edb2014-03-10 17:42:56 -07004234 break;
4235 }
4236 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004237 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004238 continue;
4239 }
4240
Eric Laurent3974e3b2017-12-07 17:58:43 -08004241 if (!profile->canOpenNewIo()) {
4242 ALOGW("Max Output number %u already opened for this profile %s",
4243 profile->maxOpenCount, profile->getTagName().c_str());
4244 continue;
4245 }
4246
Eric Laurent83efe1c2017-07-09 16:51:08 -07004247 ALOGV("opening output for device %08x with params %s profile %p name %s",
4248 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004249 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004250 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004251 status_t status = desc->open(nullptr, device, address,
4252 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004253
Eric Laurentfe231122017-11-17 17:48:06 -08004254 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004255 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004256 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004257 char *param = audio_device_address_to_parameter(device, address);
4258 mpClientInterface->setParameters(output, String8(param));
4259 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004260 }
Phil Burk00eeb322016-03-31 12:41:00 -07004261 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004262 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004263 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004264 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004265 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004266 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004267 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004268 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004269 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4270 profile->pickAudioProfile(
4271 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004272 config.offload_info.sample_rate = config.sample_rate;
4273 config.offload_info.channel_mask = config.channel_mask;
4274 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004275
4276 status_t status = desc->open(&config, device, address, AUDIO_STREAM_DEFAULT,
4277 AUDIO_OUTPUT_FLAG_NONE, &output);
4278 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004279 output = AUDIO_IO_HANDLE_NONE;
4280 }
Eric Laurentd4692962014-05-05 18:13:44 -07004281 }
4282
Eric Laurentcf2c0212014-07-25 16:20:43 -07004283 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004284 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01004285 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004286 sp<AudioPolicyMix> policyMix;
4287 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004288 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
4289 address.string());
4290 }
François Gaffie036e1e92015-03-19 10:16:24 +01004291 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07004292 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01004293
Eric Laurent87ffa392015-05-22 10:32:38 -07004294 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4295 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004296 // no duplicated output for direct outputs and
4297 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004298 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004299
Eric Laurentd4692962014-05-05 18:13:44 -07004300 //TODO: configure audio effect output stage here
4301
4302 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004303 sp<SwAudioOutputDescriptor> dupOutputDesc =
4304 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4305 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4306 &duplicatedOutput);
4307 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004308 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004309 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004310 } else {
4311 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004312 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004313 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004314 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004315 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004316 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004317 }
Eric Laurente552edb2014-03-10 17:42:56 -07004318 }
4319 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004320 } else {
4321 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004322 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004323 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004324 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004325 profiles.removeAt(profile_index);
4326 profile_index--;
4327 } else {
4328 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004329 // Load digital format info only for digital devices
4330 if (audio_device_is_digital(device)) {
4331 devDesc->importAudioPort(profile);
4332 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004333
François Gaffie53615e22015-03-19 09:24:12 +01004334 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004335 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4336 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004337 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004338 NULL/*patch handle*/, address.string());
4339 }
Eric Laurente552edb2014-03-10 17:42:56 -07004340 ALOGV("checkOutputsForDevice(): adding output %d", output);
4341 }
4342 }
4343
4344 if (profiles.isEmpty()) {
4345 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4346 return BAD_VALUE;
4347 }
Eric Laurentd4692962014-05-05 18:13:44 -07004348 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004349 // check if one opened output is not needed any more after disconnecting one device
4350 for (size_t i = 0; i < mOutputs.size(); i++) {
4351 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004352 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004353 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004354 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004355 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004356 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004357 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004358 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4359 mOutputs.keyAt(i));
4360 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004361 }
Eric Laurente552edb2014-03-10 17:42:56 -07004362 }
4363 }
Eric Laurentd4692962014-05-05 18:13:44 -07004364 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004365 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004366 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4367 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004368 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004369 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004370 "clearing direct output profile %zu on module %s",
4371 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004372 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004373 }
4374 }
4375 }
4376 }
4377 return NO_ERROR;
4378}
4379
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004380status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004381 audio_policy_dev_state_t state,
4382 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004383 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004384{
Paul McLean9080a4c2015-06-18 08:24:02 -07004385 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004386 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004387
4388 if (audio_device_is_digital(device)) {
4389 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004390 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004391 }
4392
Eric Laurentd4692962014-05-05 18:13:44 -07004393 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4394 // first list already open inputs that can be routed to this device
4395 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4396 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004397 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004398 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4399 inputs.add(mInputs.keyAt(input_index));
4400 }
4401 }
4402
4403 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004404 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004405 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004406 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004407 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004408 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004409 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004410
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004411 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004412 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004413 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004414 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004415 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4416 profile_index, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004417 }
Eric Laurentd4692962014-05-05 18:13:44 -07004418 }
4419 }
4420 }
4421
4422 if (profiles.isEmpty() && inputs.isEmpty()) {
4423 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4424 return BAD_VALUE;
4425 }
4426
4427 // open inputs for matching profiles if needed. Direct inputs are also opened to
4428 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4429 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4430
Eric Laurent1c333e22014-05-20 10:48:17 -07004431 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004432
Eric Laurentd4692962014-05-05 18:13:44 -07004433 // nothing to do if one input is already opened for this profile
4434 size_t input_index;
4435 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4436 desc = mInputs.valueAt(input_index);
4437 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004438 if (audio_device_is_digital(device)) {
4439 devDesc->importAudioPort(profile);
4440 }
Eric Laurentd4692962014-05-05 18:13:44 -07004441 break;
4442 }
4443 }
4444 if (input_index != mInputs.size()) {
4445 continue;
4446 }
4447
Eric Laurent3974e3b2017-12-07 17:58:43 -08004448 if (!profile->canOpenNewIo()) {
4449 ALOGW("Max Input number %u already opened for this profile %s",
4450 profile->maxOpenCount, profile->getTagName().c_str());
4451 continue;
4452 }
4453
Eric Laurentfe231122017-11-17 17:48:06 -08004454 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004455 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004456 status_t status = desc->open(nullptr,
4457 device,
4458 address,
4459 AUDIO_SOURCE_MIC,
4460 AUDIO_INPUT_FLAG_NONE,
4461 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004462
Eric Laurentcf2c0212014-07-25 16:20:43 -07004463 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004464 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004465 char *param = audio_device_address_to_parameter(device, address);
4466 mpClientInterface->setParameters(input, String8(param));
4467 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004468 }
Phil Burk00eeb322016-03-31 12:41:00 -07004469 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004470 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004471 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004472 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004473 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004474 }
4475
4476 if (input != 0) {
4477 addInput(input, desc);
4478 }
4479 } // endif input != 0
4480
Eric Laurentcf2c0212014-07-25 16:20:43 -07004481 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004482 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004483 profiles.removeAt(profile_index);
4484 profile_index--;
4485 } else {
4486 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004487 if (audio_device_is_digital(device)) {
4488 devDesc->importAudioPort(profile);
4489 }
Eric Laurentd4692962014-05-05 18:13:44 -07004490 ALOGV("checkInputsForDevice(): adding input %d", input);
4491 }
4492 } // end scan profiles
4493
4494 if (profiles.isEmpty()) {
4495 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4496 return BAD_VALUE;
4497 }
4498 } else {
4499 // Disconnect
4500 // check if one opened input is not needed any more after disconnecting one device
4501 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4502 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004503 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004504 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4505 mInputs.keyAt(input_index));
4506 inputs.add(mInputs.keyAt(input_index));
4507 }
4508 }
4509 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004510 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004511 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004512 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004513 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004514 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004515 if (profile->supportDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004516 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4517 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004518 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004519 }
4520 }
4521 }
4522 } // end disconnect
4523
4524 return NO_ERROR;
4525}
4526
4527
Eric Laurente0720872014-03-11 09:30:41 -07004528void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004529{
4530 ALOGV("closeOutput(%d)", output);
4531
Eric Laurentc75307b2015-03-17 15:29:32 -07004532 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004533 if (outputDesc == NULL) {
4534 ALOGW("closeOutput() unknown output %d", output);
4535 return;
4536 }
François Gaffie036e1e92015-03-19 10:16:24 +01004537 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004538
Eric Laurente552edb2014-03-10 17:42:56 -07004539 // look for duplicated outputs connected to the output being removed.
4540 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004541 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004542 if (dupOutputDesc->isDuplicated() &&
4543 (dupOutputDesc->mOutput1 == outputDesc ||
4544 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004545 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004546 if (dupOutputDesc->mOutput1 == outputDesc) {
4547 outputDesc2 = dupOutputDesc->mOutput2;
4548 } else {
4549 outputDesc2 = dupOutputDesc->mOutput1;
4550 }
4551 // As all active tracks on duplicated output will be deleted,
4552 // and as they were also referenced on the other output, the reference
4553 // count for their stream type must be adjusted accordingly on
4554 // the other output.
Andy Hungaf036da2018-09-21 10:46:21 -07004555 const bool wasActive = outputDesc2->isActive();
4556 for (const auto &clientPair : dupOutputDesc->getActiveClients()) {
4557 outputDesc2->changeStreamActiveCount(clientPair.first, -clientPair.second);
Eric Laurente552edb2014-03-10 17:42:56 -07004558 }
Eric Laurent733ce942017-12-07 12:18:25 -08004559 // stop() will be a no op if the output is still active but is needed in case all
4560 // active streams refcounts where cleared above
4561 if (wasActive) {
4562 outputDesc2->stop();
4563 }
Eric Laurente552edb2014-03-10 17:42:56 -07004564 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4565 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4566
4567 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004568 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004569 }
4570 }
4571
Eric Laurent05b90f82014-08-27 15:32:29 -07004572 nextAudioPortGeneration();
4573
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004574 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004575 if (index >= 0) {
4576 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004577 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004578 mAudioPatches.removeItemsAt(index);
4579 mpClientInterface->onAudioPatchListUpdate();
4580 }
4581
Eric Laurentfe231122017-11-17 17:48:06 -08004582 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004583
François Gaffie53615e22015-03-19 09:24:12 +01004584 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004585 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10004586
4587 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
4588 // no direct outputs are open.
4589 if (getMsdAudioOutDeviceTypes() != AUDIO_DEVICE_NONE) {
4590 bool directOutputOpen = false;
4591 for (size_t i = 0; i < mOutputs.size(); i++) {
4592 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
4593 directOutputOpen = true;
4594 break;
4595 }
4596 }
4597 if (!directOutputOpen) {
4598 ALOGV("no direct outputs open, reset MSD patch");
4599 setMsdPatch();
4600 }
4601 }
Eric Laurent05b90f82014-08-27 15:32:29 -07004602}
4603
4604void AudioPolicyManager::closeInput(audio_io_handle_t input)
4605{
4606 ALOGV("closeInput(%d)", input);
4607
4608 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4609 if (inputDesc == NULL) {
4610 ALOGW("closeInput() unknown input %d", input);
4611 return;
4612 }
4613
Eric Laurent6a94d692014-05-20 11:18:06 -07004614 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004615
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004616 audio_devices_t device = inputDesc->mDevice;
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004617 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004618 if (index >= 0) {
4619 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004620 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004621 mAudioPatches.removeItemsAt(index);
4622 mpClientInterface->onAudioPatchListUpdate();
4623 }
4624
Eric Laurentfe231122017-11-17 17:48:06 -08004625 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004626 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004627
4628 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
4629 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
4630 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
4631 SoundTrigger::setCaptureState(false);
4632 }
Eric Laurente552edb2014-03-10 17:42:56 -07004633}
4634
Eric Laurentc75307b2015-03-17 15:29:32 -07004635SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4636 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004637 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004638{
4639 SortedVector<audio_io_handle_t> outputs;
4640
4641 ALOGVV("getOutputsForDevice() device %04x", device);
4642 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004643 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004644 i, openOutputs.valueAt(i)->isDuplicated(),
4645 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004646 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4647 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4648 outputs.add(openOutputs.keyAt(i));
4649 }
4650 }
4651 return outputs;
4652}
4653
Mikhail Naganov37977152018-07-11 15:54:44 -07004654void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
4655{
4656 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
4657 // output is suspended before any tracks are moved to it
4658 checkA2dpSuspend();
4659 checkOutputForAllStrategies();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004660 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07004661 updateDevicesAndOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004662 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
4663 setMsdPatch();
4664 }
Mikhail Naganov37977152018-07-11 15:54:44 -07004665}
4666
Eric Laurente0720872014-03-11 09:30:41 -07004667void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004668{
4669 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4670 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4671 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4672 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4673
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004674 // also take into account external policy-related changes: add all outputs which are
4675 // associated with policies in the "before" and "after" output vectors
4676 ALOGVV("checkOutputForStrategy(): policy related outputs");
4677 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004678 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004679 if (desc != 0 && desc->mPolicyMix != NULL) {
4680 srcOutputs.add(desc->mIoHandle);
4681 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4682 }
4683 }
4684 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004685 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004686 if (desc != 0 && desc->mPolicyMix != NULL) {
4687 dstOutputs.add(desc->mIoHandle);
4688 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4689 }
4690 }
4691
Mikhail Naganov9de8bd12018-07-23 16:41:31 -07004692 if (srcOutputs != dstOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004693 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4694 // audio from invalidated tracks will be rendered when unmuting
4695 uint32_t maxLatency = 0;
4696 for (audio_io_handle_t srcOut : srcOutputs) {
4697 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4698 if (desc != 0 && maxLatency < desc->latency()) {
4699 maxLatency = desc->latency();
4700 }
4701 }
Eric Laurente552edb2014-03-10 17:42:56 -07004702 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4703 strategy, srcOutputs[0], dstOutputs[0]);
4704 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004705 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004706 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4707 if (desc != 0 && isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004708 setStrategyMute(strategy, true, desc);
Eric Laurentac3a6902018-05-11 16:39:10 -07004709 setStrategyMute(strategy, false, desc, maxLatency * LATENCY_MUTE_FACTOR, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004710 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004711 sp<SourceClientDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004712 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004713 if (source != 0){
4714 connectAudioSource(source);
4715 }
Eric Laurente552edb2014-03-10 17:42:56 -07004716 }
4717
4718 // Move effects associated to this strategy from previous output to new output
4719 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004720 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004721 }
4722 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004723 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004724 if (getStrategy((audio_stream_type_t)i) == strategy) {
4725 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004726 }
4727 }
4728 }
4729}
4730
Eric Laurente0720872014-03-11 09:30:41 -07004731void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004732{
François Gaffie2110e042015-03-24 08:41:51 +01004733 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004734 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004735 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004736 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004737 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004738 checkOutputForStrategy(STRATEGY_SONIFICATION);
4739 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004740 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004741 checkOutputForStrategy(STRATEGY_MEDIA);
4742 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004743 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004744}
4745
Eric Laurente0720872014-03-11 09:30:41 -07004746void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004747{
François Gaffie53615e22015-03-19 09:24:12 +01004748 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004749 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004750 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004751 return;
4752 }
4753
Eric Laurent3a4311c2014-03-17 12:00:47 -07004754 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004755 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4756 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4757 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004758
4759 // if suspended, restore A2DP output if:
4760 // ((SCO device is NOT connected) ||
4761 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4762 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004763 //
Eric Laurentf732e072016-08-03 19:30:28 -07004764 // if not suspended, suspend A2DP output if:
4765 // (SCO device is connected) &&
4766 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4767 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004768 //
4769 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004770 if (!isScoConnected ||
4771 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4772 AUDIO_POLICY_FORCE_BT_SCO) &&
4773 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4774 AUDIO_POLICY_FORCE_BT_SCO) &&
4775 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004776 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004777
4778 mpClientInterface->restoreOutput(a2dpOutput);
4779 mA2dpSuspended = false;
4780 }
4781 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004782 if (isScoConnected &&
4783 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4784 AUDIO_POLICY_FORCE_BT_SCO) ||
4785 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4786 AUDIO_POLICY_FORCE_BT_SCO) ||
4787 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004788 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004789
4790 mpClientInterface->suspendOutput(a2dpOutput);
4791 mA2dpSuspended = true;
4792 }
4793 }
4794}
4795
Eric Laurent97ac8712018-07-27 18:59:02 -07004796template <class IoDescriptor, class Filter>
4797sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4798 IoDescriptor& desc, Filter filter, bool& active, const DeviceVector& devices)
4799{
4800 auto activeClients = desc->clientsList(true /*activeOnly*/);
4801 auto activeClientsWithRoute =
4802 desc->clientsList(true /*activeOnly*/, filter, true /*preferredDevice*/);
4803 active = activeClients.size() > 0;
4804 if (active && activeClients.size() == activeClientsWithRoute.size()) {
4805 return devices.getDeviceFromId(activeClientsWithRoute[0]->preferredDeviceId());
4806 }
4807 return nullptr;
4808}
4809
4810template <class IoCollection, class Filter>
4811sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4812 IoCollection& ioCollection, Filter filter, const DeviceVector& devices)
4813{
4814 sp<DeviceDescriptor> device;
4815 for (size_t i = 0; i < ioCollection.size(); i++) {
4816 auto desc = ioCollection.valueAt(i);
4817 bool active;
4818 sp<DeviceDescriptor> curDevice = findPreferredDevice(desc, filter, active, devices);
4819 if (active && curDevice == nullptr) {
4820 return nullptr;
4821 } else if (curDevice != nullptr) {
4822 device = curDevice;
4823 }
4824 }
4825 return device;
4826}
4827
Eric Laurentc75307b2015-03-17 15:29:32 -07004828audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4829 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004830{
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004831 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004832 if (index >= 0) {
4833 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4834 if (patchDesc->mUid != mUidCached) {
4835 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004836 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004837 return outputDesc->device();
4838 }
4839 }
4840
Eric Laurent97ac8712018-07-27 18:59:02 -07004841 // Honor explicit routing requests only if no client using default routing is active on this
4842 // input: a specific app can not force routing for other apps by setting a preferred device.
4843 bool active; // unused
4844 sp<DeviceDescriptor> deviceDesc =
4845 findPreferredDevice(outputDesc, STRATEGY_NONE, active, mAvailableOutputDevices);
4846 if (deviceDesc != nullptr) {
4847 return deviceDesc->type();
Eric Laurentf3a5a602018-05-22 18:42:55 -07004848 }
4849
Eric Laurente552edb2014-03-10 17:42:56 -07004850 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004851 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004852 // use device for strategy enforced audible
4853 // 2: we are in call or the strategy phone is active on the output:
4854 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004855 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004856 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004857 // 4: the strategy for enforced audible is active but not enforced on the output:
4858 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004859 // 5: the strategy accessibility is active on the output:
4860 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004861 // 6: the strategy "respectful" sonification is active on the output:
4862 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004863 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004864 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004865 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004866 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004867 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004868 // use device for strategy t-t-s
Eric Laurent484e9272018-06-07 17:29:23 -07004869
4870 // FIXME: extend use of isStrategyActiveOnSameModule() to all strategies
4871 // with a refined rule considering mutually exclusive devices (using same backend)
4872 // as opposed to all streams on the same audio HAL module.
Eric Laurent97ac8712018-07-27 18:59:02 -07004873 audio_devices_t device = AUDIO_DEVICE_NONE;
François Gaffiead3183e2015-03-18 16:55:35 +01004874 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004875 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004876 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4877 } else if (isInCall() ||
Eric Laurent484e9272018-06-07 17:29:23 -07004878 isStrategyActiveOnSameModule(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004879 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
Yung Ti Su3e7eb5e2018-06-13 11:48:42 +08004880 } else if (isStrategyActiveOnSameModule(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004881 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004882 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
4883 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004884 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4885 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004886 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004887 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004888 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004889 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004890 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004891 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004892 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004893 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004894 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004895 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004896 }
4897
Eric Laurent1c333e22014-05-20 10:48:17 -07004898 ALOGV("getNewOutputDevice() selected device %x", device);
4899 return device;
4900}
4901
Eric Laurentfb66dd92016-01-28 18:32:03 -08004902audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004903{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004904 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004905
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004906 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004907 if (index >= 0) {
4908 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4909 if (patchDesc->mUid != mUidCached) {
4910 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004911 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004912 return inputDesc->mDevice;
4913 }
4914 }
4915
Eric Laurent97ac8712018-07-27 18:59:02 -07004916 // Honor explicit routing requests only if no client using default routing is active on this
4917 // input: a specific app can not force routing for other apps by setting a preferred device.
4918 bool active;
4919 sp<DeviceDescriptor> deviceDesc =
4920 findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
4921 if (deviceDesc != nullptr) {
4922 return deviceDesc->type();
4923 }
4924
Eric Laurentdc95a252018-04-12 12:46:56 -07004925 // If we are not in call and no client is active on this input, this methods returns
4926 // AUDIO_DEVICE_NONE, causing the patch on the input stream to be released.
Eric Laurentfb66dd92016-01-28 18:32:03 -08004927 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
Eric Laurentdc95a252018-04-12 12:46:56 -07004928 if (source == AUDIO_SOURCE_DEFAULT && isInCall()) {
4929 source = AUDIO_SOURCE_VOICE_COMMUNICATION;
4930 }
4931 if (source != AUDIO_SOURCE_DEFAULT) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08004932 device = getDeviceAndMixForInputSource(source);
4933 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004934
Eric Laurente552edb2014-03-10 17:42:56 -07004935 return device;
4936}
4937
Eric Laurent794fde22016-03-11 09:50:45 -08004938bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4939 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004940 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004941}
4942
Eric Laurente0720872014-03-11 09:30:41 -07004943uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004944 return (uint32_t)getStrategy(stream);
4945}
4946
Eric Laurente0720872014-03-11 09:30:41 -07004947audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004948 // By checking the range of stream before calling getStrategy, we avoid
4949 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4950 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004951 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004952 return AUDIO_DEVICE_NONE;
4953 }
Eric Laurentb0688d62018-08-14 15:49:18 -07004954 audio_devices_t activeDevices = AUDIO_DEVICE_NONE;
Eric Laurent28d09f02016-03-08 10:43:05 -08004955 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004956 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4957 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004958 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004959 }
Eric Laurent794fde22016-03-11 09:50:45 -08004960 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004961 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004962 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Eric Laurentb0688d62018-08-14 15:49:18 -07004963 devices |= curDevices;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004964 for (audio_io_handle_t output : getOutputsForDevice(curDevices, mOutputs)) {
4965 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08004966 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurentb0688d62018-08-14 15:49:18 -07004967 activeDevices |= outputDesc->device();
Eric Laurent28d09f02016-03-08 10:43:05 -08004968 }
4969 }
Eric Laurente552edb2014-03-10 17:42:56 -07004970 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004971
Eric Laurentb0688d62018-08-14 15:49:18 -07004972 // Favor devices selected on active streams if any to report correct device in case of
4973 // explicit device selection
4974 if (activeDevices != AUDIO_DEVICE_NONE) {
4975 devices = activeDevices;
4976 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004977 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4978 and doesn't really need to.*/
4979 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4980 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4981 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4982 }
Eric Laurente552edb2014-03-10 17:42:56 -07004983 return devices;
4984}
4985
François Gaffie2110e042015-03-24 08:41:51 +01004986routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4987{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004988 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004989 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004990}
4991
Eric Laurent97ac8712018-07-27 18:59:02 -07004992routing_strategy AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004993 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004994 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004995 return STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004996 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004997 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004998 return STRATEGY_ENFORCED_AUDIBLE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004999 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005000 // usage to strategy mapping
Eric Laurent97ac8712018-07-27 18:59:02 -07005001 return mEngine->getStrategyForUsage(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005002}
5003
Eric Laurente0720872014-03-11 09:30:41 -07005004void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005005 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005006 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07005007 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
5008 updateDevicesAndOutputs();
5009 break;
5010 default:
5011 break;
5012 }
5013}
5014
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005015uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07005016
5017 // skip beacon mute management if a dedicated TTS output is available
5018 if (mTtsOutputAvailable) {
5019 return 0;
5020 }
5021
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005022 switch(event) {
5023 case STARTING_OUTPUT:
5024 mBeaconMuteRefCount++;
5025 break;
5026 case STOPPING_OUTPUT:
5027 if (mBeaconMuteRefCount > 0) {
5028 mBeaconMuteRefCount--;
5029 }
5030 break;
5031 case STARTING_BEACON:
5032 mBeaconPlayingRefCount++;
5033 break;
5034 case STOPPING_BEACON:
5035 if (mBeaconPlayingRefCount > 0) {
5036 mBeaconPlayingRefCount--;
5037 }
5038 break;
5039 }
5040
5041 if (mBeaconMuteRefCount > 0) {
5042 // any playback causes beacon to be muted
5043 return setBeaconMute(true);
5044 } else {
5045 // no other playback: unmute when beacon starts playing, mute when it stops
5046 return setBeaconMute(mBeaconPlayingRefCount == 0);
5047 }
5048}
5049
5050uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5051 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5052 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5053 // keep track of muted state to avoid repeating mute/unmute operations
5054 if (mBeaconMuted != mute) {
5055 // mute/unmute AUDIO_STREAM_TTS on all outputs
5056 ALOGV("\t muting %d", mute);
5057 uint32_t maxLatency = 0;
5058 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005059 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005060 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07005061 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005062 0 /*delay*/, AUDIO_DEVICE_NONE);
5063 const uint32_t latency = desc->latency() * 2;
5064 if (latency > maxLatency) {
5065 maxLatency = latency;
5066 }
5067 }
5068 mBeaconMuted = mute;
5069 return maxLatency;
5070 }
5071 return 0;
5072}
5073
Eric Laurente0720872014-03-11 09:30:41 -07005074audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01005075 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005076{
Eric Laurent97ac8712018-07-27 18:59:02 -07005077 // Honor explicit routing requests only if all active clients have a preferred route in which
5078 // case the last active client route is used
5079 sp<DeviceDescriptor> deviceDesc = findPreferredDevice(mOutputs, strategy, mAvailableOutputDevices);
5080 if (deviceDesc != nullptr) {
5081 return deviceDesc->type();
Paul McLeanaa981192015-03-21 09:55:15 -07005082 }
5083
Eric Laurente552edb2014-03-10 17:42:56 -07005084 if (fromCache) {
5085 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
5086 strategy, mDeviceForStrategy[strategy]);
5087 return mDeviceForStrategy[strategy];
5088 }
François Gaffie2110e042015-03-24 08:41:51 +01005089 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07005090}
5091
Eric Laurente0720872014-03-11 09:30:41 -07005092void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005093{
5094 for (int i = 0; i < NUM_STRATEGIES; i++) {
5095 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
5096 }
5097 mPreviousOutputs = mOutputs;
5098}
5099
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005100uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005101 audio_devices_t prevDevice,
5102 uint32_t delayMs)
5103{
5104 // mute/unmute strategies using an incompatible device combination
5105 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5106 // if unmuting, unmute only after the specified delay
5107 if (outputDesc->isDuplicated()) {
5108 return 0;
5109 }
5110
5111 uint32_t muteWaitMs = 0;
5112 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07005113 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005114
5115 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
5116 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07005117 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07005118 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
5119 bool doMute = false;
5120
5121 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
5122 doMute = true;
5123 outputDesc->mStrategyMutedByDevice[i] = true;
5124 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
5125 doMute = true;
5126 outputDesc->mStrategyMutedByDevice[i] = false;
5127 }
Eric Laurent99401132014-05-07 19:48:15 -07005128 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005129 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005130 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005131 // skip output if it does not share any device with current output
5132 if ((desc->supportedDevices() & outputDesc->supportedDevices())
5133 == AUDIO_DEVICE_NONE) {
5134 continue;
5135 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005136 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07005137 mute ? "muting" : "unmuting", i, curDevice);
5138 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005139 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005140 if (mute) {
5141 // FIXME: should not need to double latency if volume could be applied
5142 // immediately by the audioflinger mixer. We must account for the delay
5143 // between now and the next time the audioflinger thread for this output
5144 // will process a buffer (which corresponds to one buffer size,
5145 // usually 1/2 or 1/4 of the latency).
5146 if (muteWaitMs < desc->latency() * 2) {
5147 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005148 }
5149 }
5150 }
5151 }
5152 }
5153 }
5154
Eric Laurent99401132014-05-07 19:48:15 -07005155 // temporary mute output if device selection changes to avoid volume bursts due to
5156 // different per device volumes
5157 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005158 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5159 // temporary mute duration is conservatively set to 4 times the reported latency
5160 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5161 if (muteWaitMs < tempMuteWaitMs) {
5162 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005163 }
Eric Laurentdc462862016-07-19 12:29:53 -07005164
Eric Laurent99401132014-05-07 19:48:15 -07005165 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005166 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005167 // make sure that we do not start the temporary mute period too early in case of
5168 // delayed device change
5169 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005170 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07005171 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07005172 }
5173 }
5174 }
5175
Eric Laurente552edb2014-03-10 17:42:56 -07005176 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5177 if (muteWaitMs > delayMs) {
5178 muteWaitMs -= delayMs;
5179 usleep(muteWaitMs * 1000);
5180 return muteWaitMs;
5181 }
5182 return 0;
5183}
5184
Eric Laurentc75307b2015-03-17 15:29:32 -07005185uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005186 audio_devices_t device,
5187 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07005188 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005189 audio_patch_handle_t *patchHandle,
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005190 const char *address,
5191 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005192{
Eric Laurentc75307b2015-03-17 15:29:32 -07005193 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005194 AudioParameter param;
5195 uint32_t muteWaitMs;
5196
5197 if (outputDesc->isDuplicated()) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005198 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs,
5199 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
5200 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs,
5201 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005202 return muteWaitMs;
5203 }
5204 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5205 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07005206 if ((device != AUDIO_DEVICE_NONE) &&
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005207 ((device & outputDesc->supportedDevices()) == AUDIO_DEVICE_NONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005208 return 0;
5209 }
5210
5211 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07005212 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07005213
5214 audio_devices_t prevDevice = outputDesc->mDevice;
5215
Paul McLeanaa981192015-03-21 09:55:15 -07005216 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005217
5218 if (device != AUDIO_DEVICE_NONE) {
5219 outputDesc->mDevice = device;
5220 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005221
5222 // if the outputs are not materially active, there is no need to mute.
5223 if (requiresMuteCheck) {
5224 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
5225 } else {
5226 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5227 muteWaitMs = 0;
5228 }
Eric Laurente552edb2014-03-10 17:42:56 -07005229
5230 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005231 // the requested device is AUDIO_DEVICE_NONE
5232 // OR the requested device is the same as current device
5233 // AND force is not specified
5234 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07005235 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07005236 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
5237 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005238 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005239 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005240 return muteWaitMs;
5241 }
5242
5243 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07005244
Eric Laurente552edb2014-03-10 17:42:56 -07005245 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07005246 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005247 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005248 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07005249 DeviceVector deviceList;
5250 if ((address == NULL) || (strlen(address) == 0)) {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005251 deviceList = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurentc40d9692016-04-13 19:14:13 -07005252 } else {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005253 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
5254 device, String8(address));
5255 if (deviceDesc) deviceList.add(deviceDesc);
Eric Laurentc40d9692016-04-13 19:14:13 -07005256 }
5257
Eric Laurent1c333e22014-05-20 10:48:17 -07005258 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005259 PatchBuilder patchBuilder;
5260 patchBuilder.addSource(outputDesc);
Eric Laurent1c333e22014-05-20 10:48:17 -07005261 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005262 patchBuilder.addSink(deviceList.itemAt(i));
Eric Laurent1c333e22014-05-20 10:48:17 -07005263 }
Mikhail Naganovdc769682018-05-04 15:34:08 -07005264 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005265 }
bryant_liuf5e7e792014-08-19 20:07:05 +08005266
5267 // inform all input as well
5268 for (size_t i = 0; i < mInputs.size(); i++) {
5269 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01005270 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08005271 AudioParameter inputCmd = AudioParameter();
5272 ALOGV("%s: inform input %d of device:%d", __func__,
5273 inputDescriptor->mIoHandle, device);
5274 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
5275 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
5276 inputCmd.toString(),
5277 delayMs);
5278 }
5279 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005280 }
Eric Laurente552edb2014-03-10 17:42:56 -07005281
5282 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07005283 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005284
5285 return muteWaitMs;
5286}
5287
Eric Laurentc75307b2015-03-17 15:29:32 -07005288status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005289 int delayMs,
5290 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005291{
Eric Laurent6a94d692014-05-20 11:18:06 -07005292 ssize_t index;
5293 if (patchHandle) {
5294 index = mAudioPatches.indexOfKey(*patchHandle);
5295 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005296 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005297 }
5298 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005299 return INVALID_OPERATION;
5300 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005301 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5302 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005303 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005304 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005305 removeAudioPatch(patchDesc->mHandle);
5306 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005307 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005308 return status;
5309}
5310
5311status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5312 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005313 bool force,
5314 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005315{
5316 status_t status = NO_ERROR;
5317
Eric Laurent1f2f2232014-06-02 12:01:23 -07005318 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005319 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5320 inputDesc->mDevice = device;
5321
Mikhail Naganov708e0382018-05-30 09:53:04 -07005322 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005323 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005324 PatchBuilder patchBuilder;
5325 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005326 // AUDIO_SOURCE_HOTWORD is for internal use only:
5327 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07005328 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5329 auto result = usecase;
5330 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5331 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5332 }
5333 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07005334 //only one input device for now
Mikhail Naganovdc769682018-05-04 15:34:08 -07005335 addSource(deviceList.itemAt(0));
5336 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005337 }
5338 }
5339 return status;
5340}
5341
Eric Laurent6a94d692014-05-20 11:18:06 -07005342status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5343 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005344{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005345 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005346 ssize_t index;
5347 if (patchHandle) {
5348 index = mAudioPatches.indexOfKey(*patchHandle);
5349 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005350 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005351 }
5352 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005353 return INVALID_OPERATION;
5354 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005355 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5356 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005357 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005358 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005359 removeAudioPatch(patchDesc->mHandle);
5360 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005361 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005362 return status;
5363}
5364
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005365sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005366 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005367 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005368 audio_format_t& format,
5369 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005370 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005371{
5372 // Choose an input profile based on the requested capture parameters: select the first available
5373 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005374 //
5375 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5376 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005377
Glenn Kasten730b9262018-03-29 15:01:26 -07005378 sp<IOProfile> firstInexact;
5379 uint32_t updatedSamplingRate = 0;
5380 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5381 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005382 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005383 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005384 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005385 //updatedFormat = format;
Eric Laurent275e8e92014-11-30 15:14:47 -08005386 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005387 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005388 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005389 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005390 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005391 &channelMask /*updatedChannelMask*/,
5392 // FIXME ugly cast
5393 (audio_output_flags_t) flags,
5394 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005395 return profile;
5396 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005397 if (firstInexact == nullptr && profile->isCompatibleProfile(device, address,
5398 samplingRate,
5399 &updatedSamplingRate,
5400 format,
5401 &updatedFormat,
5402 channelMask,
5403 &updatedChannelMask,
5404 // FIXME ugly cast
5405 (audio_output_flags_t) flags,
5406 false /*exactMatchRequiredForInputFlags*/)) {
5407 firstInexact = profile;
5408 }
5409
Eric Laurente552edb2014-03-10 17:42:56 -07005410 }
5411 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005412 if (firstInexact != nullptr) {
5413 samplingRate = updatedSamplingRate;
5414 format = updatedFormat;
5415 channelMask = updatedChannelMask;
5416 return firstInexact;
5417 }
Eric Laurente552edb2014-03-10 17:42:56 -07005418 return NULL;
5419}
5420
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005421
5422audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005423 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005424{
Eric Laurent97ac8712018-07-27 18:59:02 -07005425 // Honor explicit routing requests only if all active clients have a preferred route in which
5426 // case the last active client route is used
5427 sp<DeviceDescriptor> deviceDesc =
5428 findPreferredDevice(mInputs, inputSource, mAvailableInputDevices);
5429 if (deviceDesc != nullptr) {
5430 return deviceDesc->type();
5431 }
5432
5433
François Gaffie036e1e92015-03-19 10:16:24 +01005434 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5435 audio_devices_t selectedDeviceFromMix =
5436 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005437
François Gaffie036e1e92015-03-19 10:16:24 +01005438 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5439 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005440 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005441 return getDeviceForInputSource(inputSource);
5442}
5443
5444audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5445{
Eric Laurent97ac8712018-07-27 18:59:02 -07005446 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005447}
5448
Eric Laurente0720872014-03-11 09:30:41 -07005449float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005450 int index,
5451 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005452{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005453 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005454
5455 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5456 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5457 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5458 // the ringtone volume
5459 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5460 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5461 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5462 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5463 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5464 }
5465
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005466 // in-call: always cap volume by voice volume + some low headroom
5467 if ((stream != AUDIO_STREAM_VOICE_CALL) &&
Eric Laurent7731b5a2018-04-06 15:47:22 -07005468 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005469 switch (stream) {
5470 case AUDIO_STREAM_SYSTEM:
5471 case AUDIO_STREAM_RING:
5472 case AUDIO_STREAM_MUSIC:
5473 case AUDIO_STREAM_ALARM:
5474 case AUDIO_STREAM_NOTIFICATION:
5475 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5476 case AUDIO_STREAM_DTMF:
5477 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005478 int voiceVolumeIndex =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005479 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, device);
Eric Laurent7731b5a2018-04-06 15:47:22 -07005480 const float maxVoiceVolDb =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005481 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, device)
Eric Laurent7731b5a2018-04-06 15:47:22 -07005482 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005483 if (volumeDB > maxVoiceVolDb) {
5484 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5485 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5486 volumeDB = maxVoiceVolDb;
5487 }
5488 } break;
5489 default:
5490 break;
5491 }
5492 }
5493
Eric Laurente552edb2014-03-10 17:42:56 -07005494 // if a headset is connected, apply the following rules to ring tones and notifications
5495 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005496 // - always attenuate notifications volume by 6dB
5497 // - attenuate ring tones volume by 6dB unless music is not playing and
5498 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005499 // - if music is playing, always limit the volume to current music volume,
5500 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005501 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005502 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5503 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5504 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005505 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005506 AUDIO_DEVICE_OUT_USB_HEADSET |
5507 AUDIO_DEVICE_OUT_HEARING_AID)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005508 ((stream_strategy == STRATEGY_SONIFICATION)
5509 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005510 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005511 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005512 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005513 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005514 // when the phone is ringing we must consider that music could have been paused just before
5515 // by the music application and behave as if music was active if the last music track was
5516 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005517 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005518 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005519 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005520 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005521 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005522 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5523 musicDevice),
5524 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005525 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5526 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005527 if (volumeDB > minVolDB) {
5528 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005529 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005530 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005531 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5532 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5533 // on A2DP, also ensure notification volume is not too low compared to media when
5534 // intended to be played
5535 if ((volumeDB > -96.0f) &&
5536 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5537 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5538 stream, device,
5539 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5540 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5541 }
5542 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005543 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5544 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005545 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005546 }
5547 }
5548
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005549 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005550}
5551
Eric Laurent3839bc02018-07-10 18:33:34 -07005552int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
5553 audio_stream_type_t srcStream,
5554 audio_stream_type_t dstStream)
5555{
5556 if (srcStream == dstStream) {
5557 return srcIndex;
5558 }
5559 float minSrc = (float)mVolumeCurves->getVolumeIndexMin(srcStream);
5560 float maxSrc = (float)mVolumeCurves->getVolumeIndexMax(srcStream);
5561 float minDst = (float)mVolumeCurves->getVolumeIndexMin(dstStream);
5562 float maxDst = (float)mVolumeCurves->getVolumeIndexMax(dstStream);
5563
5564 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
5565}
5566
Eric Laurente0720872014-03-11 09:30:41 -07005567status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005568 int index,
5569 const sp<AudioOutputDescriptor>& outputDesc,
5570 audio_devices_t device,
5571 int delayMs,
5572 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005573{
Eric Laurente552edb2014-03-10 17:42:56 -07005574 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005575 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005576 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005577 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005578 return NO_ERROR;
5579 }
François Gaffie2110e042015-03-24 08:41:51 +01005580 audio_policy_forced_cfg_t forceUseForComm =
5581 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005582 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005583 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5584 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005585 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005586 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005587 return INVALID_OPERATION;
5588 }
5589
Eric Laurentc75307b2015-03-17 15:29:32 -07005590 if (device == AUDIO_DEVICE_NONE) {
5591 device = outputDesc->device();
5592 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005593
Eric Laurentffbc80f2015-03-18 18:30:19 -07005594 float volumeDb = computeVolume(stream, index, device);
HW Leeda7581e2018-05-22 18:31:34 +08005595 if (outputDesc->isFixedVolume(device) ||
5596 // Force VoIP volume to max for bluetooth SCO
5597 ((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
5598 (device & AUDIO_DEVICE_OUT_ALL_SCO) != 0)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005599 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005600 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005601
Eric Laurentffbc80f2015-03-18 18:30:19 -07005602 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005603
Eric Laurent3b73df72014-03-11 09:06:29 -07005604 if (stream == AUDIO_STREAM_VOICE_CALL ||
5605 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005606 float voiceVolume;
5607 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005608 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurent3839bc02018-07-10 18:33:34 -07005609 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005610 } else {
5611 voiceVolume = 1.0;
5612 }
5613
Eric Laurent18fba842016-03-31 14:41:26 -07005614 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005615 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5616 mLastVoiceVolume = voiceVolume;
5617 }
5618 }
5619
5620 return NO_ERROR;
5621}
5622
Eric Laurentc75307b2015-03-17 15:29:32 -07005623void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5624 audio_devices_t device,
5625 int delayMs,
5626 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005627{
Eric Laurentc75307b2015-03-17 15:29:32 -07005628 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005629
Eric Laurent794fde22016-03-11 09:50:45 -08005630 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005631 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005632 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005633 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005634 device,
5635 delayMs,
5636 force);
5637 }
5638}
5639
Eric Laurente0720872014-03-11 09:30:41 -07005640void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005641 bool on,
5642 const sp<AudioOutputDescriptor>& outputDesc,
5643 int delayMs,
5644 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005645{
Eric Laurent72249d52015-06-08 11:12:15 -07005646 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5647 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005648 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005649 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005650 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005651 }
5652 }
5653}
5654
Eric Laurente0720872014-03-11 09:30:41 -07005655void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005656 bool on,
5657 const sp<AudioOutputDescriptor>& outputDesc,
5658 int delayMs,
5659 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005660{
Eric Laurente552edb2014-03-10 17:42:56 -07005661 if (device == AUDIO_DEVICE_NONE) {
5662 device = outputDesc->device();
5663 }
5664
Eric Laurentc75307b2015-03-17 15:29:32 -07005665 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5666 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005667
5668 if (on) {
5669 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005670 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005671 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005672 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005673 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005674 }
5675 }
5676 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5677 outputDesc->mMuteCount[stream]++;
5678 } else {
5679 if (outputDesc->mMuteCount[stream] == 0) {
5680 ALOGV("setStreamMute() unmuting non muted stream!");
5681 return;
5682 }
5683 if (--outputDesc->mMuteCount[stream] == 0) {
5684 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005685 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005686 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005687 device,
5688 delayMs);
5689 }
5690 }
5691}
5692
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005693audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5694{
5695 // flags to stream type mapping
5696 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5697 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5698 }
5699 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5700 return AUDIO_STREAM_BLUETOOTH_SCO;
5701 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005702 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5703 return AUDIO_STREAM_TTS;
5704 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005705
Ari Hausman-Cohen5c00d012018-06-26 17:09:11 -07005706 return audio_usage_to_stream_type(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005707}
Eric Laurente83b55d2014-11-14 10:06:21 -08005708
François Gaffie53615e22015-03-19 09:24:12 +01005709bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5710{
Eric Laurente83b55d2014-11-14 10:06:21 -08005711 // has flags that map to a strategy?
5712 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5713 return true;
5714 }
5715
5716 // has known usage?
5717 switch (paa->usage) {
5718 case AUDIO_USAGE_UNKNOWN:
5719 case AUDIO_USAGE_MEDIA:
5720 case AUDIO_USAGE_VOICE_COMMUNICATION:
5721 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5722 case AUDIO_USAGE_ALARM:
5723 case AUDIO_USAGE_NOTIFICATION:
5724 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5725 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5726 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5727 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5728 case AUDIO_USAGE_NOTIFICATION_EVENT:
5729 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5730 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5731 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5732 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005733 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005734 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005735 break;
5736 default:
5737 return false;
5738 }
5739 return true;
5740}
5741
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005742bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005743 routing_strategy strategy, uint32_t inPastMs,
5744 nsecs_t sysTime) const
5745{
5746 if ((sysTime == 0) && (inPastMs != 0)) {
5747 sysTime = systemTime();
5748 }
Eric Laurent794fde22016-03-11 09:50:45 -08005749 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005750 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurent97ac8712018-07-27 18:59:02 -07005751 (STRATEGY_NONE == strategy)) &&
François Gaffiead3183e2015-03-18 16:55:35 +01005752 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5753 return true;
5754 }
5755 }
5756 return false;
5757}
5758
Eric Laurent484e9272018-06-07 17:29:23 -07005759bool AudioPolicyManager::isStrategyActiveOnSameModule(const sp<AudioOutputDescriptor>& outputDesc,
5760 routing_strategy strategy, uint32_t inPastMs,
5761 nsecs_t sysTime) const
5762{
5763 for (size_t i = 0; i < mOutputs.size(); i++) {
5764 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5765 if (outputDesc->sharesHwModuleWith(desc)
5766 && isStrategyActive(desc, strategy, inPastMs, sysTime)) {
5767 return true;
5768 }
5769 }
5770 return false;
5771}
5772
François Gaffie2110e042015-03-24 08:41:51 +01005773audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5774{
5775 return mEngine->getForceUse(usage);
5776}
5777
5778bool AudioPolicyManager::isInCall()
5779{
5780 return isStateInCall(mEngine->getPhoneState());
5781}
5782
5783bool AudioPolicyManager::isStateInCall(int state)
5784{
5785 return is_state_in_call(state);
5786}
5787
Eric Laurentd60560a2015-04-10 11:31:20 -07005788void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5789{
5790 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005791 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5792 if (sourceDesc->srcDevice()->equals(deviceDesc)) {
5793 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->portId());
5794 stopAudioSource(sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005795 }
5796 }
5797
5798 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5799 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5800 bool release = false;
5801 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5802 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5803 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5804 source->ext.device.type == deviceDesc->type()) {
5805 release = true;
5806 }
5807 }
5808 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5809 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5810 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5811 sink->ext.device.type == deviceDesc->type()) {
5812 release = true;
5813 }
5814 }
5815 if (release) {
5816 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5817 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5818 }
5819 }
5820}
5821
Phil Burk09bc4612016-02-24 15:58:15 -08005822// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005823void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5824 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005825 // TODO Set this based on Config properties.
5826 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005827
5828 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5829 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005830 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005831
jiabin81772902018-04-02 17:52:27 -07005832 // If MANUAL, keep the supported surround sound formats as current enabled ones.
5833 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
5834 formats.clear();
5835 for (auto it = mSurroundFormats.begin(); it != mSurroundFormats.end(); it++) {
5836 formats.add(*it);
Phil Burk09bc4612016-02-24 15:58:15 -08005837 }
jiabin81772902018-04-02 17:52:27 -07005838 // Always enable IEC61937 when in MANUAL mode.
5839 formats.add(AUDIO_FORMAT_IEC61937);
5840 } else { // NEVER, AUTO or ALWAYS
5841 // Analyze original support for various formats.
5842 bool supportsAC3 = false;
5843 bool supportsOtherSurround = false;
5844 bool supportsIEC61937 = false;
5845 mSurroundFormats.clear();
5846 for (ssize_t formatIndex = 0; formatIndex < (ssize_t)formats.size(); formatIndex++) {
5847 audio_format_t format = formats[formatIndex];
5848 switch (format) {
5849 case AUDIO_FORMAT_AC3:
5850 supportsAC3 = true;
5851 break;
5852 case AUDIO_FORMAT_E_AC3:
5853 case AUDIO_FORMAT_DTS:
5854 case AUDIO_FORMAT_DTS_HD:
5855 // If ALWAYS, remove all other surround formats here
5856 // since we will add them later.
5857 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5858 formats.removeAt(formatIndex);
5859 formatIndex--;
5860 }
5861 supportsOtherSurround = true;
5862 break;
5863 case AUDIO_FORMAT_IEC61937:
5864 supportsIEC61937 = true;
5865 break;
5866 default:
5867 break;
5868 }
5869 }
Phil Burk09bc4612016-02-24 15:58:15 -08005870
jiabin81772902018-04-02 17:52:27 -07005871 // Modify formats based on surround preferences.
5872 // If NEVER, remove support for surround formats.
5873 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5874 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5875 // Remove surround sound related formats.
5876 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5877 audio_format_t format = formats[formatIndex];
5878 switch(format) {
5879 case AUDIO_FORMAT_AC3:
5880 case AUDIO_FORMAT_E_AC3:
5881 case AUDIO_FORMAT_DTS:
5882 case AUDIO_FORMAT_DTS_HD:
5883 case AUDIO_FORMAT_IEC61937:
5884 formats.removeAt(formatIndex);
5885 break;
5886 default:
5887 formatIndex++; // keep it
5888 break;
5889 }
5890 }
5891 supportsAC3 = false;
5892 supportsOtherSurround = false;
5893 supportsIEC61937 = false;
5894 }
5895 } else { // AUTO or ALWAYS
5896 // Most TVs support AC3 even if they do not report it in the EDID.
5897 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
5898 && !supportsAC3) {
5899 formats.add(AUDIO_FORMAT_AC3);
5900 supportsAC3 = true;
5901 }
5902
5903 // If ALWAYS, add support for raw surround formats if all are missing.
5904 // This assumes that if any of these formats are reported by the HAL
5905 // then the report is valid and should not be modified.
5906 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5907 formats.add(AUDIO_FORMAT_E_AC3);
5908 formats.add(AUDIO_FORMAT_DTS);
5909 formats.add(AUDIO_FORMAT_DTS_HD);
5910 supportsOtherSurround = true;
5911 }
5912
5913 // Add support for IEC61937 if any raw surround supported.
5914 // The HAL could do this but add it here, just in case.
5915 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
5916 formats.add(AUDIO_FORMAT_IEC61937);
5917 supportsIEC61937 = true;
5918 }
5919
5920 // Add reported surround sound formats to enabled surround formats.
5921 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
Phil Burk07ac1142016-03-25 13:39:29 -07005922 audio_format_t format = formats[formatIndex];
5923 switch(format) {
5924 case AUDIO_FORMAT_AC3:
5925 case AUDIO_FORMAT_E_AC3:
5926 case AUDIO_FORMAT_DTS:
5927 case AUDIO_FORMAT_DTS_HD:
jiabin81772902018-04-02 17:52:27 -07005928 case AUDIO_FORMAT_AAC_LC:
5929 case AUDIO_FORMAT_DOLBY_TRUEHD:
5930 case AUDIO_FORMAT_E_AC3_JOC:
5931 mSurroundFormats.insert(format);
Phil Burk07ac1142016-03-25 13:39:29 -07005932 default:
Phil Burk07ac1142016-03-25 13:39:29 -07005933 break;
5934 }
Phil Burk09bc4612016-02-24 15:58:15 -08005935 }
Phil Burk07ac1142016-03-25 13:39:29 -07005936 }
Phil Burk09bc4612016-02-24 15:58:15 -08005937 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005938}
5939
5940// Modify the list of channel masks supported.
5941void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
5942 ChannelsVector &channelMasks = *channelMasksPtr;
5943 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5944 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5945
5946 // If NEVER, then remove support for channelMasks > stereo.
5947 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5948 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5949 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5950 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5951 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5952 channelMasks.removeAt(maskIndex);
5953 } else {
5954 maskIndex++;
5955 }
5956 }
jiabin81772902018-04-02 17:52:27 -07005957 // If ALWAYS or MANUAL, then make sure we at least support 5.1
5958 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
5959 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005960 bool supports5dot1 = false;
5961 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005962 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005963 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5964 supports5dot1 = true;
5965 break;
5966 }
5967 }
5968 // If not then add 5.1 support.
5969 if (!supports5dot1) {
5970 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
5971 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
5972 }
Phil Burk09bc4612016-02-24 15:58:15 -08005973 }
5974}
5975
Phil Burk00eeb322016-03-31 12:41:00 -07005976void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
5977 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005978 AudioProfileVector &profiles)
5979{
5980 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07005981
François Gaffie112b0af2015-11-19 16:13:25 +01005982 // Format MUST be checked first to update the list of AudioProfile
5983 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005984 reply = mpClientInterface->getParameters(
5985 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07005986 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005987 AudioParameter repliedParameters(reply);
5988 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005989 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005990 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5991 return;
5992 }
Phil Burk09bc4612016-02-24 15:58:15 -08005993 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07005994 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005995 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005996 }
Phil Burk09bc4612016-02-24 15:58:15 -08005997 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005998 }
François Gaffie112b0af2015-11-19 16:13:25 +01005999
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006000 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08006001 ChannelsVector channelMasks;
6002 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01006003 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07006004 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01006005
6006 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006007 reply = mpClientInterface->getParameters(
6008 ioHandle,
6009 requestedParameters.toString() + ";" +
6010 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01006011 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006012 AudioParameter repliedParameters(reply);
6013 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006014 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006015 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01006016 }
6017 }
6018 if (profiles.hasDynamicChannelsFor(format)) {
6019 reply = mpClientInterface->getParameters(ioHandle,
6020 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07006021 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01006022 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006023 AudioParameter repliedParameters(reply);
6024 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006025 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006026 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07006027 if (device == AUDIO_DEVICE_OUT_HDMI) {
6028 filterSurroundChannelMasks(&channelMasks);
6029 }
François Gaffie112b0af2015-11-19 16:13:25 +01006030 }
6031 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08006032 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006033 }
6034}
Eric Laurentd60560a2015-04-10 11:31:20 -07006035
Mikhail Naganovdc769682018-05-04 15:34:08 -07006036status_t AudioPolicyManager::installPatch(const char *caller,
6037 audio_patch_handle_t *patchHandle,
6038 AudioIODescriptorInterface *ioDescriptor,
6039 const struct audio_patch *patch,
6040 int delayMs)
6041{
6042 ssize_t index = mAudioPatches.indexOfKey(
6043 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6044 *patchHandle : ioDescriptor->getPatchHandle());
6045 sp<AudioPatch> patchDesc;
6046 status_t status = installPatch(
6047 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6048 if (status == NO_ERROR) {
6049 ioDescriptor->setPatchHandle(patchDesc->mHandle);
6050 }
6051 return status;
6052}
6053
6054status_t AudioPolicyManager::installPatch(const char *caller,
6055 ssize_t index,
6056 audio_patch_handle_t *patchHandle,
6057 const struct audio_patch *patch,
6058 int delayMs,
6059 uid_t uid,
6060 sp<AudioPatch> *patchDescPtr)
6061{
6062 sp<AudioPatch> patchDesc;
6063 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6064 if (index >= 0) {
6065 patchDesc = mAudioPatches.valueAt(index);
6066 afPatchHandle = patchDesc->mAfPatchHandle;
6067 }
6068
6069 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6070 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6071 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6072 if (status == NO_ERROR) {
6073 if (index < 0) {
6074 patchDesc = new AudioPatch(patch, uid);
6075 addAudioPatch(patchDesc->mHandle, patchDesc);
6076 } else {
6077 patchDesc->mPatch = *patch;
6078 }
6079 patchDesc->mAfPatchHandle = afPatchHandle;
6080 if (patchHandle) {
6081 *patchHandle = patchDesc->mHandle;
6082 }
6083 nextAudioPortGeneration();
6084 mpClientInterface->onAudioPatchListUpdate();
6085 }
6086 if (patchDescPtr) *patchDescPtr = patchDesc;
6087 return status;
6088}
6089
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006090} // namespace android