blob: 3e8c46247409f790effb3483b51f50723194665e [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
Andy Hungc29d82b2018-10-05 12:23:17 -07002689void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07002690{
Andy Hungc29d82b2018-10-05 12:23:17 -07002691 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
2692 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07002693 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002694 std::string stateLiteral;
2695 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07002696 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002697 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
2698 "communications", "media", "record", "dock", "system",
2699 "HDMI system audio", "encoded surround output", "vibrate ringing" };
2700 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
2701 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Andy Hungc29d82b2018-10-05 12:23:17 -07002702 dst->appendFormat(" Force use for %s: %d\n",
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002703 forceUses[i], mEngine->getForceUse(i));
2704 }
Andy Hungc29d82b2018-10-05 12:23:17 -07002705 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
2706 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
2707 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
2708 mAvailableOutputDevices.dump(dst, String8("Available output"));
2709 mAvailableInputDevices.dump(dst, String8("Available input"));
2710 mHwModulesAll.dump(dst);
2711 mOutputs.dump(dst);
2712 mInputs.dump(dst);
2713 mVolumeCurves->dump(dst);
2714 mEffects.dump(dst);
2715 mAudioPatches.dump(dst);
2716 mPolicyMixes.dump(dst);
2717 mAudioSources.dump(dst);
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002718 if (!mSurroundFormats.empty()) {
Andy Hungc29d82b2018-10-05 12:23:17 -07002719 dst->append("\nEnabled Surround Formats:\n");
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002720 size_t i = 0;
2721 for (const auto& fmt : mSurroundFormats) {
Andy Hungc29d82b2018-10-05 12:23:17 -07002722 dst->append(i++ == 0 ? " " : ", ");
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002723 std::string sfmt;
2724 FormatConverter::toString(fmt, sfmt);
Andy Hungc29d82b2018-10-05 12:23:17 -07002725 dst->append(sfmt.c_str());
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002726 }
Andy Hungc29d82b2018-10-05 12:23:17 -07002727 dst->append("\n");
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002728 }
Andy Hungc29d82b2018-10-05 12:23:17 -07002729}
2730
2731status_t AudioPolicyManager::dump(int fd)
2732{
2733 String8 result;
2734 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07002735 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002736 return NO_ERROR;
2737}
2738
2739// This function checks for the parameters which can be offloaded.
2740// This can be enhanced depending on the capability of the DSP and policy
2741// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002742bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002743{
2744 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002745 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002746 offloadInfo.sample_rate, offloadInfo.channel_mask,
2747 offloadInfo.format,
2748 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2749 offloadInfo.has_video);
2750
Andy Hung2ddee192015-12-18 17:34:44 -08002751 if (mMasterMono) {
2752 return false; // no offloading if mono is set.
2753 }
2754
Eric Laurente552edb2014-03-10 17:42:56 -07002755 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07002756 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
2757 ALOGV("offload disabled by audio.offload.disable");
2758 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002759 }
2760
2761 // Check if stream type is music, then only allow offload as of now.
2762 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2763 {
2764 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2765 return false;
2766 }
2767
2768 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002769 const bool allowOffloadWithVideo =
2770 property_get_bool("audio.offload.video", false /* default_value */);
2771 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002772 ALOGV("isOffloadSupported: has_video == true, returning false");
2773 return false;
2774 }
2775
2776 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07002777 const int min_duration_secs = property_get_int32(
2778 "audio.offload.min.duration.secs", -1 /* default_value */);
2779 if (min_duration_secs >= 0) {
2780 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
2781 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%d)",
2782 min_duration_secs);
Eric Laurente552edb2014-03-10 17:42:56 -07002783 return false;
2784 }
2785 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2786 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2787 return false;
2788 }
2789
2790 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2791 // creating an offloaded track and tearing it down immediately after start when audioflinger
2792 // detects there is an active non offloadable effect.
2793 // FIXME: We should check the audio session here but we do not have it in this context.
2794 // This may prevent offloading in rare situations where effects are left active by apps
2795 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002796 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002797 return false;
2798 }
2799
2800 // See if there is a profile to support this.
2801 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002802 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002803 offloadInfo.sample_rate,
2804 offloadInfo.format,
2805 offloadInfo.channel_mask,
2806 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002807 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2808 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002809}
2810
Eric Laurent6a94d692014-05-20 11:18:06 -07002811status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2812 audio_port_type_t type,
2813 unsigned int *num_ports,
2814 struct audio_port *ports,
2815 unsigned int *generation)
2816{
2817 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2818 generation == NULL) {
2819 return BAD_VALUE;
2820 }
2821 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2822 if (ports == NULL) {
2823 *num_ports = 0;
2824 }
2825
2826 size_t portsWritten = 0;
2827 size_t portsMax = *num_ports;
2828 *num_ports = 0;
2829 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002830 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2831 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002832 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002833 for (const auto& dev : mAvailableOutputDevices) {
2834 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002835 continue;
2836 }
2837 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002838 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002839 }
2840 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002841 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002842 }
2843 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002844 for (const auto& dev : mAvailableInputDevices) {
2845 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002846 continue;
2847 }
2848 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002849 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002850 }
2851 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002852 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002853 }
2854 }
2855 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2856 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2857 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2858 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2859 }
2860 *num_ports += mInputs.size();
2861 }
2862 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002863 size_t numOutputs = 0;
2864 for (size_t i = 0; i < mOutputs.size(); i++) {
2865 if (!mOutputs[i]->isDuplicated()) {
2866 numOutputs++;
2867 if (portsWritten < portsMax) {
2868 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2869 }
2870 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002871 }
Eric Laurent84c70242014-06-23 08:46:27 -07002872 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002873 }
2874 }
2875 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002876 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002877 return NO_ERROR;
2878}
2879
Eric Laurent99fcae42018-05-17 16:59:18 -07002880status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07002881{
Eric Laurent99fcae42018-05-17 16:59:18 -07002882 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
2883 return BAD_VALUE;
2884 }
2885 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
2886 if (dev != 0) {
2887 dev->toAudioPort(port);
2888 return NO_ERROR;
2889 }
2890 dev = mAvailableInputDevices.getDeviceFromId(port->id);
2891 if (dev != 0) {
2892 dev->toAudioPort(port);
2893 return NO_ERROR;
2894 }
2895 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
2896 if (out != 0) {
2897 out->toAudioPort(port);
2898 return NO_ERROR;
2899 }
2900 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
2901 if (in != 0) {
2902 in->toAudioPort(port);
2903 return NO_ERROR;
2904 }
2905 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002906}
2907
Eric Laurent6a94d692014-05-20 11:18:06 -07002908status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2909 audio_patch_handle_t *handle,
2910 uid_t uid)
2911{
2912 ALOGV("createAudioPatch()");
2913
2914 if (handle == NULL || patch == NULL) {
2915 return BAD_VALUE;
2916 }
2917 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2918
Mikhail Naganovac9858b2018-06-15 13:12:37 -07002919 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07002920 return BAD_VALUE;
2921 }
2922 // only one source per audio patch supported for now
2923 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002924 return INVALID_OPERATION;
2925 }
Eric Laurent874c42872014-08-08 15:13:39 -07002926
2927 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002928 return INVALID_OPERATION;
2929 }
Eric Laurent874c42872014-08-08 15:13:39 -07002930 for (size_t i = 0; i < patch->num_sinks; i++) {
2931 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2932 return INVALID_OPERATION;
2933 }
2934 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002935
2936 sp<AudioPatch> patchDesc;
2937 ssize_t index = mAudioPatches.indexOfKey(*handle);
2938
Eric Laurent6a94d692014-05-20 11:18:06 -07002939 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2940 patch->sources[0].role,
2941 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002942#if LOG_NDEBUG == 0
2943 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002944 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002945 patch->sinks[i].role,
2946 patch->sinks[i].type);
2947 }
2948#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002949
2950 if (index >= 0) {
2951 patchDesc = mAudioPatches.valueAt(index);
2952 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2953 mUidCached, patchDesc->mUid, uid);
2954 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2955 return INVALID_OPERATION;
2956 }
2957 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002958 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002959 }
2960
2961 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002962 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002963 if (outputDesc == NULL) {
2964 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2965 return BAD_VALUE;
2966 }
Eric Laurent84c70242014-06-23 08:46:27 -07002967 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2968 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002969 if (patchDesc != 0) {
2970 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2971 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2972 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2973 return BAD_VALUE;
2974 }
2975 }
Eric Laurent874c42872014-08-08 15:13:39 -07002976 DeviceVector devices;
2977 for (size_t i = 0; i < patch->num_sinks; i++) {
2978 // Only support mix to devices connection
2979 // TODO add support for mix to mix connection
2980 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2981 ALOGV("createAudioPatch() source mix but sink is not a device");
2982 return INVALID_OPERATION;
2983 }
2984 sp<DeviceDescriptor> devDesc =
2985 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2986 if (devDesc == 0) {
2987 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2988 return BAD_VALUE;
2989 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002990
François Gaffie53615e22015-03-19 09:24:12 +01002991 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002992 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002993 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002994 NULL, // updatedSamplingRate
2995 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002996 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002997 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002998 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002999 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07003000 ALOGV("createAudioPatch() profile not supported for device %08x",
3001 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07003002 return INVALID_OPERATION;
3003 }
3004 devices.add(devDesc);
3005 }
3006 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003007 return INVALID_OPERATION;
3008 }
Eric Laurent874c42872014-08-08 15:13:39 -07003009
Eric Laurent6a94d692014-05-20 11:18:06 -07003010 // TODO: reconfigure output format and channels here
3011 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07003012 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07003013 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003014 index = mAudioPatches.indexOfKey(*handle);
3015 if (index >= 0) {
3016 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3017 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
3018 }
3019 patchDesc = mAudioPatches.valueAt(index);
3020 patchDesc->mUid = uid;
3021 ALOGV("createAudioPatch() success");
3022 } else {
3023 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
3024 return INVALID_OPERATION;
3025 }
3026 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3027 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3028 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003029 // only one sink supported when connecting an input device to a mix
3030 if (patch->num_sinks > 1) {
3031 return INVALID_OPERATION;
3032 }
François Gaffie53615e22015-03-19 09:24:12 +01003033 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003034 if (inputDesc == NULL) {
3035 return BAD_VALUE;
3036 }
3037 if (patchDesc != 0) {
3038 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3039 return BAD_VALUE;
3040 }
3041 }
3042 sp<DeviceDescriptor> devDesc =
3043 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
3044 if (devDesc == 0) {
3045 return BAD_VALUE;
3046 }
3047
François Gaffie53615e22015-03-19 09:24:12 +01003048 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08003049 devDesc->mAddress,
3050 patch->sinks[0].sample_rate,
3051 NULL, /*updatedSampleRate*/
3052 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003053 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003054 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003055 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003056 // FIXME for the parameter type,
3057 // and the NONE
3058 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003059 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003060 return INVALID_OPERATION;
3061 }
3062 // TODO: reconfigure output format and channels here
3063 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01003064 devDesc->type(), inputDesc->mIoHandle);
3065 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003066 index = mAudioPatches.indexOfKey(*handle);
3067 if (index >= 0) {
3068 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3069 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
3070 }
3071 patchDesc = mAudioPatches.valueAt(index);
3072 patchDesc->mUid = uid;
3073 ALOGV("createAudioPatch() success");
3074 } else {
3075 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
3076 return INVALID_OPERATION;
3077 }
3078 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3079 // device to device connection
3080 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003081 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003082 return BAD_VALUE;
3083 }
3084 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003085 sp<DeviceDescriptor> srcDeviceDesc =
3086 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07003087 if (srcDeviceDesc == 0) {
3088 return BAD_VALUE;
3089 }
Eric Laurent874c42872014-08-08 15:13:39 -07003090
Eric Laurent6a94d692014-05-20 11:18:06 -07003091 //update source and sink with our own data as the data passed in the patch may
3092 // be incomplete.
3093 struct audio_patch newPatch = *patch;
3094 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003095
Eric Laurent874c42872014-08-08 15:13:39 -07003096 for (size_t i = 0; i < patch->num_sinks; i++) {
3097 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3098 ALOGV("createAudioPatch() source device but one sink is not a device");
3099 return INVALID_OPERATION;
3100 }
3101
3102 sp<DeviceDescriptor> sinkDeviceDesc =
3103 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3104 if (sinkDeviceDesc == 0) {
3105 return BAD_VALUE;
3106 }
3107 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
3108
Eric Laurent3bcf8592015-04-03 12:13:24 -07003109 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003110 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003111 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08003112 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003113 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003114 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003115 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003116 return INVALID_OPERATION;
3117 }
Eric Laurent874c42872014-08-08 15:13:39 -07003118 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01003119 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003120 // if the sink device is reachable via an opened output stream, request to go via
3121 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07003122 audio_io_handle_t output = selectOutput(outputs,
3123 AUDIO_OUTPUT_FLAG_NONE,
3124 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07003125 if (output != AUDIO_IO_HANDLE_NONE) {
3126 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3127 if (outputDesc->isDuplicated()) {
3128 return INVALID_OPERATION;
3129 }
3130 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003131 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003132 newPatch.num_sources = 2;
3133 }
Eric Laurent83b88082014-06-20 18:31:16 -07003134 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003135 }
3136 // TODO: check from routing capabilities in config file and other conflicting patches
3137
Mikhail Naganovdc769682018-05-04 15:34:08 -07003138 status_t status = installPatch(__func__, index, handle, &newPatch, 0, uid, &patchDesc);
3139 if (status != NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003140 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3141 status);
3142 return INVALID_OPERATION;
3143 }
3144 } else {
3145 return BAD_VALUE;
3146 }
3147 } else {
3148 return BAD_VALUE;
3149 }
3150 return NO_ERROR;
3151}
3152
3153status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3154 uid_t uid)
3155{
3156 ALOGV("releaseAudioPatch() patch %d", handle);
3157
3158 ssize_t index = mAudioPatches.indexOfKey(handle);
3159
3160 if (index < 0) {
3161 return BAD_VALUE;
3162 }
3163 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3164 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3165 mUidCached, patchDesc->mUid, uid);
3166 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3167 return INVALID_OPERATION;
3168 }
3169
3170 struct audio_patch *patch = &patchDesc->mPatch;
3171 patchDesc->mUid = mUidCached;
3172 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003173 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003174 if (outputDesc == NULL) {
3175 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3176 return BAD_VALUE;
3177 }
3178
Eric Laurentc75307b2015-03-17 15:29:32 -07003179 setOutputDevice(outputDesc,
3180 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07003181 true,
3182 0,
3183 NULL);
3184 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3185 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003186 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003187 if (inputDesc == NULL) {
3188 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3189 return BAD_VALUE;
3190 }
3191 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003192 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003193 true,
3194 NULL);
3195 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003196 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3197 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3198 status, patchDesc->mAfPatchHandle);
3199 removeAudioPatch(patchDesc->mHandle);
3200 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003201 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003202 } else {
3203 return BAD_VALUE;
3204 }
3205 } else {
3206 return BAD_VALUE;
3207 }
3208 return NO_ERROR;
3209}
3210
3211status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3212 struct audio_patch *patches,
3213 unsigned int *generation)
3214{
François Gaffie53615e22015-03-19 09:24:12 +01003215 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003216 return BAD_VALUE;
3217 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003218 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003219 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003220}
3221
Eric Laurente1715a42014-05-20 11:30:42 -07003222status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003223{
Eric Laurente1715a42014-05-20 11:30:42 -07003224 ALOGV("setAudioPortConfig()");
3225
3226 if (config == NULL) {
3227 return BAD_VALUE;
3228 }
3229 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3230 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003231 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3232 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003233 }
3234
Eric Laurenta121f902014-06-03 13:32:54 -07003235 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003236 if (config->type == AUDIO_PORT_TYPE_MIX) {
3237 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003238 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003239 if (outputDesc == NULL) {
3240 return BAD_VALUE;
3241 }
Eric Laurent84c70242014-06-23 08:46:27 -07003242 ALOG_ASSERT(!outputDesc->isDuplicated(),
3243 "setAudioPortConfig() called on duplicated output %d",
3244 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003245 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003246 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003247 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003248 if (inputDesc == NULL) {
3249 return BAD_VALUE;
3250 }
Eric Laurenta121f902014-06-03 13:32:54 -07003251 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003252 } else {
3253 return BAD_VALUE;
3254 }
3255 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3256 sp<DeviceDescriptor> deviceDesc;
3257 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3258 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3259 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3260 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3261 } else {
3262 return BAD_VALUE;
3263 }
3264 if (deviceDesc == NULL) {
3265 return BAD_VALUE;
3266 }
Eric Laurenta121f902014-06-03 13:32:54 -07003267 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003268 } else {
3269 return BAD_VALUE;
3270 }
3271
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003272 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003273 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3274 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003275 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003276 audioPortConfig->toAudioPortConfig(&newConfig, config);
3277 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003278 }
Eric Laurenta121f902014-06-03 13:32:54 -07003279 if (status != NO_ERROR) {
3280 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003281 }
Eric Laurente1715a42014-05-20 11:30:42 -07003282
3283 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003284}
3285
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003286void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3287{
Eric Laurentd60560a2015-04-10 11:31:20 -07003288 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003289 clearAudioPatches(uid);
3290 clearSessionRoutes(uid);
3291}
3292
Eric Laurent6a94d692014-05-20 11:18:06 -07003293void AudioPolicyManager::clearAudioPatches(uid_t uid)
3294{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003295 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003296 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3297 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003298 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003299 }
3300 }
3301}
3302
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003303void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3304 audio_io_handle_t ouptutToSkip)
3305{
3306 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3307 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3308 for (size_t j = 0; j < mOutputs.size(); j++) {
3309 if (mOutputs.keyAt(j) == ouptutToSkip) {
3310 continue;
3311 }
3312 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3313 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3314 continue;
3315 }
3316 // If the default device for this strategy is on another output mix,
3317 // invalidate all tracks in this strategy to force re connection.
3318 // Otherwise select new device on the output mix.
3319 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003320 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003321 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3322 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3323 }
3324 }
3325 } else {
3326 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3327 setOutputDevice(outputDesc, newDevice, false);
3328 }
3329 }
3330}
3331
3332void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3333{
3334 // remove output routes associated with this uid
3335 SortedVector<routing_strategy> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07003336 for (size_t i = 0; i < mOutputs.size(); i++) {
3337 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003338 for (const auto& client : outputDesc->getClientIterable()) {
3339 if (client->hasPreferredDevice() && client->uid() == uid) {
3340 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3341 affectedStrategies.add(getStrategy(client->stream()));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003342 }
3343 }
3344 }
3345 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003346 for (const auto& strategy : affectedStrategies) {
3347 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003348 }
3349
3350 // remove input routes associated with this uid
3351 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07003352 for (size_t i = 0; i < mInputs.size(); i++) {
3353 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003354 for (const auto& client : inputDesc->getClientIterable()) {
3355 if (client->hasPreferredDevice() && client->uid() == uid) {
3356 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3357 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003358 }
3359 }
3360 }
3361 // reroute inputs if necessary
3362 SortedVector<audio_io_handle_t> inputsToClose;
3363 for (size_t i = 0; i < mInputs.size(); i++) {
3364 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003365 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003366 inputsToClose.add(inputDesc->mIoHandle);
3367 }
3368 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003369 for (const auto& input : inputsToClose) {
3370 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003371 }
3372}
3373
Eric Laurentd60560a2015-04-10 11:31:20 -07003374void AudioPolicyManager::clearAudioSources(uid_t uid)
3375{
3376 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003377 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3378 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07003379 stopAudioSource(mAudioSources.keyAt(i));
3380 }
3381 }
3382}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003383
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003384status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3385 audio_io_handle_t *ioHandle,
3386 audio_devices_t *device)
3387{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003388 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3389 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003390 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003391
François Gaffiedf372692015-03-19 10:43:27 +01003392 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003393}
3394
Eric Laurentd60560a2015-04-10 11:31:20 -07003395status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003396 const audio_attributes_t *attributes,
3397 audio_port_handle_t *portId,
3398 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003399{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003400 ALOGV("%s", __FUNCTION__);
3401 *portId = AUDIO_PORT_HANDLE_NONE;
3402
3403 if (source == NULL || attributes == NULL || portId == NULL) {
3404 ALOGW("%s invalid argument: source %p attributes %p handle %p",
3405 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003406 return BAD_VALUE;
3407 }
3408
Eric Laurentd60560a2015-04-10 11:31:20 -07003409 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3410 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003411 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
3412 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003413 return INVALID_OPERATION;
3414 }
3415
3416 sp<DeviceDescriptor> srcDeviceDesc =
3417 mAvailableInputDevices.getDevice(source->ext.device.type,
3418 String8(source->ext.device.address));
3419 if (srcDeviceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003420 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003421 return BAD_VALUE;
3422 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003423
3424 *portId = AudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07003425
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003426 struct audio_patch dummyPatch = {};
Eric Laurentd60560a2015-04-10 11:31:20 -07003427 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003428
3429 sp<SourceClientDescriptor> sourceDesc =
3430 new SourceClientDescriptor(*portId, uid, *attributes, patchDesc, srcDeviceDesc,
Eric Laurent97ac8712018-07-27 18:59:02 -07003431 streamTypefromAttributesInt(attributes),
3432 getStrategyForAttr(attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07003433
3434 status_t status = connectAudioSource(sourceDesc);
3435 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003436 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003437 }
3438 return status;
3439}
3440
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003441status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003442{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003443 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003444
3445 // make sure we only have one patch per source.
3446 disconnectAudioSource(sourceDesc);
3447
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003448 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003449 routing_strategy strategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003450 audio_stream_type_t stream = sourceDesc->stream();
3451 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->srcDevice();
Eric Laurentd60560a2015-04-10 11:31:20 -07003452
3453 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3454 sp<DeviceDescriptor> sinkDeviceDesc =
3455 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3456
3457 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003458
3459 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3460 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003461 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003462 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3463 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3464 // create patch between src device and output device
3465 // create Hwoutput and add to mHwOutputs
3466 } else {
3467 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3468 audio_io_handle_t output =
3469 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3470 if (output == AUDIO_IO_HANDLE_NONE) {
3471 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3472 return INVALID_OPERATION;
3473 }
3474 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3475 if (outputDesc->isDuplicated()) {
3476 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3477 return INVALID_OPERATION;
3478 }
Eric Laurent733ce942017-12-07 12:18:25 -08003479 status_t status = outputDesc->start();
3480 if (status != NO_ERROR) {
3481 return status;
3482 }
3483
Eric Laurentd60560a2015-04-10 11:31:20 -07003484 // create a special patch with no sink and two sources:
3485 // - the second source indicates to PatchPanel through which output mix this patch should
3486 // be connected as well as the stream type for volume control
3487 // - the sink is defined by whatever output device is currently selected for the output
3488 // though which this patch is routed.
Mikhail Naganovdc769682018-05-04 15:34:08 -07003489 PatchBuilder patchBuilder;
3490 patchBuilder.addSource(srcDeviceDesc).addSource(outputDesc, { .stream = stream });
3491 status = mpClientInterface->createAudioPatch(patchBuilder.patch(),
Eric Laurentd60560a2015-04-10 11:31:20 -07003492 &afPatchHandle,
3493 0);
3494 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3495 status, afPatchHandle);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003496 sourceDesc->patchDesc()->mPatch = *patchBuilder.patch();
Eric Laurentd60560a2015-04-10 11:31:20 -07003497 if (status != NO_ERROR) {
3498 ALOGW("%s patch panel could not connect device patch, error %d",
3499 __FUNCTION__, status);
3500 return INVALID_OPERATION;
3501 }
3502 uint32_t delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07003503 status = startSource(outputDesc, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003504
3505 if (status != NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003506 mpClientInterface->releaseAudioPatch(sourceDesc->patchDesc()->mAfPatchHandle, 0);
Eric Laurentd60560a2015-04-10 11:31:20 -07003507 return status;
3508 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003509 sourceDesc->setSwOutput(outputDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003510 if (delayMs != 0) {
3511 usleep(delayMs * 1000);
3512 }
3513 }
3514
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003515 sourceDesc->patchDesc()->mAfPatchHandle = afPatchHandle;
3516 addAudioPatch(sourceDesc->patchDesc()->mHandle, sourceDesc->patchDesc());
Eric Laurentd60560a2015-04-10 11:31:20 -07003517
3518 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003519}
3520
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003521status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07003522{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003523 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
3524 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003525 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003526 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003527 return BAD_VALUE;
3528 }
3529 status_t status = disconnectAudioSource(sourceDesc);
3530
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003531 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003532 return status;
3533}
3534
Andy Hung2ddee192015-12-18 17:34:44 -08003535status_t AudioPolicyManager::setMasterMono(bool mono)
3536{
3537 if (mMasterMono == mono) {
3538 return NO_ERROR;
3539 }
3540 mMasterMono = mono;
3541 // if enabling mono we close all offloaded devices, which will invalidate the
3542 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3543 // for recreating the new AudioTrack as non-offloaded PCM.
3544 //
3545 // If disabling mono, we leave all tracks as is: we don't know which clients
3546 // and tracks are able to be recreated as offloaded. The next "song" should
3547 // play back offloaded.
3548 if (mMasterMono) {
3549 Vector<audio_io_handle_t> offloaded;
3550 for (size_t i = 0; i < mOutputs.size(); ++i) {
3551 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3552 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3553 offloaded.push(desc->mIoHandle);
3554 }
3555 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003556 for (const auto& handle : offloaded) {
3557 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003558 }
3559 }
3560 // update master mono for all remaining outputs
3561 for (size_t i = 0; i < mOutputs.size(); ++i) {
3562 updateMono(mOutputs.keyAt(i));
3563 }
3564 return NO_ERROR;
3565}
3566
3567status_t AudioPolicyManager::getMasterMono(bool *mono)
3568{
3569 *mono = mMasterMono;
3570 return NO_ERROR;
3571}
3572
Eric Laurentac9cef52017-06-09 15:46:26 -07003573float AudioPolicyManager::getStreamVolumeDB(
3574 audio_stream_type_t stream, int index, audio_devices_t device)
3575{
3576 return computeVolume(stream, index, device);
3577}
3578
jiabin81772902018-04-02 17:52:27 -07003579status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3580 audio_format_t *surroundFormats,
3581 bool *surroundFormatsEnabled,
3582 bool reported)
3583{
3584 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3585 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3586 return BAD_VALUE;
3587 }
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003588 ALOGV("getSurroundFormats() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p"
3589 " reported %d", *numSurroundFormats, surroundFormats, surroundFormatsEnabled, reported);
jiabin81772902018-04-02 17:52:27 -07003590
3591 // Only return value if there is HDMI output.
3592 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3593 return INVALID_OPERATION;
3594 }
3595
3596 size_t formatsWritten = 0;
3597 size_t formatsMax = *numSurroundFormats;
3598 *numSurroundFormats = 0;
Mikhail Naganov2563f232018-09-27 14:48:01 -07003599 std::unordered_set<audio_format_t> formats;
jiabin81772902018-04-02 17:52:27 -07003600 if (reported) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003601 // Return formats from HDMI profiles, that have already been resolved by
3602 // checkOutputsForDevice().
3603 DeviceVector hdmiOutputDevs = mAvailableOutputDevices.getDevicesFromTypeMask(
3604 AUDIO_DEVICE_OUT_HDMI);
3605 for (size_t i = 0; i < hdmiOutputDevs.size(); i++) {
3606 FormatVector supportedFormats =
3607 hdmiOutputDevs[i]->getAudioPort()->getAudioProfiles().getSupportedFormats();
3608 for (size_t j = 0; j < supportedFormats.size(); j++) {
3609 if (std::find(std::begin(SURROUND_FORMATS),
3610 std::end(SURROUND_FORMATS),
3611 supportedFormats[j]) != std::end(SURROUND_FORMATS)) {
3612 formats.insert(supportedFormats[j]);
3613 } else if (std::find(std::begin(AAC_FORMATS),
3614 std::end(AAC_FORMATS),
3615 supportedFormats[j]) != std::end(AAC_FORMATS)) {
3616 // if any format in AAC_FORMATS is reported, insert AUDIO_FORMAT_AAC_LC as this
3617 // is the only AAC format used in the TvSettings UI for all AAC formats.
3618 formats.insert(AUDIO_FORMAT_AAC_LC);
3619 }
3620 }
jiabin81772902018-04-02 17:52:27 -07003621 }
3622 } else {
3623 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003624 formats.insert(SURROUND_FORMATS[i]);
jiabin81772902018-04-02 17:52:27 -07003625 }
3626 }
Mikhail Naganov2563f232018-09-27 14:48:01 -07003627 for (const auto& format: formats) {
jiabin81772902018-04-02 17:52:27 -07003628 if (formatsWritten < formatsMax) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003629 surroundFormats[formatsWritten] = format;
jiabin81772902018-04-02 17:52:27 -07003630 bool formatEnabled = false;
Mikhail Naganov2563f232018-09-27 14:48:01 -07003631 if (format == AUDIO_FORMAT_AAC_LC) {
3632 for (size_t j = 0; j < ARRAY_SIZE(AAC_FORMATS) && !formatEnabled; j++) {
jiabin81772902018-04-02 17:52:27 -07003633 formatEnabled =
Mikhail Naganov2563f232018-09-27 14:48:01 -07003634 mSurroundFormats.find(AAC_FORMATS[j]) != mSurroundFormats.end();
jiabin81772902018-04-02 17:52:27 -07003635 }
3636 } else {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003637 formatEnabled = mSurroundFormats.find(format) != mSurroundFormats.end();
jiabin81772902018-04-02 17:52:27 -07003638 }
3639 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3640 }
3641 (*numSurroundFormats)++;
3642 }
3643 return NO_ERROR;
3644}
3645
3646status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3647{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003648 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
jiabin81772902018-04-02 17:52:27 -07003649 // Check if audio format is a surround formats.
3650 bool isSurroundFormat = false;
3651 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3652 if (audioFormat == SURROUND_FORMATS[i]) {
3653 isSurroundFormat = true;
3654 break;
3655 }
3656 }
3657 if (!isSurroundFormat) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003658 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07003659 return BAD_VALUE;
3660 }
3661
3662 // Should only be called when MANUAL.
3663 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3664 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
3665 if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003666 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07003667 return INVALID_OPERATION;
3668 }
3669
3670 if ((mSurroundFormats.find(audioFormat) != mSurroundFormats.end() && enabled)
3671 || (mSurroundFormats.find(audioFormat) == mSurroundFormats.end() && !enabled)) {
3672 return NO_ERROR;
3673 }
3674
3675 // The operation is valid only when there is HDMI output available.
3676 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003677 ALOGW("%s() no HDMI out devices found", __func__);
jiabin81772902018-04-02 17:52:27 -07003678 return INVALID_OPERATION;
3679 }
3680
Mikhail Naganov2563f232018-09-27 14:48:01 -07003681 std::unordered_set<audio_format_t> surroundFormatsBackup(mSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07003682 if (enabled) {
3683 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3684 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3685 mSurroundFormats.insert(AAC_FORMATS[i]);
3686 }
3687 } else {
3688 mSurroundFormats.insert(audioFormat);
3689 }
3690 } else {
3691 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3692 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3693 mSurroundFormats.erase(AAC_FORMATS[i]);
3694 }
3695 } else {
3696 mSurroundFormats.erase(audioFormat);
3697 }
3698 }
3699
3700 sp<SwAudioOutputDescriptor> outputDesc;
3701 bool profileUpdated = false;
Mikhail Naganov708e0382018-05-30 09:53:04 -07003702 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003703 AUDIO_DEVICE_OUT_HDMI);
3704 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3705 // Simulate reconnection to update enabled surround sound formats.
3706 String8 address = hdmiOutputDevices[i]->mAddress;
3707 String8 name = hdmiOutputDevices[i]->getName();
3708 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3709 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3710 address.c_str(),
3711 name.c_str());
3712 if (status != NO_ERROR) {
3713 continue;
3714 }
3715 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3716 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3717 address.c_str(),
3718 name.c_str());
3719 profileUpdated |= (status == NO_ERROR);
3720 }
Mikhail Naganov708e0382018-05-30 09:53:04 -07003721 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003722 AUDIO_DEVICE_IN_HDMI);
3723 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3724 // Simulate reconnection to update enabled surround sound formats.
3725 String8 address = hdmiInputDevices[i]->mAddress;
3726 String8 name = hdmiInputDevices[i]->getName();
3727 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3728 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3729 address.c_str(),
3730 name.c_str());
3731 if (status != NO_ERROR) {
3732 continue;
3733 }
3734 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3735 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3736 address.c_str(),
3737 name.c_str());
3738 profileUpdated |= (status == NO_ERROR);
3739 }
3740
3741 // Undo the surround formats change due to no audio profiles updated.
3742 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003743 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov2563f232018-09-27 14:48:01 -07003744 mSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07003745 }
3746
3747 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3748}
3749
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003750void AudioPolicyManager::setRecordSilenced(uid_t uid, bool silenced)
3751{
3752 ALOGV("AudioPolicyManager:setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
3753
3754 Vector<sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
3755 for (size_t i = 0; i < activeInputs.size(); i++) {
3756 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
Eric Laurent8f42ea12018-08-08 09:08:25 -07003757 RecordClientVector clients = activeDesc->clientsList(true /*activeOnly*/);
3758 for (const auto& client : clients) {
3759 if (uid == client->uid()) {
3760 client->setSilenced(silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003761 }
3762 }
3763 }
3764}
3765
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003766status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003767{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003768 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003769
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003770 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003771 if (patchDesc == 0) {
3772 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003773 sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003774 return BAD_VALUE;
3775 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003776 removeAudioPatch(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003777
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003778 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003779 if (swOutputDesc != 0) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003780 status_t status = stopSource(swOutputDesc, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08003781 if (status == NO_ERROR) {
3782 swOutputDesc->stop();
3783 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003784 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3785 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003786 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003787 if (hwOutputDesc != 0) {
3788 // release patch between src device and output device
3789 // close Hwoutput and remove from mHwOutputs
3790 } else {
3791 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3792 }
3793 }
3794 return NO_ERROR;
3795}
3796
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003797sp<SourceClientDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
Eric Laurentd60560a2015-04-10 11:31:20 -07003798 audio_io_handle_t output, routing_strategy strategy)
3799{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003800 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07003801 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003802 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3803 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003804 routing_strategy sourceStrategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003805 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003806 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3807 source = sourceDesc;
3808 break;
3809 }
3810 }
3811 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003812}
3813
Eric Laurente552edb2014-03-10 17:42:56 -07003814// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003815// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003816// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003817uint32_t AudioPolicyManager::nextAudioPortGeneration()
3818{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003819 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003820}
3821
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003822#ifdef USE_XML_AUDIO_POLICY_CONF
3823// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3824static const char *kConfigLocationList[] =
3825 {"/odm/etc", "/vendor/etc", "/system/etc"};
3826static const int kConfigLocationListSize =
3827 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3828
3829static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3830 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07003831 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003832 status_t ret;
3833
Petri Gyntherf497f292018-04-17 18:46:10 -07003834 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
3835 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
3836 // A2DP offload supported but disabled: try to use special XML file
3837 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
3838 }
3839 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3840
3841 for (const char* fileName : fileNames) {
3842 for (int i = 0; i < kConfigLocationListSize; i++) {
Petri Gyntherf497f292018-04-17 18:46:10 -07003843 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
3844 "%s/%s", kConfigLocationList[i], fileName);
Mikhail Naganova289aea2018-09-17 15:26:23 -07003845 ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile, &config);
Petri Gyntherf497f292018-04-17 18:46:10 -07003846 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003847 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07003848 return ret;
3849 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003850 }
3851 }
3852 return ret;
3853}
3854#endif
3855
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003856AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
3857 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07003858 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07003859 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003860 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07003861 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003862 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003863#ifdef USE_XML_AUDIO_POLICY_CONF
3864 mVolumeCurves(new VolumeCurvesCollection()),
3865 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08003866 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003867#else
3868 mVolumeCurves(new StreamDescriptorCollection()),
3869 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
3870 mDefaultOutputDevice),
3871#endif
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003872 mAudioPortGeneration(1),
3873 mBeaconMuteRefCount(0),
3874 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003875 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003876 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003877 mMasterMono(false),
Chris Thornton2b864642017-06-27 21:26:07 -07003878 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE),
3879 mHasComputedSoundTriggerSupportsConcurrentCapture(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003880{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003881}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003882
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003883AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
3884 : AudioPolicyManager(clientInterface, false /*forTesting*/)
3885{
3886 loadConfig();
3887 initialize();
3888}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003889
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003890void AudioPolicyManager::loadConfig() {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003891#ifdef USE_XML_AUDIO_POLICY_CONF
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003892 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003893#else
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003894 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, getConfig()) != NO_ERROR)
3895 && (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, getConfig()) != NO_ERROR)) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003896#endif
3897 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003898 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01003899 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003900}
3901
3902status_t AudioPolicyManager::initialize() {
3903 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01003904
3905 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003906 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3907 if (!engineInstance) {
3908 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003909 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003910 }
3911 // Retrieve the Policy Manager Interface
3912 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3913 if (mEngine == NULL) {
3914 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003915 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003916 }
3917 mEngine->setObserver(this);
3918 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003919 if (status != NO_ERROR) {
3920 LOG_FATAL("Policy engine not initialized(err=%d)", status);
3921 return status;
3922 }
François Gaffie2110e042015-03-24 08:41:51 +01003923
Eric Laurent3a4311c2014-03-17 12:00:47 -07003924 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003925 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003926 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3927 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Mikhail Naganovd4120142017-12-06 15:49:22 -08003928 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003929 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08003930 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
3931 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003932 continue;
3933 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08003934 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07003935 // open all output streams needed to access attached devices
3936 // except for direct output streams that are only opened when they are actually
3937 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003938 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003939 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003940 if (!outProfile->canOpenNewIo()) {
3941 ALOGE("Invalid Output profile max open count %u for profile %s",
3942 outProfile->maxOpenCount, outProfile->getTagName().c_str());
3943 continue;
3944 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003945 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003946 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003947 continue;
3948 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003949 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003950 mTtsOutputAvailable = true;
3951 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003952
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003953 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003954 continue;
3955 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003956 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003957 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3958 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003959 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003960 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003961 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003962 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003963 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003964 if ((profileType & outputDeviceTypes) == 0) {
3965 continue;
3966 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003967 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3968 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003969 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov708e0382018-05-30 09:53:04 -07003970 const DeviceVector &devicesForType = supportedDevices.getDevicesFromTypeMask(
3971 profileType);
Eric Laurentc40d9692016-04-13 19:14:13 -07003972 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3973 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003974 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08003975 status_t status = outputDesc->open(nullptr, profileType, address,
3976 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07003977
3978 if (status != NO_ERROR) {
3979 ALOGW("Cannot open output stream for device %08x on hw module %s",
3980 outputDesc->mDevice,
Mikhail Naganovd4120142017-12-06 15:49:22 -08003981 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003982 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003983 for (const auto& dev : supportedDevices) {
3984 ssize_t index = mAvailableOutputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07003985 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003986 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003987 mAvailableOutputDevices[index]->attach(hwModule);
Eric Laurentd78f1532014-09-16 16:38:20 -07003988 }
3989 }
3990 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003991 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003992 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003993 }
3994 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003995 setOutputDevice(outputDesc,
Eric Laurentfe231122017-11-17 17:48:06 -08003996 profileType,
Eric Laurentc40d9692016-04-13 19:14:13 -07003997 true,
3998 0,
3999 NULL,
Eric Laurentfe231122017-11-17 17:48:06 -08004000 address);
Eric Laurentd78f1532014-09-16 16:38:20 -07004001 }
Eric Laurente552edb2014-03-10 17:42:56 -07004002 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004003 // open input streams needed to access attached devices to validate
4004 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004005 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004006 if (!inProfile->canOpenNewIo()) {
4007 ALOGE("Invalid Input profile max open count %u for profile %s",
4008 inProfile->maxOpenCount, inProfile->getTagName().c_str());
4009 continue;
4010 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004011 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004012 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004013 continue;
4014 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004015 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07004016 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004017 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
4018
Eric Laurentd78f1532014-09-16 16:38:20 -07004019 if ((profileType & inputDeviceTypes) == 0) {
4020 continue;
4021 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08004022 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08004023 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004024
Mikhail Naganov708e0382018-05-30 09:53:04 -07004025 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(profileType);
Eric Laurent53b810e2017-12-10 17:25:10 -08004026 // the inputs vector must be of size >= 1, but we don't want to crash here
4027 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
4028 : String8("");
4029 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
4030 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
4031
Eric Laurentd78f1532014-09-16 16:38:20 -07004032 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004033 status_t status = inputDesc->open(nullptr,
4034 profileType,
Eric Laurent53b810e2017-12-10 17:25:10 -08004035 address,
Eric Laurentfe231122017-11-17 17:48:06 -08004036 AUDIO_SOURCE_MIC,
4037 AUDIO_INPUT_FLAG_NONE,
4038 &input);
Eric Laurentd78f1532014-09-16 16:38:20 -07004039
4040 if (status == NO_ERROR) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004041 for (const auto& dev : inProfile->getSupportedDevices()) {
4042 ssize_t index = mAvailableInputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07004043 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07004044 if (index >= 0) {
4045 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
4046 if (!devDesc->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004047 devDesc->attach(hwModule);
Eric Laurent83efe1c2017-07-09 16:51:08 -07004048 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07004049 }
Eric Laurentd78f1532014-09-16 16:38:20 -07004050 }
4051 }
Eric Laurentfe231122017-11-17 17:48:06 -08004052 inputDesc->close();
Eric Laurentd78f1532014-09-16 16:38:20 -07004053 } else {
4054 ALOGW("Cannot open input stream for device %08x on hw module %s",
Eric Laurentfe231122017-11-17 17:48:06 -08004055 profileType,
Mikhail Naganovd4120142017-12-06 15:49:22 -08004056 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07004057 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004058 }
4059 }
4060 // make sure all attached devices have been allocated a unique ID
4061 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004062 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004063 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004064 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
4065 continue;
4066 }
François Gaffie2110e042015-03-24 08:41:51 +01004067 // The device is now validated and can be appended to the available devices of the engine
4068 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
4069 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004070 i++;
4071 }
4072 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004073 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01004074 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004075 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
4076 continue;
4077 }
François Gaffie2110e042015-03-24 08:41:51 +01004078 // The device is now validated and can be appended to the available devices of the engine
4079 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
4080 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004081 i++;
4082 }
4083 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004084 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01004085 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004086 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004087 }
jiabin9ff780e2018-03-19 18:19:52 -07004088 // If microphones address is empty, set it according to device type
4089 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
4090 if (mAvailableInputDevices[i]->mAddress.isEmpty()) {
4091 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
4092 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
4093 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
4094 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BACK_MICROPHONE_ADDRESS);
4095 }
4096 }
4097 }
Eric Laurente552edb2014-03-10 17:42:56 -07004098
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004099 if (mPrimaryOutput == 0) {
4100 ALOGE("Failed to open primary output");
4101 status = NO_INIT;
4102 }
Eric Laurente552edb2014-03-10 17:42:56 -07004103
4104 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004105 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004106}
4107
Eric Laurente0720872014-03-11 09:30:41 -07004108AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004109{
Eric Laurente552edb2014-03-10 17:42:56 -07004110 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004111 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004112 }
4113 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004114 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004115 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004116 mAvailableOutputDevices.clear();
4117 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004118 mOutputs.clear();
4119 mInputs.clear();
4120 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004121 mHwModulesAll.clear();
jiabin81772902018-04-02 17:52:27 -07004122 mSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004123}
4124
Eric Laurente0720872014-03-11 09:30:41 -07004125status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004126{
Eric Laurent87ffa392015-05-22 10:32:38 -07004127 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004128}
4129
Eric Laurente552edb2014-03-10 17:42:56 -07004130// ---
4131
Eric Laurent98e38192018-02-15 18:31:53 -08004132void AudioPolicyManager::addOutput(audio_io_handle_t output,
4133 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004134{
Eric Laurent1c333e22014-05-20 10:48:17 -07004135 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08004136 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004137 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004138 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004139 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004140}
4141
François Gaffie53615e22015-03-19 09:24:12 +01004142void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4143{
4144 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004145 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004146}
4147
Eric Laurent98e38192018-02-15 18:31:53 -08004148void AudioPolicyManager::addInput(audio_io_handle_t input,
4149 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004150{
Eric Laurent1c333e22014-05-20 10:48:17 -07004151 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004152 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004153}
Eric Laurente552edb2014-03-10 17:42:56 -07004154
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004155void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08004156 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004157 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004158 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08004159 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004160 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08004161 if (devDesc != 0) {
4162 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
4163 desc->mIoHandle, address.string());
4164 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004165 }
4166}
4167
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004168status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004169 audio_policy_dev_state_t state,
4170 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004171 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07004172{
François Gaffie53615e22015-03-19 09:24:12 +01004173 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07004174 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004175
4176 if (audio_device_is_digital(device)) {
4177 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004178 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004179 }
Eric Laurente552edb2014-03-10 17:42:56 -07004180
Eric Laurent3b73df72014-03-11 09:06:29 -07004181 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004182 // first list already open outputs that can be routed to this device
4183 for (size_t i = 0; i < mOutputs.size(); i++) {
4184 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07004185 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004186 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004187 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
4188 outputs.add(mOutputs.keyAt(i));
4189 } else {
4190 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08004191 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004192 }
Eric Laurente552edb2014-03-10 17:42:56 -07004193 }
4194 }
4195 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004196 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004197 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004198 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4199 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004200 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004201 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004202 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004203 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004204 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4205 j, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004206 }
Eric Laurente552edb2014-03-10 17:42:56 -07004207 }
4208 }
4209 }
4210
Eric Laurent7b279bb2015-12-14 10:18:23 -08004211 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004212
Eric Laurente552edb2014-03-10 17:42:56 -07004213 if (profiles.isEmpty() && outputs.isEmpty()) {
4214 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4215 return BAD_VALUE;
4216 }
4217
4218 // open outputs for matching profiles if needed. Direct outputs are also opened to
4219 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4220 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004221 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004222
4223 // nothing to do if one output is already opened for this profile
4224 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004225 for (j = 0; j < outputs.size(); j++) {
4226 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004227 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004228 // matching profile: save the sample rates, format and channel masks supported
4229 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07004230 if (audio_device_is_digital(device)) {
4231 devDesc->importAudioPort(profile);
4232 }
Eric Laurente552edb2014-03-10 17:42:56 -07004233 break;
4234 }
4235 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004236 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004237 continue;
4238 }
4239
Eric Laurent3974e3b2017-12-07 17:58:43 -08004240 if (!profile->canOpenNewIo()) {
4241 ALOGW("Max Output number %u already opened for this profile %s",
4242 profile->maxOpenCount, profile->getTagName().c_str());
4243 continue;
4244 }
4245
Eric Laurent83efe1c2017-07-09 16:51:08 -07004246 ALOGV("opening output for device %08x with params %s profile %p name %s",
4247 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004248 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004249 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004250 status_t status = desc->open(nullptr, device, address,
4251 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004252
Eric Laurentfe231122017-11-17 17:48:06 -08004253 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004254 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004255 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004256 char *param = audio_device_address_to_parameter(device, address);
4257 mpClientInterface->setParameters(output, String8(param));
4258 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004259 }
Phil Burk00eeb322016-03-31 12:41:00 -07004260 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004261 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004262 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004263 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004264 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004265 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004266 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004267 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004268 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4269 profile->pickAudioProfile(
4270 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004271 config.offload_info.sample_rate = config.sample_rate;
4272 config.offload_info.channel_mask = config.channel_mask;
4273 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004274
4275 status_t status = desc->open(&config, device, address, AUDIO_STREAM_DEFAULT,
4276 AUDIO_OUTPUT_FLAG_NONE, &output);
4277 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004278 output = AUDIO_IO_HANDLE_NONE;
4279 }
Eric Laurentd4692962014-05-05 18:13:44 -07004280 }
4281
Eric Laurentcf2c0212014-07-25 16:20:43 -07004282 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004283 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01004284 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004285 sp<AudioPolicyMix> policyMix;
4286 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004287 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
4288 address.string());
4289 }
François Gaffie036e1e92015-03-19 10:16:24 +01004290 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07004291 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01004292
Eric Laurent87ffa392015-05-22 10:32:38 -07004293 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4294 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004295 // no duplicated output for direct outputs and
4296 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004297 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004298
Eric Laurentd4692962014-05-05 18:13:44 -07004299 //TODO: configure audio effect output stage here
4300
4301 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004302 sp<SwAudioOutputDescriptor> dupOutputDesc =
4303 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4304 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4305 &duplicatedOutput);
4306 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004307 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004308 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004309 } else {
4310 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004311 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004312 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004313 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004314 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004315 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004316 }
Eric Laurente552edb2014-03-10 17:42:56 -07004317 }
4318 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004319 } else {
4320 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004321 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004322 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004323 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004324 profiles.removeAt(profile_index);
4325 profile_index--;
4326 } else {
4327 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004328 // Load digital format info only for digital devices
4329 if (audio_device_is_digital(device)) {
4330 devDesc->importAudioPort(profile);
4331 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004332
François Gaffie53615e22015-03-19 09:24:12 +01004333 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004334 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4335 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004336 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004337 NULL/*patch handle*/, address.string());
4338 }
Eric Laurente552edb2014-03-10 17:42:56 -07004339 ALOGV("checkOutputsForDevice(): adding output %d", output);
4340 }
4341 }
4342
4343 if (profiles.isEmpty()) {
4344 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4345 return BAD_VALUE;
4346 }
Eric Laurentd4692962014-05-05 18:13:44 -07004347 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004348 // check if one opened output is not needed any more after disconnecting one device
4349 for (size_t i = 0; i < mOutputs.size(); i++) {
4350 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004351 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004352 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004353 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004354 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004355 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004356 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004357 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4358 mOutputs.keyAt(i));
4359 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004360 }
Eric Laurente552edb2014-03-10 17:42:56 -07004361 }
4362 }
Eric Laurentd4692962014-05-05 18:13:44 -07004363 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004364 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004365 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4366 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004367 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004368 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004369 "clearing direct output profile %zu on module %s",
4370 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004371 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004372 }
4373 }
4374 }
4375 }
4376 return NO_ERROR;
4377}
4378
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004379status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004380 audio_policy_dev_state_t state,
4381 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004382 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004383{
Paul McLean9080a4c2015-06-18 08:24:02 -07004384 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004385 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004386
4387 if (audio_device_is_digital(device)) {
4388 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004389 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004390 }
4391
Eric Laurentd4692962014-05-05 18:13:44 -07004392 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4393 // first list already open inputs that can be routed to this device
4394 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4395 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004396 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004397 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4398 inputs.add(mInputs.keyAt(input_index));
4399 }
4400 }
4401
4402 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004403 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004404 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004405 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004406 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004407 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004408 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004409
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004410 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004411 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004412 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004413 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004414 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4415 profile_index, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004416 }
Eric Laurentd4692962014-05-05 18:13:44 -07004417 }
4418 }
4419 }
4420
4421 if (profiles.isEmpty() && inputs.isEmpty()) {
4422 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4423 return BAD_VALUE;
4424 }
4425
4426 // open inputs for matching profiles if needed. Direct inputs are also opened to
4427 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4428 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4429
Eric Laurent1c333e22014-05-20 10:48:17 -07004430 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004431
Eric Laurentd4692962014-05-05 18:13:44 -07004432 // nothing to do if one input is already opened for this profile
4433 size_t input_index;
4434 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4435 desc = mInputs.valueAt(input_index);
4436 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004437 if (audio_device_is_digital(device)) {
4438 devDesc->importAudioPort(profile);
4439 }
Eric Laurentd4692962014-05-05 18:13:44 -07004440 break;
4441 }
4442 }
4443 if (input_index != mInputs.size()) {
4444 continue;
4445 }
4446
Eric Laurent3974e3b2017-12-07 17:58:43 -08004447 if (!profile->canOpenNewIo()) {
4448 ALOGW("Max Input number %u already opened for this profile %s",
4449 profile->maxOpenCount, profile->getTagName().c_str());
4450 continue;
4451 }
4452
Eric Laurentfe231122017-11-17 17:48:06 -08004453 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004454 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004455 status_t status = desc->open(nullptr,
4456 device,
4457 address,
4458 AUDIO_SOURCE_MIC,
4459 AUDIO_INPUT_FLAG_NONE,
4460 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004461
Eric Laurentcf2c0212014-07-25 16:20:43 -07004462 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004463 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004464 char *param = audio_device_address_to_parameter(device, address);
4465 mpClientInterface->setParameters(input, String8(param));
4466 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004467 }
Phil Burk00eeb322016-03-31 12:41:00 -07004468 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004469 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004470 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004471 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004472 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004473 }
4474
4475 if (input != 0) {
4476 addInput(input, desc);
4477 }
4478 } // endif input != 0
4479
Eric Laurentcf2c0212014-07-25 16:20:43 -07004480 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004481 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004482 profiles.removeAt(profile_index);
4483 profile_index--;
4484 } else {
4485 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004486 if (audio_device_is_digital(device)) {
4487 devDesc->importAudioPort(profile);
4488 }
Eric Laurentd4692962014-05-05 18:13:44 -07004489 ALOGV("checkInputsForDevice(): adding input %d", input);
4490 }
4491 } // end scan profiles
4492
4493 if (profiles.isEmpty()) {
4494 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4495 return BAD_VALUE;
4496 }
4497 } else {
4498 // Disconnect
4499 // check if one opened input is not needed any more after disconnecting one device
4500 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4501 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004502 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004503 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4504 mInputs.keyAt(input_index));
4505 inputs.add(mInputs.keyAt(input_index));
4506 }
4507 }
4508 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004509 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004510 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004511 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004512 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004513 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004514 if (profile->supportDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004515 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4516 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004517 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004518 }
4519 }
4520 }
4521 } // end disconnect
4522
4523 return NO_ERROR;
4524}
4525
4526
Eric Laurente0720872014-03-11 09:30:41 -07004527void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004528{
4529 ALOGV("closeOutput(%d)", output);
4530
Eric Laurentc75307b2015-03-17 15:29:32 -07004531 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004532 if (outputDesc == NULL) {
4533 ALOGW("closeOutput() unknown output %d", output);
4534 return;
4535 }
François Gaffie036e1e92015-03-19 10:16:24 +01004536 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004537
Eric Laurente552edb2014-03-10 17:42:56 -07004538 // look for duplicated outputs connected to the output being removed.
4539 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004540 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004541 if (dupOutputDesc->isDuplicated() &&
4542 (dupOutputDesc->mOutput1 == outputDesc ||
4543 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004544 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004545 if (dupOutputDesc->mOutput1 == outputDesc) {
4546 outputDesc2 = dupOutputDesc->mOutput2;
4547 } else {
4548 outputDesc2 = dupOutputDesc->mOutput1;
4549 }
4550 // As all active tracks on duplicated output will be deleted,
4551 // and as they were also referenced on the other output, the reference
4552 // count for their stream type must be adjusted accordingly on
4553 // the other output.
Andy Hungaf036da2018-09-21 10:46:21 -07004554 const bool wasActive = outputDesc2->isActive();
4555 for (const auto &clientPair : dupOutputDesc->getActiveClients()) {
4556 outputDesc2->changeStreamActiveCount(clientPair.first, -clientPair.second);
Eric Laurente552edb2014-03-10 17:42:56 -07004557 }
Eric Laurent733ce942017-12-07 12:18:25 -08004558 // stop() will be a no op if the output is still active but is needed in case all
4559 // active streams refcounts where cleared above
4560 if (wasActive) {
4561 outputDesc2->stop();
4562 }
Eric Laurente552edb2014-03-10 17:42:56 -07004563 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4564 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4565
4566 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004567 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004568 }
4569 }
4570
Eric Laurent05b90f82014-08-27 15:32:29 -07004571 nextAudioPortGeneration();
4572
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004573 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004574 if (index >= 0) {
4575 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004576 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004577 mAudioPatches.removeItemsAt(index);
4578 mpClientInterface->onAudioPatchListUpdate();
4579 }
4580
Eric Laurentfe231122017-11-17 17:48:06 -08004581 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004582
François Gaffie53615e22015-03-19 09:24:12 +01004583 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004584 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10004585
4586 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
4587 // no direct outputs are open.
4588 if (getMsdAudioOutDeviceTypes() != AUDIO_DEVICE_NONE) {
4589 bool directOutputOpen = false;
4590 for (size_t i = 0; i < mOutputs.size(); i++) {
4591 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
4592 directOutputOpen = true;
4593 break;
4594 }
4595 }
4596 if (!directOutputOpen) {
4597 ALOGV("no direct outputs open, reset MSD patch");
4598 setMsdPatch();
4599 }
4600 }
Eric Laurent05b90f82014-08-27 15:32:29 -07004601}
4602
4603void AudioPolicyManager::closeInput(audio_io_handle_t input)
4604{
4605 ALOGV("closeInput(%d)", input);
4606
4607 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4608 if (inputDesc == NULL) {
4609 ALOGW("closeInput() unknown input %d", input);
4610 return;
4611 }
4612
Eric Laurent6a94d692014-05-20 11:18:06 -07004613 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004614
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004615 audio_devices_t device = inputDesc->mDevice;
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004616 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004617 if (index >= 0) {
4618 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004619 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004620 mAudioPatches.removeItemsAt(index);
4621 mpClientInterface->onAudioPatchListUpdate();
4622 }
4623
Eric Laurentfe231122017-11-17 17:48:06 -08004624 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004625 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004626
4627 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
4628 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
4629 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
4630 SoundTrigger::setCaptureState(false);
4631 }
Eric Laurente552edb2014-03-10 17:42:56 -07004632}
4633
Eric Laurentc75307b2015-03-17 15:29:32 -07004634SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4635 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004636 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004637{
4638 SortedVector<audio_io_handle_t> outputs;
4639
4640 ALOGVV("getOutputsForDevice() device %04x", device);
4641 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004642 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004643 i, openOutputs.valueAt(i)->isDuplicated(),
4644 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004645 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4646 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4647 outputs.add(openOutputs.keyAt(i));
4648 }
4649 }
4650 return outputs;
4651}
4652
Mikhail Naganov37977152018-07-11 15:54:44 -07004653void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
4654{
4655 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
4656 // output is suspended before any tracks are moved to it
4657 checkA2dpSuspend();
4658 checkOutputForAllStrategies();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004659 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07004660 updateDevicesAndOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004661 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
4662 setMsdPatch();
4663 }
Mikhail Naganov37977152018-07-11 15:54:44 -07004664}
4665
Eric Laurente0720872014-03-11 09:30:41 -07004666void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004667{
4668 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4669 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4670 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4671 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4672
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004673 // also take into account external policy-related changes: add all outputs which are
4674 // associated with policies in the "before" and "after" output vectors
4675 ALOGVV("checkOutputForStrategy(): policy related outputs");
4676 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004677 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004678 if (desc != 0 && desc->mPolicyMix != NULL) {
4679 srcOutputs.add(desc->mIoHandle);
4680 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4681 }
4682 }
4683 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004684 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004685 if (desc != 0 && desc->mPolicyMix != NULL) {
4686 dstOutputs.add(desc->mIoHandle);
4687 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4688 }
4689 }
4690
Mikhail Naganov9de8bd12018-07-23 16:41:31 -07004691 if (srcOutputs != dstOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004692 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4693 // audio from invalidated tracks will be rendered when unmuting
4694 uint32_t maxLatency = 0;
4695 for (audio_io_handle_t srcOut : srcOutputs) {
4696 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4697 if (desc != 0 && maxLatency < desc->latency()) {
4698 maxLatency = desc->latency();
4699 }
4700 }
Eric Laurente552edb2014-03-10 17:42:56 -07004701 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4702 strategy, srcOutputs[0], dstOutputs[0]);
4703 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004704 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004705 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4706 if (desc != 0 && isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004707 setStrategyMute(strategy, true, desc);
Eric Laurentac3a6902018-05-11 16:39:10 -07004708 setStrategyMute(strategy, false, desc, maxLatency * LATENCY_MUTE_FACTOR, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004709 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004710 sp<SourceClientDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004711 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004712 if (source != 0){
4713 connectAudioSource(source);
4714 }
Eric Laurente552edb2014-03-10 17:42:56 -07004715 }
4716
4717 // Move effects associated to this strategy from previous output to new output
4718 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004719 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004720 }
4721 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004722 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004723 if (getStrategy((audio_stream_type_t)i) == strategy) {
4724 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004725 }
4726 }
4727 }
4728}
4729
Eric Laurente0720872014-03-11 09:30:41 -07004730void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004731{
François Gaffie2110e042015-03-24 08:41:51 +01004732 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004733 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004734 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004735 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004736 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004737 checkOutputForStrategy(STRATEGY_SONIFICATION);
4738 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004739 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004740 checkOutputForStrategy(STRATEGY_MEDIA);
4741 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004742 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004743}
4744
Eric Laurente0720872014-03-11 09:30:41 -07004745void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004746{
François Gaffie53615e22015-03-19 09:24:12 +01004747 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004748 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004749 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004750 return;
4751 }
4752
Eric Laurent3a4311c2014-03-17 12:00:47 -07004753 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004754 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4755 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4756 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004757
4758 // if suspended, restore A2DP output if:
4759 // ((SCO device is NOT connected) ||
4760 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4761 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004762 //
Eric Laurentf732e072016-08-03 19:30:28 -07004763 // if not suspended, suspend A2DP output if:
4764 // (SCO device is connected) &&
4765 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4766 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004767 //
4768 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004769 if (!isScoConnected ||
4770 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4771 AUDIO_POLICY_FORCE_BT_SCO) &&
4772 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4773 AUDIO_POLICY_FORCE_BT_SCO) &&
4774 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004775 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004776
4777 mpClientInterface->restoreOutput(a2dpOutput);
4778 mA2dpSuspended = false;
4779 }
4780 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004781 if (isScoConnected &&
4782 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4783 AUDIO_POLICY_FORCE_BT_SCO) ||
4784 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4785 AUDIO_POLICY_FORCE_BT_SCO) ||
4786 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004787 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004788
4789 mpClientInterface->suspendOutput(a2dpOutput);
4790 mA2dpSuspended = true;
4791 }
4792 }
4793}
4794
Eric Laurent97ac8712018-07-27 18:59:02 -07004795template <class IoDescriptor, class Filter>
4796sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4797 IoDescriptor& desc, Filter filter, bool& active, const DeviceVector& devices)
4798{
4799 auto activeClients = desc->clientsList(true /*activeOnly*/);
4800 auto activeClientsWithRoute =
4801 desc->clientsList(true /*activeOnly*/, filter, true /*preferredDevice*/);
4802 active = activeClients.size() > 0;
4803 if (active && activeClients.size() == activeClientsWithRoute.size()) {
4804 return devices.getDeviceFromId(activeClientsWithRoute[0]->preferredDeviceId());
4805 }
4806 return nullptr;
4807}
4808
4809template <class IoCollection, class Filter>
4810sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4811 IoCollection& ioCollection, Filter filter, const DeviceVector& devices)
4812{
4813 sp<DeviceDescriptor> device;
4814 for (size_t i = 0; i < ioCollection.size(); i++) {
4815 auto desc = ioCollection.valueAt(i);
4816 bool active;
4817 sp<DeviceDescriptor> curDevice = findPreferredDevice(desc, filter, active, devices);
4818 if (active && curDevice == nullptr) {
4819 return nullptr;
4820 } else if (curDevice != nullptr) {
4821 device = curDevice;
4822 }
4823 }
4824 return device;
4825}
4826
Eric Laurentc75307b2015-03-17 15:29:32 -07004827audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4828 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004829{
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004830 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004831 if (index >= 0) {
4832 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4833 if (patchDesc->mUid != mUidCached) {
4834 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004835 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004836 return outputDesc->device();
4837 }
4838 }
4839
Eric Laurent97ac8712018-07-27 18:59:02 -07004840 // Honor explicit routing requests only if no client using default routing is active on this
4841 // input: a specific app can not force routing for other apps by setting a preferred device.
4842 bool active; // unused
4843 sp<DeviceDescriptor> deviceDesc =
4844 findPreferredDevice(outputDesc, STRATEGY_NONE, active, mAvailableOutputDevices);
4845 if (deviceDesc != nullptr) {
4846 return deviceDesc->type();
Eric Laurentf3a5a602018-05-22 18:42:55 -07004847 }
4848
Eric Laurente552edb2014-03-10 17:42:56 -07004849 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004850 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004851 // use device for strategy enforced audible
4852 // 2: we are in call or the strategy phone is active on the output:
4853 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004854 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004855 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004856 // 4: the strategy for enforced audible is active but not enforced on the output:
4857 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004858 // 5: the strategy accessibility is active on the output:
4859 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004860 // 6: the strategy "respectful" sonification is active on the output:
4861 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004862 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004863 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004864 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004865 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004866 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004867 // use device for strategy t-t-s
Eric Laurent484e9272018-06-07 17:29:23 -07004868
4869 // FIXME: extend use of isStrategyActiveOnSameModule() to all strategies
4870 // with a refined rule considering mutually exclusive devices (using same backend)
4871 // as opposed to all streams on the same audio HAL module.
Eric Laurent97ac8712018-07-27 18:59:02 -07004872 audio_devices_t device = AUDIO_DEVICE_NONE;
François Gaffiead3183e2015-03-18 16:55:35 +01004873 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004874 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004875 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4876 } else if (isInCall() ||
Eric Laurent484e9272018-06-07 17:29:23 -07004877 isStrategyActiveOnSameModule(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004878 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
Yung Ti Su3e7eb5e2018-06-13 11:48:42 +08004879 } else if (isStrategyActiveOnSameModule(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004880 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004881 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
4882 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004883 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4884 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004885 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004886 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004887 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004888 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004889 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004890 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004891 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004892 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004893 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004894 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004895 }
4896
Eric Laurent1c333e22014-05-20 10:48:17 -07004897 ALOGV("getNewOutputDevice() selected device %x", device);
4898 return device;
4899}
4900
Eric Laurentfb66dd92016-01-28 18:32:03 -08004901audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004902{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004903 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004904
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004905 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004906 if (index >= 0) {
4907 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4908 if (patchDesc->mUid != mUidCached) {
4909 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004910 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004911 return inputDesc->mDevice;
4912 }
4913 }
4914
Eric Laurent97ac8712018-07-27 18:59:02 -07004915 // Honor explicit routing requests only if no client using default routing is active on this
4916 // input: a specific app can not force routing for other apps by setting a preferred device.
4917 bool active;
4918 sp<DeviceDescriptor> deviceDesc =
4919 findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
4920 if (deviceDesc != nullptr) {
4921 return deviceDesc->type();
4922 }
4923
Eric Laurentdc95a252018-04-12 12:46:56 -07004924 // If we are not in call and no client is active on this input, this methods returns
4925 // AUDIO_DEVICE_NONE, causing the patch on the input stream to be released.
Eric Laurentfb66dd92016-01-28 18:32:03 -08004926 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
Eric Laurentdc95a252018-04-12 12:46:56 -07004927 if (source == AUDIO_SOURCE_DEFAULT && isInCall()) {
4928 source = AUDIO_SOURCE_VOICE_COMMUNICATION;
4929 }
4930 if (source != AUDIO_SOURCE_DEFAULT) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08004931 device = getDeviceAndMixForInputSource(source);
4932 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004933
Eric Laurente552edb2014-03-10 17:42:56 -07004934 return device;
4935}
4936
Eric Laurent794fde22016-03-11 09:50:45 -08004937bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4938 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004939 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004940}
4941
Eric Laurente0720872014-03-11 09:30:41 -07004942uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004943 return (uint32_t)getStrategy(stream);
4944}
4945
Eric Laurente0720872014-03-11 09:30:41 -07004946audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004947 // By checking the range of stream before calling getStrategy, we avoid
4948 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4949 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004950 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004951 return AUDIO_DEVICE_NONE;
4952 }
Eric Laurentb0688d62018-08-14 15:49:18 -07004953 audio_devices_t activeDevices = AUDIO_DEVICE_NONE;
Eric Laurent28d09f02016-03-08 10:43:05 -08004954 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004955 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4956 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004957 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004958 }
Eric Laurent794fde22016-03-11 09:50:45 -08004959 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004960 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004961 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Eric Laurentb0688d62018-08-14 15:49:18 -07004962 devices |= curDevices;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004963 for (audio_io_handle_t output : getOutputsForDevice(curDevices, mOutputs)) {
4964 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08004965 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurentb0688d62018-08-14 15:49:18 -07004966 activeDevices |= outputDesc->device();
Eric Laurent28d09f02016-03-08 10:43:05 -08004967 }
4968 }
Eric Laurente552edb2014-03-10 17:42:56 -07004969 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004970
Eric Laurentb0688d62018-08-14 15:49:18 -07004971 // Favor devices selected on active streams if any to report correct device in case of
4972 // explicit device selection
4973 if (activeDevices != AUDIO_DEVICE_NONE) {
4974 devices = activeDevices;
4975 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004976 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4977 and doesn't really need to.*/
4978 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4979 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4980 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4981 }
Eric Laurente552edb2014-03-10 17:42:56 -07004982 return devices;
4983}
4984
François Gaffie2110e042015-03-24 08:41:51 +01004985routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4986{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004987 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004988 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004989}
4990
Eric Laurent97ac8712018-07-27 18:59:02 -07004991routing_strategy AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004992 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004993 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004994 return STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004995 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004996 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004997 return STRATEGY_ENFORCED_AUDIBLE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004998 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004999 // usage to strategy mapping
Eric Laurent97ac8712018-07-27 18:59:02 -07005000 return mEngine->getStrategyForUsage(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005001}
5002
Eric Laurente0720872014-03-11 09:30:41 -07005003void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005004 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005005 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07005006 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
5007 updateDevicesAndOutputs();
5008 break;
5009 default:
5010 break;
5011 }
5012}
5013
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005014uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07005015
5016 // skip beacon mute management if a dedicated TTS output is available
5017 if (mTtsOutputAvailable) {
5018 return 0;
5019 }
5020
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005021 switch(event) {
5022 case STARTING_OUTPUT:
5023 mBeaconMuteRefCount++;
5024 break;
5025 case STOPPING_OUTPUT:
5026 if (mBeaconMuteRefCount > 0) {
5027 mBeaconMuteRefCount--;
5028 }
5029 break;
5030 case STARTING_BEACON:
5031 mBeaconPlayingRefCount++;
5032 break;
5033 case STOPPING_BEACON:
5034 if (mBeaconPlayingRefCount > 0) {
5035 mBeaconPlayingRefCount--;
5036 }
5037 break;
5038 }
5039
5040 if (mBeaconMuteRefCount > 0) {
5041 // any playback causes beacon to be muted
5042 return setBeaconMute(true);
5043 } else {
5044 // no other playback: unmute when beacon starts playing, mute when it stops
5045 return setBeaconMute(mBeaconPlayingRefCount == 0);
5046 }
5047}
5048
5049uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5050 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5051 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5052 // keep track of muted state to avoid repeating mute/unmute operations
5053 if (mBeaconMuted != mute) {
5054 // mute/unmute AUDIO_STREAM_TTS on all outputs
5055 ALOGV("\t muting %d", mute);
5056 uint32_t maxLatency = 0;
5057 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005058 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005059 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07005060 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005061 0 /*delay*/, AUDIO_DEVICE_NONE);
5062 const uint32_t latency = desc->latency() * 2;
5063 if (latency > maxLatency) {
5064 maxLatency = latency;
5065 }
5066 }
5067 mBeaconMuted = mute;
5068 return maxLatency;
5069 }
5070 return 0;
5071}
5072
Eric Laurente0720872014-03-11 09:30:41 -07005073audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01005074 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005075{
Eric Laurent97ac8712018-07-27 18:59:02 -07005076 // Honor explicit routing requests only if all active clients have a preferred route in which
5077 // case the last active client route is used
5078 sp<DeviceDescriptor> deviceDesc = findPreferredDevice(mOutputs, strategy, mAvailableOutputDevices);
5079 if (deviceDesc != nullptr) {
5080 return deviceDesc->type();
Paul McLeanaa981192015-03-21 09:55:15 -07005081 }
5082
Eric Laurente552edb2014-03-10 17:42:56 -07005083 if (fromCache) {
5084 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
5085 strategy, mDeviceForStrategy[strategy]);
5086 return mDeviceForStrategy[strategy];
5087 }
François Gaffie2110e042015-03-24 08:41:51 +01005088 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07005089}
5090
Eric Laurente0720872014-03-11 09:30:41 -07005091void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005092{
5093 for (int i = 0; i < NUM_STRATEGIES; i++) {
5094 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
5095 }
5096 mPreviousOutputs = mOutputs;
5097}
5098
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005099uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005100 audio_devices_t prevDevice,
5101 uint32_t delayMs)
5102{
5103 // mute/unmute strategies using an incompatible device combination
5104 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5105 // if unmuting, unmute only after the specified delay
5106 if (outputDesc->isDuplicated()) {
5107 return 0;
5108 }
5109
5110 uint32_t muteWaitMs = 0;
5111 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07005112 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005113
5114 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
5115 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07005116 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07005117 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
5118 bool doMute = false;
5119
5120 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
5121 doMute = true;
5122 outputDesc->mStrategyMutedByDevice[i] = true;
5123 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
5124 doMute = true;
5125 outputDesc->mStrategyMutedByDevice[i] = false;
5126 }
Eric Laurent99401132014-05-07 19:48:15 -07005127 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005128 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005129 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005130 // skip output if it does not share any device with current output
5131 if ((desc->supportedDevices() & outputDesc->supportedDevices())
5132 == AUDIO_DEVICE_NONE) {
5133 continue;
5134 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005135 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07005136 mute ? "muting" : "unmuting", i, curDevice);
5137 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005138 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005139 if (mute) {
5140 // FIXME: should not need to double latency if volume could be applied
5141 // immediately by the audioflinger mixer. We must account for the delay
5142 // between now and the next time the audioflinger thread for this output
5143 // will process a buffer (which corresponds to one buffer size,
5144 // usually 1/2 or 1/4 of the latency).
5145 if (muteWaitMs < desc->latency() * 2) {
5146 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005147 }
5148 }
5149 }
5150 }
5151 }
5152 }
5153
Eric Laurent99401132014-05-07 19:48:15 -07005154 // temporary mute output if device selection changes to avoid volume bursts due to
5155 // different per device volumes
5156 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005157 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5158 // temporary mute duration is conservatively set to 4 times the reported latency
5159 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5160 if (muteWaitMs < tempMuteWaitMs) {
5161 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005162 }
Eric Laurentdc462862016-07-19 12:29:53 -07005163
Eric Laurent99401132014-05-07 19:48:15 -07005164 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005165 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005166 // make sure that we do not start the temporary mute period too early in case of
5167 // delayed device change
5168 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005169 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07005170 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07005171 }
5172 }
5173 }
5174
Eric Laurente552edb2014-03-10 17:42:56 -07005175 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5176 if (muteWaitMs > delayMs) {
5177 muteWaitMs -= delayMs;
5178 usleep(muteWaitMs * 1000);
5179 return muteWaitMs;
5180 }
5181 return 0;
5182}
5183
Eric Laurentc75307b2015-03-17 15:29:32 -07005184uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005185 audio_devices_t device,
5186 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07005187 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005188 audio_patch_handle_t *patchHandle,
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005189 const char *address,
5190 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005191{
Eric Laurentc75307b2015-03-17 15:29:32 -07005192 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005193 AudioParameter param;
5194 uint32_t muteWaitMs;
5195
5196 if (outputDesc->isDuplicated()) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005197 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs,
5198 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
5199 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs,
5200 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005201 return muteWaitMs;
5202 }
5203 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5204 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07005205 if ((device != AUDIO_DEVICE_NONE) &&
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005206 ((device & outputDesc->supportedDevices()) == AUDIO_DEVICE_NONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005207 return 0;
5208 }
5209
5210 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07005211 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07005212
5213 audio_devices_t prevDevice = outputDesc->mDevice;
5214
Paul McLeanaa981192015-03-21 09:55:15 -07005215 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005216
5217 if (device != AUDIO_DEVICE_NONE) {
5218 outputDesc->mDevice = device;
5219 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005220
5221 // if the outputs are not materially active, there is no need to mute.
5222 if (requiresMuteCheck) {
5223 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
5224 } else {
5225 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5226 muteWaitMs = 0;
5227 }
Eric Laurente552edb2014-03-10 17:42:56 -07005228
5229 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005230 // the requested device is AUDIO_DEVICE_NONE
5231 // OR the requested device is the same as current device
5232 // AND force is not specified
5233 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07005234 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07005235 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
5236 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005237 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005238 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005239 return muteWaitMs;
5240 }
5241
5242 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07005243
Eric Laurente552edb2014-03-10 17:42:56 -07005244 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07005245 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005246 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005247 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07005248 DeviceVector deviceList;
5249 if ((address == NULL) || (strlen(address) == 0)) {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005250 deviceList = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurentc40d9692016-04-13 19:14:13 -07005251 } else {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005252 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
5253 device, String8(address));
5254 if (deviceDesc) deviceList.add(deviceDesc);
Eric Laurentc40d9692016-04-13 19:14:13 -07005255 }
5256
Eric Laurent1c333e22014-05-20 10:48:17 -07005257 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005258 PatchBuilder patchBuilder;
5259 patchBuilder.addSource(outputDesc);
Eric Laurent1c333e22014-05-20 10:48:17 -07005260 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005261 patchBuilder.addSink(deviceList.itemAt(i));
Eric Laurent1c333e22014-05-20 10:48:17 -07005262 }
Mikhail Naganovdc769682018-05-04 15:34:08 -07005263 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005264 }
bryant_liuf5e7e792014-08-19 20:07:05 +08005265
5266 // inform all input as well
5267 for (size_t i = 0; i < mInputs.size(); i++) {
5268 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01005269 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08005270 AudioParameter inputCmd = AudioParameter();
5271 ALOGV("%s: inform input %d of device:%d", __func__,
5272 inputDescriptor->mIoHandle, device);
5273 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
5274 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
5275 inputCmd.toString(),
5276 delayMs);
5277 }
5278 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005279 }
Eric Laurente552edb2014-03-10 17:42:56 -07005280
5281 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07005282 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005283
5284 return muteWaitMs;
5285}
5286
Eric Laurentc75307b2015-03-17 15:29:32 -07005287status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005288 int delayMs,
5289 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005290{
Eric Laurent6a94d692014-05-20 11:18:06 -07005291 ssize_t index;
5292 if (patchHandle) {
5293 index = mAudioPatches.indexOfKey(*patchHandle);
5294 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005295 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005296 }
5297 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005298 return INVALID_OPERATION;
5299 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005300 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5301 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005302 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005303 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005304 removeAudioPatch(patchDesc->mHandle);
5305 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005306 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005307 return status;
5308}
5309
5310status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5311 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005312 bool force,
5313 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005314{
5315 status_t status = NO_ERROR;
5316
Eric Laurent1f2f2232014-06-02 12:01:23 -07005317 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005318 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5319 inputDesc->mDevice = device;
5320
Mikhail Naganov708e0382018-05-30 09:53:04 -07005321 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005322 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005323 PatchBuilder patchBuilder;
5324 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005325 // AUDIO_SOURCE_HOTWORD is for internal use only:
5326 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07005327 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5328 auto result = usecase;
5329 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5330 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5331 }
5332 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07005333 //only one input device for now
Mikhail Naganovdc769682018-05-04 15:34:08 -07005334 addSource(deviceList.itemAt(0));
5335 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005336 }
5337 }
5338 return status;
5339}
5340
Eric Laurent6a94d692014-05-20 11:18:06 -07005341status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5342 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005343{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005344 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005345 ssize_t index;
5346 if (patchHandle) {
5347 index = mAudioPatches.indexOfKey(*patchHandle);
5348 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005349 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005350 }
5351 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005352 return INVALID_OPERATION;
5353 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005354 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5355 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005356 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005357 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005358 removeAudioPatch(patchDesc->mHandle);
5359 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005360 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005361 return status;
5362}
5363
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005364sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005365 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005366 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005367 audio_format_t& format,
5368 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005369 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005370{
5371 // Choose an input profile based on the requested capture parameters: select the first available
5372 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005373 //
5374 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5375 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005376
Glenn Kasten730b9262018-03-29 15:01:26 -07005377 sp<IOProfile> firstInexact;
5378 uint32_t updatedSamplingRate = 0;
5379 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5380 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005381 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005382 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005383 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005384 //updatedFormat = format;
Eric Laurent275e8e92014-11-30 15:14:47 -08005385 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005386 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005387 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005388 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005389 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005390 &channelMask /*updatedChannelMask*/,
5391 // FIXME ugly cast
5392 (audio_output_flags_t) flags,
5393 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005394 return profile;
5395 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005396 if (firstInexact == nullptr && profile->isCompatibleProfile(device, address,
5397 samplingRate,
5398 &updatedSamplingRate,
5399 format,
5400 &updatedFormat,
5401 channelMask,
5402 &updatedChannelMask,
5403 // FIXME ugly cast
5404 (audio_output_flags_t) flags,
5405 false /*exactMatchRequiredForInputFlags*/)) {
5406 firstInexact = profile;
5407 }
5408
Eric Laurente552edb2014-03-10 17:42:56 -07005409 }
5410 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005411 if (firstInexact != nullptr) {
5412 samplingRate = updatedSamplingRate;
5413 format = updatedFormat;
5414 channelMask = updatedChannelMask;
5415 return firstInexact;
5416 }
Eric Laurente552edb2014-03-10 17:42:56 -07005417 return NULL;
5418}
5419
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005420
5421audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005422 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005423{
Eric Laurent97ac8712018-07-27 18:59:02 -07005424 // Honor explicit routing requests only if all active clients have a preferred route in which
5425 // case the last active client route is used
5426 sp<DeviceDescriptor> deviceDesc =
5427 findPreferredDevice(mInputs, inputSource, mAvailableInputDevices);
5428 if (deviceDesc != nullptr) {
5429 return deviceDesc->type();
5430 }
5431
5432
François Gaffie036e1e92015-03-19 10:16:24 +01005433 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5434 audio_devices_t selectedDeviceFromMix =
5435 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005436
François Gaffie036e1e92015-03-19 10:16:24 +01005437 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5438 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005439 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005440 return getDeviceForInputSource(inputSource);
5441}
5442
5443audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5444{
Eric Laurent97ac8712018-07-27 18:59:02 -07005445 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005446}
5447
Eric Laurente0720872014-03-11 09:30:41 -07005448float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005449 int index,
5450 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005451{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005452 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005453
5454 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5455 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5456 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5457 // the ringtone volume
5458 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5459 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5460 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5461 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5462 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5463 }
5464
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005465 // in-call: always cap volume by voice volume + some low headroom
5466 if ((stream != AUDIO_STREAM_VOICE_CALL) &&
Eric Laurent7731b5a2018-04-06 15:47:22 -07005467 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005468 switch (stream) {
5469 case AUDIO_STREAM_SYSTEM:
5470 case AUDIO_STREAM_RING:
5471 case AUDIO_STREAM_MUSIC:
5472 case AUDIO_STREAM_ALARM:
5473 case AUDIO_STREAM_NOTIFICATION:
5474 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5475 case AUDIO_STREAM_DTMF:
5476 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005477 int voiceVolumeIndex =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005478 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, device);
Eric Laurent7731b5a2018-04-06 15:47:22 -07005479 const float maxVoiceVolDb =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005480 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, device)
Eric Laurent7731b5a2018-04-06 15:47:22 -07005481 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005482 if (volumeDB > maxVoiceVolDb) {
5483 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5484 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5485 volumeDB = maxVoiceVolDb;
5486 }
5487 } break;
5488 default:
5489 break;
5490 }
5491 }
5492
Eric Laurente552edb2014-03-10 17:42:56 -07005493 // if a headset is connected, apply the following rules to ring tones and notifications
5494 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005495 // - always attenuate notifications volume by 6dB
5496 // - attenuate ring tones volume by 6dB unless music is not playing and
5497 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005498 // - if music is playing, always limit the volume to current music volume,
5499 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005500 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005501 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5502 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5503 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005504 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005505 AUDIO_DEVICE_OUT_USB_HEADSET |
5506 AUDIO_DEVICE_OUT_HEARING_AID)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005507 ((stream_strategy == STRATEGY_SONIFICATION)
5508 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005509 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005510 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005511 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005512 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005513 // when the phone is ringing we must consider that music could have been paused just before
5514 // by the music application and behave as if music was active if the last music track was
5515 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005516 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005517 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005518 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005519 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005520 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005521 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5522 musicDevice),
5523 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005524 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5525 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005526 if (volumeDB > minVolDB) {
5527 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005528 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005529 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005530 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5531 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5532 // on A2DP, also ensure notification volume is not too low compared to media when
5533 // intended to be played
5534 if ((volumeDB > -96.0f) &&
5535 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5536 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5537 stream, device,
5538 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5539 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5540 }
5541 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005542 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5543 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005544 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005545 }
5546 }
5547
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005548 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005549}
5550
Eric Laurent3839bc02018-07-10 18:33:34 -07005551int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
5552 audio_stream_type_t srcStream,
5553 audio_stream_type_t dstStream)
5554{
5555 if (srcStream == dstStream) {
5556 return srcIndex;
5557 }
5558 float minSrc = (float)mVolumeCurves->getVolumeIndexMin(srcStream);
5559 float maxSrc = (float)mVolumeCurves->getVolumeIndexMax(srcStream);
5560 float minDst = (float)mVolumeCurves->getVolumeIndexMin(dstStream);
5561 float maxDst = (float)mVolumeCurves->getVolumeIndexMax(dstStream);
5562
5563 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
5564}
5565
Eric Laurente0720872014-03-11 09:30:41 -07005566status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005567 int index,
5568 const sp<AudioOutputDescriptor>& outputDesc,
5569 audio_devices_t device,
5570 int delayMs,
5571 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005572{
Eric Laurente552edb2014-03-10 17:42:56 -07005573 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005574 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005575 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005576 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005577 return NO_ERROR;
5578 }
François Gaffie2110e042015-03-24 08:41:51 +01005579 audio_policy_forced_cfg_t forceUseForComm =
5580 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005581 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005582 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5583 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005584 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005585 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005586 return INVALID_OPERATION;
5587 }
5588
Eric Laurentc75307b2015-03-17 15:29:32 -07005589 if (device == AUDIO_DEVICE_NONE) {
5590 device = outputDesc->device();
5591 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005592
Eric Laurentffbc80f2015-03-18 18:30:19 -07005593 float volumeDb = computeVolume(stream, index, device);
HW Leeda7581e2018-05-22 18:31:34 +08005594 if (outputDesc->isFixedVolume(device) ||
5595 // Force VoIP volume to max for bluetooth SCO
5596 ((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
5597 (device & AUDIO_DEVICE_OUT_ALL_SCO) != 0)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005598 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005599 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005600
Eric Laurentffbc80f2015-03-18 18:30:19 -07005601 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005602
Eric Laurent3b73df72014-03-11 09:06:29 -07005603 if (stream == AUDIO_STREAM_VOICE_CALL ||
5604 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005605 float voiceVolume;
5606 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005607 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurent3839bc02018-07-10 18:33:34 -07005608 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005609 } else {
5610 voiceVolume = 1.0;
5611 }
5612
Eric Laurent18fba842016-03-31 14:41:26 -07005613 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005614 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5615 mLastVoiceVolume = voiceVolume;
5616 }
5617 }
5618
5619 return NO_ERROR;
5620}
5621
Eric Laurentc75307b2015-03-17 15:29:32 -07005622void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5623 audio_devices_t device,
5624 int delayMs,
5625 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005626{
Eric Laurentc75307b2015-03-17 15:29:32 -07005627 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005628
Eric Laurent794fde22016-03-11 09:50:45 -08005629 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005630 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005631 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005632 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005633 device,
5634 delayMs,
5635 force);
5636 }
5637}
5638
Eric Laurente0720872014-03-11 09:30:41 -07005639void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005640 bool on,
5641 const sp<AudioOutputDescriptor>& outputDesc,
5642 int delayMs,
5643 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005644{
Eric Laurent72249d52015-06-08 11:12:15 -07005645 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5646 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005647 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005648 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005649 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005650 }
5651 }
5652}
5653
Eric Laurente0720872014-03-11 09:30:41 -07005654void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005655 bool on,
5656 const sp<AudioOutputDescriptor>& outputDesc,
5657 int delayMs,
5658 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005659{
Eric Laurente552edb2014-03-10 17:42:56 -07005660 if (device == AUDIO_DEVICE_NONE) {
5661 device = outputDesc->device();
5662 }
5663
Eric Laurentc75307b2015-03-17 15:29:32 -07005664 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5665 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005666
5667 if (on) {
5668 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005669 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005670 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005671 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005672 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005673 }
5674 }
5675 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5676 outputDesc->mMuteCount[stream]++;
5677 } else {
5678 if (outputDesc->mMuteCount[stream] == 0) {
5679 ALOGV("setStreamMute() unmuting non muted stream!");
5680 return;
5681 }
5682 if (--outputDesc->mMuteCount[stream] == 0) {
5683 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005684 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005685 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005686 device,
5687 delayMs);
5688 }
5689 }
5690}
5691
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005692audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5693{
5694 // flags to stream type mapping
5695 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5696 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5697 }
5698 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5699 return AUDIO_STREAM_BLUETOOTH_SCO;
5700 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005701 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5702 return AUDIO_STREAM_TTS;
5703 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005704
Ari Hausman-Cohen5c00d012018-06-26 17:09:11 -07005705 return audio_usage_to_stream_type(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005706}
Eric Laurente83b55d2014-11-14 10:06:21 -08005707
François Gaffie53615e22015-03-19 09:24:12 +01005708bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5709{
Eric Laurente83b55d2014-11-14 10:06:21 -08005710 // has flags that map to a strategy?
5711 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5712 return true;
5713 }
5714
5715 // has known usage?
5716 switch (paa->usage) {
5717 case AUDIO_USAGE_UNKNOWN:
5718 case AUDIO_USAGE_MEDIA:
5719 case AUDIO_USAGE_VOICE_COMMUNICATION:
5720 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5721 case AUDIO_USAGE_ALARM:
5722 case AUDIO_USAGE_NOTIFICATION:
5723 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5724 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5725 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5726 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5727 case AUDIO_USAGE_NOTIFICATION_EVENT:
5728 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5729 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5730 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5731 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005732 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005733 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005734 break;
5735 default:
5736 return false;
5737 }
5738 return true;
5739}
5740
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005741bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005742 routing_strategy strategy, uint32_t inPastMs,
5743 nsecs_t sysTime) const
5744{
5745 if ((sysTime == 0) && (inPastMs != 0)) {
5746 sysTime = systemTime();
5747 }
Eric Laurent794fde22016-03-11 09:50:45 -08005748 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005749 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurent97ac8712018-07-27 18:59:02 -07005750 (STRATEGY_NONE == strategy)) &&
François Gaffiead3183e2015-03-18 16:55:35 +01005751 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5752 return true;
5753 }
5754 }
5755 return false;
5756}
5757
Eric Laurent484e9272018-06-07 17:29:23 -07005758bool AudioPolicyManager::isStrategyActiveOnSameModule(const sp<AudioOutputDescriptor>& outputDesc,
5759 routing_strategy strategy, uint32_t inPastMs,
5760 nsecs_t sysTime) const
5761{
5762 for (size_t i = 0; i < mOutputs.size(); i++) {
5763 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5764 if (outputDesc->sharesHwModuleWith(desc)
5765 && isStrategyActive(desc, strategy, inPastMs, sysTime)) {
5766 return true;
5767 }
5768 }
5769 return false;
5770}
5771
François Gaffie2110e042015-03-24 08:41:51 +01005772audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5773{
5774 return mEngine->getForceUse(usage);
5775}
5776
5777bool AudioPolicyManager::isInCall()
5778{
5779 return isStateInCall(mEngine->getPhoneState());
5780}
5781
5782bool AudioPolicyManager::isStateInCall(int state)
5783{
5784 return is_state_in_call(state);
5785}
5786
Eric Laurentd60560a2015-04-10 11:31:20 -07005787void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5788{
5789 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005790 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5791 if (sourceDesc->srcDevice()->equals(deviceDesc)) {
5792 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->portId());
5793 stopAudioSource(sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005794 }
5795 }
5796
5797 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5798 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5799 bool release = false;
5800 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5801 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5802 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5803 source->ext.device.type == deviceDesc->type()) {
5804 release = true;
5805 }
5806 }
5807 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5808 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5809 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5810 sink->ext.device.type == deviceDesc->type()) {
5811 release = true;
5812 }
5813 }
5814 if (release) {
5815 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5816 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5817 }
5818 }
5819}
5820
Phil Burk09bc4612016-02-24 15:58:15 -08005821// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005822void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5823 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005824 // TODO Set this based on Config properties.
5825 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005826
5827 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5828 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005829 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005830
jiabin81772902018-04-02 17:52:27 -07005831 // If MANUAL, keep the supported surround sound formats as current enabled ones.
5832 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
5833 formats.clear();
5834 for (auto it = mSurroundFormats.begin(); it != mSurroundFormats.end(); it++) {
5835 formats.add(*it);
Phil Burk09bc4612016-02-24 15:58:15 -08005836 }
jiabin81772902018-04-02 17:52:27 -07005837 // Always enable IEC61937 when in MANUAL mode.
5838 formats.add(AUDIO_FORMAT_IEC61937);
5839 } else { // NEVER, AUTO or ALWAYS
5840 // Analyze original support for various formats.
5841 bool supportsAC3 = false;
5842 bool supportsOtherSurround = false;
5843 bool supportsIEC61937 = false;
5844 mSurroundFormats.clear();
5845 for (ssize_t formatIndex = 0; formatIndex < (ssize_t)formats.size(); formatIndex++) {
5846 audio_format_t format = formats[formatIndex];
5847 switch (format) {
5848 case AUDIO_FORMAT_AC3:
5849 supportsAC3 = true;
5850 break;
5851 case AUDIO_FORMAT_E_AC3:
5852 case AUDIO_FORMAT_DTS:
5853 case AUDIO_FORMAT_DTS_HD:
5854 // If ALWAYS, remove all other surround formats here
5855 // since we will add them later.
5856 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5857 formats.removeAt(formatIndex);
5858 formatIndex--;
5859 }
5860 supportsOtherSurround = true;
5861 break;
5862 case AUDIO_FORMAT_IEC61937:
5863 supportsIEC61937 = true;
5864 break;
5865 default:
5866 break;
5867 }
5868 }
Phil Burk09bc4612016-02-24 15:58:15 -08005869
jiabin81772902018-04-02 17:52:27 -07005870 // Modify formats based on surround preferences.
5871 // If NEVER, remove support for surround formats.
5872 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5873 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5874 // Remove surround sound related formats.
5875 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5876 audio_format_t format = formats[formatIndex];
5877 switch(format) {
5878 case AUDIO_FORMAT_AC3:
5879 case AUDIO_FORMAT_E_AC3:
5880 case AUDIO_FORMAT_DTS:
5881 case AUDIO_FORMAT_DTS_HD:
5882 case AUDIO_FORMAT_IEC61937:
5883 formats.removeAt(formatIndex);
5884 break;
5885 default:
5886 formatIndex++; // keep it
5887 break;
5888 }
5889 }
5890 supportsAC3 = false;
5891 supportsOtherSurround = false;
5892 supportsIEC61937 = false;
5893 }
5894 } else { // AUTO or ALWAYS
5895 // Most TVs support AC3 even if they do not report it in the EDID.
5896 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
5897 && !supportsAC3) {
5898 formats.add(AUDIO_FORMAT_AC3);
5899 supportsAC3 = true;
5900 }
5901
5902 // If ALWAYS, add support for raw surround formats if all are missing.
5903 // This assumes that if any of these formats are reported by the HAL
5904 // then the report is valid and should not be modified.
5905 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5906 formats.add(AUDIO_FORMAT_E_AC3);
5907 formats.add(AUDIO_FORMAT_DTS);
5908 formats.add(AUDIO_FORMAT_DTS_HD);
5909 supportsOtherSurround = true;
5910 }
5911
5912 // Add support for IEC61937 if any raw surround supported.
5913 // The HAL could do this but add it here, just in case.
5914 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
5915 formats.add(AUDIO_FORMAT_IEC61937);
5916 supportsIEC61937 = true;
5917 }
5918
5919 // Add reported surround sound formats to enabled surround formats.
5920 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
Phil Burk07ac1142016-03-25 13:39:29 -07005921 audio_format_t format = formats[formatIndex];
5922 switch(format) {
5923 case AUDIO_FORMAT_AC3:
5924 case AUDIO_FORMAT_E_AC3:
5925 case AUDIO_FORMAT_DTS:
5926 case AUDIO_FORMAT_DTS_HD:
jiabin81772902018-04-02 17:52:27 -07005927 case AUDIO_FORMAT_AAC_LC:
5928 case AUDIO_FORMAT_DOLBY_TRUEHD:
5929 case AUDIO_FORMAT_E_AC3_JOC:
5930 mSurroundFormats.insert(format);
Phil Burk07ac1142016-03-25 13:39:29 -07005931 default:
Phil Burk07ac1142016-03-25 13:39:29 -07005932 break;
5933 }
Phil Burk09bc4612016-02-24 15:58:15 -08005934 }
Phil Burk07ac1142016-03-25 13:39:29 -07005935 }
Phil Burk09bc4612016-02-24 15:58:15 -08005936 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005937}
5938
5939// Modify the list of channel masks supported.
5940void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
5941 ChannelsVector &channelMasks = *channelMasksPtr;
5942 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5943 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5944
5945 // If NEVER, then remove support for channelMasks > stereo.
5946 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5947 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5948 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5949 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5950 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5951 channelMasks.removeAt(maskIndex);
5952 } else {
5953 maskIndex++;
5954 }
5955 }
jiabin81772902018-04-02 17:52:27 -07005956 // If ALWAYS or MANUAL, then make sure we at least support 5.1
5957 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
5958 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005959 bool supports5dot1 = false;
5960 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005961 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005962 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5963 supports5dot1 = true;
5964 break;
5965 }
5966 }
5967 // If not then add 5.1 support.
5968 if (!supports5dot1) {
5969 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
5970 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
5971 }
Phil Burk09bc4612016-02-24 15:58:15 -08005972 }
5973}
5974
Phil Burk00eeb322016-03-31 12:41:00 -07005975void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
5976 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005977 AudioProfileVector &profiles)
5978{
5979 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07005980
François Gaffie112b0af2015-11-19 16:13:25 +01005981 // Format MUST be checked first to update the list of AudioProfile
5982 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005983 reply = mpClientInterface->getParameters(
5984 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07005985 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005986 AudioParameter repliedParameters(reply);
5987 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005988 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005989 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5990 return;
5991 }
Phil Burk09bc4612016-02-24 15:58:15 -08005992 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07005993 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005994 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005995 }
Phil Burk09bc4612016-02-24 15:58:15 -08005996 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005997 }
François Gaffie112b0af2015-11-19 16:13:25 +01005998
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005999 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08006000 ChannelsVector channelMasks;
6001 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01006002 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07006003 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01006004
6005 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006006 reply = mpClientInterface->getParameters(
6007 ioHandle,
6008 requestedParameters.toString() + ";" +
6009 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01006010 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006011 AudioParameter repliedParameters(reply);
6012 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006013 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006014 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01006015 }
6016 }
6017 if (profiles.hasDynamicChannelsFor(format)) {
6018 reply = mpClientInterface->getParameters(ioHandle,
6019 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07006020 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01006021 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006022 AudioParameter repliedParameters(reply);
6023 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006024 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006025 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07006026 if (device == AUDIO_DEVICE_OUT_HDMI) {
6027 filterSurroundChannelMasks(&channelMasks);
6028 }
François Gaffie112b0af2015-11-19 16:13:25 +01006029 }
6030 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08006031 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006032 }
6033}
Eric Laurentd60560a2015-04-10 11:31:20 -07006034
Mikhail Naganovdc769682018-05-04 15:34:08 -07006035status_t AudioPolicyManager::installPatch(const char *caller,
6036 audio_patch_handle_t *patchHandle,
6037 AudioIODescriptorInterface *ioDescriptor,
6038 const struct audio_patch *patch,
6039 int delayMs)
6040{
6041 ssize_t index = mAudioPatches.indexOfKey(
6042 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6043 *patchHandle : ioDescriptor->getPatchHandle());
6044 sp<AudioPatch> patchDesc;
6045 status_t status = installPatch(
6046 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6047 if (status == NO_ERROR) {
6048 ioDescriptor->setPatchHandle(patchDesc->mHandle);
6049 }
6050 return status;
6051}
6052
6053status_t AudioPolicyManager::installPatch(const char *caller,
6054 ssize_t index,
6055 audio_patch_handle_t *patchHandle,
6056 const struct audio_patch *patch,
6057 int delayMs,
6058 uid_t uid,
6059 sp<AudioPatch> *patchDescPtr)
6060{
6061 sp<AudioPatch> patchDesc;
6062 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6063 if (index >= 0) {
6064 patchDesc = mAudioPatches.valueAt(index);
6065 afPatchHandle = patchDesc->mAfPatchHandle;
6066 }
6067
6068 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6069 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6070 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6071 if (status == NO_ERROR) {
6072 if (index < 0) {
6073 patchDesc = new AudioPatch(patch, uid);
6074 addAudioPatch(patchDesc->mHandle, patchDesc);
6075 } else {
6076 patchDesc->mPatch = *patch;
6077 }
6078 patchDesc->mAfPatchHandle = afPatchHandle;
6079 if (patchHandle) {
6080 *patchHandle = patchDesc->mHandle;
6081 }
6082 nextAudioPortGeneration();
6083 mpClientInterface->onAudioPatchListUpdate();
6084 }
6085 if (patchDescPtr) *patchDescPtr = patchDesc;
6086 return status;
6087}
6088
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006089} // namespace android