blob: c6d0a8b9638719a091325a75801be09910ba75bb [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);
Eric Laurent97ac8712018-07-27 18:59:02 -0700913 outputDesc->clientsMap().emplace(*portId, 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;
Mikhail Naganov86112352018-10-04 09:02:49 -07001113 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1114 if (msdModule != 0) {
1115 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1116 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1117 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1118 const struct audio_port_config *source = &patch->mPatch.sources[j];
1119 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1120 source->ext.device.hw_module == msdModule->getHandle()) {
1121 msdPatches.addAudioPatch(patch->mHandle, patch);
1122 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001123 }
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 }
Eric Laurent97ac8712018-07-27 18:59:02 -07001340 sp<TrackClientDescriptor> client = outputDesc->clientsMap()[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 }
Eric Laurent97ac8712018-07-27 18:59:02 -07001533 sp<TrackClientDescriptor> client = outputDesc->clientsMap()[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) {
1634 ALOGW("releaseOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001635 return;
1636 }
Eric Laurent97ac8712018-07-27 18:59:02 -07001637 sp<TrackClientDescriptor> client = outputDesc->clientsMap()[portId];
Eric Laurent8fc147b2018-07-22 19:13:55 -07001638
1639 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001640
Eric Laurent8fc147b2018-07-22 19:13:55 -07001641 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1642 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001643 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07001644 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001645 return;
1646 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001647 if (--outputDesc->mDirectOpenCount == 0) {
1648 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07001649 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001650 }
1651 }
Eric Laurent97ac8712018-07-27 18:59:02 -07001652 outputDesc->clientsMap().erase(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001653}
1654
1655
Eric Laurentcaf7f482014-11-25 17:50:47 -08001656status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1657 audio_io_handle_t *input,
1658 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001659 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001660 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001661 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001662 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001663 input_type_t *inputType,
1664 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001665{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001666 ALOGV("getInputForAttr() source %d, sampling rate %d, format %#x, channel mask %#x,"
Eric Laurentcaf7f482014-11-25 17:50:47 -08001667 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001668 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001669
Eric Laurentad2e7b92017-09-14 20:06:42 -07001670 status_t status = NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -08001671 // handle legacy remote submix case where the address was not always specified
1672 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001673 audio_source_t halInputSource;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001674 audio_source_t inputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001675 AudioMix *policyMix = NULL;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001676 DeviceVector inputDevices;
Eric Laurent8fc147b2018-07-22 19:13:55 -07001677 sp<AudioInputDescriptor> inputDesc;
1678 sp<RecordClientDescriptor> clientDesc;
1679 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001680 bool isSoundTrigger;
1681 audio_devices_t device;
1682
1683 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1684 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1685 return INVALID_OPERATION;
1686 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001687
Eric Laurentfe231122017-11-17 17:48:06 -08001688 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1689 inputSource = AUDIO_SOURCE_MIC;
1690 }
1691
Paul McLean466dc8e2015-04-17 13:15:36 -06001692 // Explicit routing?
1693 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -07001694 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
jiabinc0c831a2018-01-29 17:55:15 -08001695 deviceDesc = mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001696 }
Paul McLean466dc8e2015-04-17 13:15:36 -06001697
Eric Laurentad2e7b92017-09-14 20:06:42 -07001698 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1699 // possible
1700 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1701 *input != AUDIO_IO_HANDLE_NONE) {
1702 ssize_t index = mInputs.indexOfKey(*input);
1703 if (index < 0) {
1704 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1705 status = BAD_VALUE;
1706 goto error;
1707 }
1708 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001709 RecordClientVector clients = inputDesc->getClientsForSession(session);
1710 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001711 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1712 status = BAD_VALUE;
1713 goto error;
1714 }
1715 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1716 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001717 // corresponds to a new client and is only permitted from the same UID.
1718 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07001719 if (clients.size() > 1) {
1720 for (const auto& client : clients) {
1721 // The client map is ordered by key values (portId) and portIds are allocated
1722 // incrementaly. So the first client in this list is the one opened by audio flinger
1723 // when the mmap stream is created and should be ignored as it does not correspond
1724 // to an actual client
1725 if (client == *clients.cbegin()) {
1726 continue;
1727 }
1728 if (uid != client->uid() && !client->isSilenced()) {
1729 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
1730 uid, client->portId(), client->uid());
1731 status = INVALID_OPERATION;
1732 goto error;
1733 }
Eric Laurent331679c2018-04-16 17:03:16 -07001734 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001735 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001736 *inputType = API_INPUT_LEGACY;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001737 device = inputDesc->mDevice;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001738
Eric Laurent8f42ea12018-08-08 09:08:25 -07001739 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001740 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001741 }
1742
1743 *input = AUDIO_IO_HANDLE_NONE;
1744 *inputType = API_INPUT_INVALID;
1745
Eric Laurentad2e7b92017-09-14 20:06:42 -07001746 halInputSource = inputSource;
1747
Eric Laurentc447ded2015-01-06 08:47:05 -08001748 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001749 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001750 status = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
1751 if (status != NO_ERROR) {
1752 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001753 }
1754 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001755 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1756 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001757 } else {
Eric Laurent97ac8712018-07-27 18:59:02 -07001758 if (deviceDesc != 0) {
1759 device = deviceDesc->type();
1760 } else {
1761 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
1762 }
Eric Laurent275e8e92014-11-30 15:14:47 -08001763 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001764 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001765 status = BAD_VALUE;
1766 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001767 }
Eric Laurentc722f302014-12-10 11:21:49 -08001768 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001769 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001770 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1771 // there is an external policy, but this input is attached to a mix of recorders,
1772 // meaning it receives audio injected into the framework, so the recorder doesn't
1773 // know about it and is therefore considered "legacy"
1774 *inputType = API_INPUT_LEGACY;
1775 } else {
1776 // recording a mix of players defined by an external policy, we're rerouting for
1777 // an external policy
1778 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1779 }
Eric Laurentc722f302014-12-10 11:21:49 -08001780 } else if (audio_is_remote_submix_device(device)) {
1781 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001782 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001783 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1784 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001785 } else {
1786 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001787 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001788
Eric Laurent599c7582015-12-07 18:05:55 -08001789 }
1790
Eric Laurent8f42ea12018-08-08 09:08:25 -07001791 *input = getInputForDevice(device, address, session, inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001792 config, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001793 policyMix);
1794 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001795 status = INVALID_OPERATION;
1796 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001797 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001798
Eric Laurent8f42ea12018-08-08 09:08:25 -07001799exit:
1800
Mikhail Naganov708e0382018-05-30 09:53:04 -07001801 inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -07001802 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
Eric Laurent8f42ea12018-08-08 09:08:25 -07001803 : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07001804
Eric Laurent8f42ea12018-08-08 09:08:25 -07001805 isSoundTrigger = inputSource == AUDIO_SOURCE_HOTWORD &&
1806 mSoundTriggerSessions.indexOfKey(session) > 0;
1807 *portId = AudioPort::getNextUniqueId();
1808
Eric Laurent8fc147b2018-07-22 19:13:55 -07001809 clientDesc = new RecordClientDescriptor(*portId, uid, session,
Eric Laurent8f42ea12018-08-08 09:08:25 -07001810 *attr, *config, requestedDeviceId,
1811 inputSource,flags, isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001812 inputDesc = mInputs.valueFor(*input);
Eric Laurent97ac8712018-07-27 18:59:02 -07001813 inputDesc->clientsMap().emplace(*portId, clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001814
1815 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
1816 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001817
Eric Laurent599c7582015-12-07 18:05:55 -08001818 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001819
1820error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07001821 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001822}
1823
1824
1825audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1826 String8 address,
1827 audio_session_t session,
Eric Laurent599c7582015-12-07 18:05:55 -08001828 audio_source_t inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001829 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08001830 audio_input_flags_t flags,
1831 AudioMix *policyMix)
1832{
1833 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1834 audio_source_t halInputSource = inputSource;
1835 bool isSoundTrigger = false;
1836
1837 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1838 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1839 if (index >= 0) {
1840 input = mSoundTriggerSessions.valueFor(session);
1841 isSoundTrigger = true;
1842 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1843 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1844 } else {
1845 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001846 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001847 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08001848 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001849 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001850 }
1851
Andy Hungf129b032015-04-07 13:45:50 -07001852 // find a compatible input profile (not necessarily identical in parameters)
1853 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08001854 // sampling rate and flags may be updated by getInputProfile
1855 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
1856 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07001857 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08001858 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07001859 audio_input_flags_t profileFlags = flags;
1860 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07001861 profileFormat = config->format; // reset each time through loop, in case it is updated
Eric Laurent275e8e92014-11-30 15:14:47 -08001862 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001863 profileSamplingRate, profileFormat, profileChannelMask,
1864 profileFlags);
1865 if (profile != 0) {
1866 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001867 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1868 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001869 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1870 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1871 } else { // fail
Glenn Kastenfaa10a62017-05-25 15:52:05 -07001872 ALOGW("getInputForDevice() could not find profile for device 0x%X, "
Eric Laurentfe231122017-11-17 17:48:06 -08001873 "sampling rate %u, format %#x, channel mask 0x%X, flags %#x",
1874 device, config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001875 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001876 }
Eric Laurente552edb2014-03-10 17:42:56 -07001877 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001878 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08001879 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08001880 if (samplingRate == 0) {
1881 samplingRate = profileSamplingRate;
1882 }
Eric Laurente552edb2014-03-10 17:42:56 -07001883
Eric Laurent322b4d22015-04-03 15:57:54 -07001884 if (profile->getModuleHandle() == 0) {
1885 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001886 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001887 }
1888
Eric Laurent3974e3b2017-12-07 17:58:43 -08001889 if (!profile->canOpenNewIo()) {
1890 return AUDIO_IO_HANDLE_NONE;
1891 }
1892
Eric Laurentfe231122017-11-17 17:48:06 -08001893 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001894
Eric Laurentfe231122017-11-17 17:48:06 -08001895 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
1896 lConfig.sample_rate = profileSamplingRate;
1897 lConfig.channel_mask = profileChannelMask;
1898 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07001899
Eric Laurent53b810e2017-12-10 17:25:10 -08001900 if (address == "") {
Mikhail Naganov708e0382018-05-30 09:53:04 -07001901 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -08001902 // the inputs vector must be of size >= 1, but we don't want to crash here
1903 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress : String8("");
1904 }
1905
Eric Laurentfe231122017-11-17 17:48:06 -08001906 status_t status = inputDesc->open(&lConfig, device, address,
1907 halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001908
1909 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001910 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08001911 (profileSamplingRate != lConfig.sample_rate) ||
1912 !audio_formats_match(profileFormat, lConfig.format) ||
1913 (profileChannelMask != lConfig.channel_mask)) {
1914 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001915 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08001916 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001917 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001918 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07001919 }
Eric Laurent599c7582015-12-07 18:05:55 -08001920 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001921 }
1922
Eric Laurentc722f302014-12-10 11:21:49 -08001923 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001924
Eric Laurent599c7582015-12-07 18:05:55 -08001925 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001926 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001927
Eric Laurent599c7582015-12-07 18:05:55 -08001928 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001929}
1930
Eric Laurentbb948092017-01-23 18:33:30 -08001931//static
1932bool AudioPolicyManager::isConcurrentSource(audio_source_t source)
1933{
1934 return (source == AUDIO_SOURCE_HOTWORD) ||
1935 (source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
1936 (source == AUDIO_SOURCE_FM_TUNER);
1937}
1938
Chris Thornton2b864642017-06-27 21:26:07 -07001939// FIXME: remove when concurrent capture is ready. This is a hack to work around bug b/63083537.
1940bool AudioPolicyManager::soundTriggerSupportsConcurrentCapture() {
1941 if (!mHasComputedSoundTriggerSupportsConcurrentCapture) {
1942 bool soundTriggerSupportsConcurrentCapture = false;
1943 unsigned int numModules = 0;
1944 struct sound_trigger_module_descriptor* nModules = NULL;
1945
1946 status_t status = SoundTrigger::listModules(nModules, &numModules);
1947 if (status == NO_ERROR && numModules != 0) {
1948 nModules = (struct sound_trigger_module_descriptor*) calloc(
1949 numModules, sizeof(struct sound_trigger_module_descriptor));
1950 if (nModules == NULL) {
1951 // We failed to malloc the buffer, so just say no for now, and hope that we have more
1952 // ram the next time this function is called.
1953 ALOGE("Failed to allocate buffer for module descriptors");
1954 return false;
1955 }
1956
1957 status = SoundTrigger::listModules(nModules, &numModules);
1958 if (status == NO_ERROR) {
1959 soundTriggerSupportsConcurrentCapture = true;
1960 for (size_t i = 0; i < numModules; ++i) {
1961 soundTriggerSupportsConcurrentCapture &=
1962 nModules[i].properties.concurrent_capture;
1963 }
1964 }
1965 free(nModules);
1966 }
1967 mSoundTriggerSupportsConcurrentCapture = soundTriggerSupportsConcurrentCapture;
1968 mHasComputedSoundTriggerSupportsConcurrentCapture = true;
1969 }
1970 return mSoundTriggerSupportsConcurrentCapture;
1971}
1972
Eric Laurentfb66dd92016-01-28 18:32:03 -08001973
Eric Laurent8fc147b2018-07-22 19:13:55 -07001974status_t AudioPolicyManager::startInput(audio_port_handle_t portId,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001975 bool silenced,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001976 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07001977{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001978 *concurrency = API_INPUT_CONCURRENCY_NONE;
1979
1980 ALOGV("%s portId %d", __FUNCTION__, portId);
1981
1982 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
1983 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07001984 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001985 return BAD_VALUE;
1986 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001987 audio_io_handle_t input = inputDesc->mIoHandle;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001988 sp<RecordClientDescriptor> client = inputDesc->clientsMap()[portId];
1989 if (client->active()) {
1990 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
1991 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07001992 }
1993
Eric Laurent8f42ea12018-08-08 09:08:25 -07001994 audio_session_t session = client->session();
1995
1996 ALOGV("%s input:%d, session:%d, silenced:%d, concurrency:%d)",
1997 __FUNCTION__, input, session, silenced, *concurrency);
1998
Eric Laurent74708e72017-04-07 17:13:42 -07001999 if (!is_virtual_input_device(inputDesc->mDevice)) {
2000 if (mCallTxPatch != 0 &&
2001 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
2002 ALOGW("startInput(%d) failed: call in progress", input);
Ray Essick84e84a52018-05-03 18:45:07 -07002003 *concurrency |= API_INPUT_CONCURRENCY_CALL;
Eric Laurent74708e72017-04-07 17:13:42 -07002004 return INVALID_OPERATION;
2005 }
2006
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002007 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002008
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002009 // If a UID is idle and records silence and another not silenced recording starts
2010 // from another UID (idle or active) we stop the current idle UID recording in
2011 // favor of the new one - "There can be only one" TM
2012 if (!silenced) {
2013 for (const auto& activeDesc : activeInputs) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002014 if ((activeDesc->getAudioPort()->getFlags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002015 activeDesc->getId() == inputDesc->getId()) {
2016 continue;
2017 }
2018
Eric Laurent8f42ea12018-08-08 09:08:25 -07002019 RecordClientVector activeClients = activeDesc->clientsList(true /*activeOnly*/);
2020 for (const auto& activeClient : activeClients) {
2021 if (activeClient->isSilenced()) {
2022 closeClient(activeClient->portId());
2023 ALOGV("%s client %d stopping silenced client %d", __FUNCTION__,
2024 portId, activeClient->portId());
2025 activeInputs = mInputs.getActiveInputs();
2026 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002027 }
2028 }
2029 }
2030
2031 for (const auto& activeDesc : activeInputs) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002032 if ((client->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
Eric Laurentcb4dae22017-07-01 19:39:32 -07002033 activeDesc->getId() == inputDesc->getId()) {
2034 continue;
2035 }
2036
Eric Laurent74708e72017-04-07 17:13:42 -07002037 audio_source_t activeSource = activeDesc->inputSource(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002038 if (client->source() == AUDIO_SOURCE_HOTWORD) {
Eric Laurent74708e72017-04-07 17:13:42 -07002039 if (activeSource == AUDIO_SOURCE_HOTWORD) {
2040 if (activeDesc->hasPreemptedSession(session)) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002041 ALOGW("%s input %d failed for HOTWORD: "
2042 "other input %d already started for HOTWORD", __FUNCTION__,
Eric Laurent74708e72017-04-07 17:13:42 -07002043 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07002044 *concurrency |= API_INPUT_CONCURRENCY_HOTWORD;
Eric Laurent74708e72017-04-07 17:13:42 -07002045 return INVALID_OPERATION;
2046 }
2047 } else {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002048 ALOGV("%s input %d failed for HOTWORD: other input %d already started",
2049 __FUNCTION__, input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07002050 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07002051 return INVALID_OPERATION;
2052 }
2053 } else {
2054 if (activeSource != AUDIO_SOURCE_HOTWORD) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002055 ALOGW("%s input %d failed: other input %d already started", __FUNCTION__,
Eric Laurent74708e72017-04-07 17:13:42 -07002056 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 }
2061 }
2062
Chris Thornton2b864642017-06-27 21:26:07 -07002063 // We only need to check if the sound trigger session supports concurrent capture if the
2064 // input is also a sound trigger input. Otherwise, we should preempt any hotword stream
2065 // that's running.
2066 const bool allowConcurrentWithSoundTrigger =
2067 inputDesc->isSoundTrigger() ? soundTriggerSupportsConcurrentCapture() : false;
2068
Eric Laurent74708e72017-04-07 17:13:42 -07002069 // if capture is allowed, preempt currently active HOTWORD captures
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002070 for (const auto& activeDesc : activeInputs) {
Chris Thornton2b864642017-06-27 21:26:07 -07002071 if (allowConcurrentWithSoundTrigger && activeDesc->isSoundTrigger()) {
2072 continue;
2073 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002074 RecordClientVector activeHotwordClients =
2075 activeDesc->clientsList(true, AUDIO_SOURCE_HOTWORD);
2076 if (activeHotwordClients.size() > 0) {
Eric Laurent74708e72017-04-07 17:13:42 -07002077 SortedVector<audio_session_t> sessions = activeDesc->getPreemptedSessions();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002078
2079 for (const auto& activeClient : activeHotwordClients) {
2080 *concurrency |= API_INPUT_CONCURRENCY_PREEMPT;
2081 sessions.add(activeClient->session());
2082 closeClient(activeClient->portId());
2083 ALOGV("%s input %d for HOTWORD preempting HOTWORD input %d", __FUNCTION__,
2084 input, activeDesc->mIoHandle);
2085 }
2086
Eric Laurent74708e72017-04-07 17:13:42 -07002087 inputDesc->setPreemptedSessions(sessions);
Eric Laurent74708e72017-04-07 17:13:42 -07002088 }
2089 }
2090 }
Eric Laurente552edb2014-03-10 17:42:56 -07002091
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002092 // Make sure we start with the correct silence state
Eric Laurent8f42ea12018-08-08 09:08:25 -07002093 client->setSilenced(silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002094
Eric Laurent313d1e72016-01-29 09:56:57 -08002095 // increment activity count before calling getNewInputDevice() below as only active sessions
2096 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002097 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002098
Eric Laurent8f42ea12018-08-08 09:08:25 -07002099 // indicate active capture to sound trigger service if starting capture from a mic on
2100 // primary HW module
2101 audio_devices_t device = getNewInputDevice(inputDesc);
2102 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002103
Eric Laurent8f42ea12018-08-08 09:08:25 -07002104 status_t status = inputDesc->start();
2105 if (status != NO_ERROR) {
2106 inputDesc->setClientActive(client, false);
2107 return status;
2108 }
2109
2110 if (inputDesc->activeCount() == 1) {
2111 // if input maps to a dynamic policy with an activity listener, notify of state change
2112 if ((inputDesc->mPolicyMix != NULL)
2113 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2114 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2115 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002116 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002117
Eric Laurent8f42ea12018-08-08 09:08:25 -07002118 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2119 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2120 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
2121 SoundTrigger::setCaptureState(true);
2122 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002123
Eric Laurent8f42ea12018-08-08 09:08:25 -07002124 // automatically enable the remote submix output when input is started if not
2125 // used by a policy mix of type MIX_TYPE_RECORDERS
2126 // For remote submix (a virtual device), we open only one input per capture request.
2127 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2128 String8 address = String8("");
2129 if (inputDesc->mPolicyMix == NULL) {
2130 address = String8("0");
2131 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2132 address = inputDesc->mPolicyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002133 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002134 if (address != "") {
2135 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2136 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2137 address, "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08002138 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002139 }
Eric Laurente552edb2014-03-10 17:42:56 -07002140 }
2141
Eric Laurent8f42ea12018-08-08 09:08:25 -07002142 ALOGV("%s input %d source = %d exit", __FUNCTION__, input, client->source());
Eric Laurente552edb2014-03-10 17:42:56 -07002143
Eric Laurente552edb2014-03-10 17:42:56 -07002144 return NO_ERROR;
2145}
2146
Eric Laurent8fc147b2018-07-22 19:13:55 -07002147status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002148{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002149 ALOGV("%s portId %d", __FUNCTION__, portId);
2150
2151 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2152 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002153 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002154 return BAD_VALUE;
2155 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002156 audio_io_handle_t input = inputDesc->mIoHandle;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002157 sp<RecordClientDescriptor> client = inputDesc->clientsMap()[portId];
2158 if (!client->active()) {
2159 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002160 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002161 }
2162
Eric Laurent8f42ea12018-08-08 09:08:25 -07002163 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002164
Eric Laurent8f42ea12018-08-08 09:08:25 -07002165 inputDesc->stop();
2166 if (inputDesc->isActive()) {
2167 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2168 } else {
2169 // if input maps to a dynamic policy with an activity listener, notify of state change
2170 if ((inputDesc->mPolicyMix != NULL)
2171 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2172 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2173 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002174 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002175
2176 // automatically disable the remote submix output when input is stopped if not
2177 // used by a policy mix of type MIX_TYPE_RECORDERS
2178 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2179 String8 address = String8("");
2180 if (inputDesc->mPolicyMix == NULL) {
2181 address = String8("0");
2182 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2183 address = inputDesc->mPolicyMix->mDeviceAddress;
2184 }
2185 if (address != "") {
2186 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2187 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2188 address, "remote-submix");
2189 }
2190 }
2191
2192 audio_devices_t device = inputDesc->mDevice;
2193 resetInputDevice(input);
2194
2195 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2196 // primary HW module
2197 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2198 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2199 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
2200 SoundTrigger::setCaptureState(false);
2201 }
2202 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002203 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002204 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002205}
2206
Eric Laurent8fc147b2018-07-22 19:13:55 -07002207void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002208{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002209 ALOGV("%s portId %d", __FUNCTION__, portId);
2210
2211 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2212 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002213 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002214 return;
2215 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002216 sp<RecordClientDescriptor> client = inputDesc->clientsMap()[portId];
Eric Laurent8fc147b2018-07-22 19:13:55 -07002217 audio_io_handle_t input = inputDesc->mIoHandle;
2218
Eric Laurent8f42ea12018-08-08 09:08:25 -07002219 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002220
Eric Laurent8f42ea12018-08-08 09:08:25 -07002221 inputDesc->clientsMap().erase(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002222
Eric Laurent8f42ea12018-08-08 09:08:25 -07002223 if (inputDesc->clientsMap().size() > 0) {
2224 ALOGV("%s %zu clients remaining", __FUNCTION__, inputDesc->clientsMap().size());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002225 return;
2226 }
2227
Eric Laurent05b90f82014-08-27 15:32:29 -07002228 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002229 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002230 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002231}
2232
Eric Laurent8f42ea12018-08-08 09:08:25 -07002233void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002234{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002235 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002236
2237 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002238 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002239 }
2240}
2241
Eric Laurent8f42ea12018-08-08 09:08:25 -07002242void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2243{
2244 stopInput(portId);
2245 releaseInput(portId);
2246}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002247
Eric Laurentd4692962014-05-05 18:13:44 -07002248void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002249 bool patchRemoved = false;
2250
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002251 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002252 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002253 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002254 if (patch_index >= 0) {
2255 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002256 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002257 mAudioPatches.removeItemsAt(patch_index);
2258 patchRemoved = true;
2259 }
Eric Laurentfe231122017-11-17 17:48:06 -08002260 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002261 }
2262 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002263 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002264 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002265
2266 if (patchRemoved) {
2267 mpClientInterface->onAudioPatchListUpdate();
2268 }
Eric Laurentd4692962014-05-05 18:13:44 -07002269}
2270
Eric Laurente0720872014-03-11 09:30:41 -07002271void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002272 int indexMin,
2273 int indexMax)
2274{
2275 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002276 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002277
2278 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002279 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2280 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002281 continue;
2282 }
2283 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002284 }
Eric Laurente552edb2014-03-10 17:42:56 -07002285}
2286
Eric Laurente0720872014-03-11 09:30:41 -07002287status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002288 int index,
2289 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002290{
2291
Nadav Bar7c605f62017-12-25 00:01:52 +02002292 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2293 // app that has MODIFY_PHONE_STATE permission.
2294 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
2295 !(stream == AUDIO_STREAM_VOICE_CALL && index == 0)) ||
François Gaffied1ab2bd2015-12-02 18:20:06 +01002296 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002297 return BAD_VALUE;
2298 }
2299 if (!audio_is_output_device(device)) {
2300 return BAD_VALUE;
2301 }
2302
2303 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002304 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002305
Eric Laurent1fd372e2016-04-06 14:23:53 -07002306 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002307 stream, device, index);
2308
Eric Laurent28d09f02016-03-08 10:43:05 -08002309 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002310 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2311 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002312 continue;
2313 }
2314 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2315 }
Eric Laurente552edb2014-03-10 17:42:56 -07002316
Eric Laurent1fd372e2016-04-06 14:23:53 -07002317 // update volume on all outputs and streams matching the following:
2318 // - The requested stream (or a stream matching for volume control) is active on the output
2319 // - The device (or devices) selected by the strategy corresponding to this stream includes
2320 // the requested device
2321 // - For non default requested device, currently selected device on the output is either the
2322 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002323 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2324 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002325 status_t status = NO_ERROR;
2326 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002327 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2328 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08002329 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
Eric Laurent3839bc02018-07-10 18:33:34 -07002330 if (!(streamsMatchForvolume(stream, (audio_stream_type_t)curStream))) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002331 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002332 }
Eric Laurentdcd4ab12018-06-29 17:45:13 -07002333 if (!(desc->isStreamActive((audio_stream_type_t)curStream) || isInCall())) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002334 continue;
2335 }
Eric Laurent794fde22016-03-11 09:50:45 -08002336 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002337 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2338 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002339 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2340 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002341 continue;
2342 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002343 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002344 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002345 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07002346 applyVolume = (curDevice & curStreamDevice) != 0;
2347 } else {
2348 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002349 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002350 }
Eric Laurent3839bc02018-07-10 18:33:34 -07002351 // rescale index before applying to curStream as ranges may be different for
2352 // stream and curStream
2353 int idx = rescaleVolumeIndex(index, stream, (audio_stream_type_t)curStream);
Eric Laurente76f29c2016-09-14 17:17:53 -07002354 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002355 //FIXME: workaround for truncated touch sounds
2356 // delayed volume change for system stream to be removed when the problem is
2357 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002358 status_t volStatus =
Eric Laurent3839bc02018-07-10 18:33:34 -07002359 checkAndSetVolume((audio_stream_type_t)curStream, idx, desc, curDevice,
Eric Laurentdc462862016-07-19 12:29:53 -07002360 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002361 if (volStatus != NO_ERROR) {
2362 status = volStatus;
2363 }
2364 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002365 }
Eric Laurente552edb2014-03-10 17:42:56 -07002366 }
2367 return status;
2368}
2369
Eric Laurente0720872014-03-11 09:30:41 -07002370status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002371 int *index,
2372 audio_devices_t device)
2373{
2374 if (index == NULL) {
2375 return BAD_VALUE;
2376 }
2377 if (!audio_is_output_device(device)) {
2378 return BAD_VALUE;
2379 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002380 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002381 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002382 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002383 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2384 }
François Gaffiedfd74092015-03-19 12:10:59 +01002385 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002386
François Gaffied1ab2bd2015-12-02 18:20:06 +01002387 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002388 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2389 return NO_ERROR;
2390}
2391
Eric Laurent36829f92017-04-07 19:04:42 -07002392audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002393{
2394 // select one output among several suitable for global effects.
2395 // The priority is as follows:
2396 // 1: An offloaded output. If the effect ends up not being offloadable,
2397 // AudioFlinger will invalidate the track and the offloaded output
2398 // will be closed causing the effect to be moved to a PCM output.
2399 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002400 // 3: The primary output
2401 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002402
Eric Laurent3b73df72014-03-11 09:06:29 -07002403 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002404 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent36829f92017-04-07 19:04:42 -07002405 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002406
Eric Laurent36829f92017-04-07 19:04:42 -07002407 if (outputs.size() == 0) {
2408 return AUDIO_IO_HANDLE_NONE;
2409 }
Eric Laurente552edb2014-03-10 17:42:56 -07002410
Eric Laurent36829f92017-04-07 19:04:42 -07002411 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2412 bool activeOnly = true;
2413
2414 while (output == AUDIO_IO_HANDLE_NONE) {
2415 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2416 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2417 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2418
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002419 for (audio_io_handle_t output : outputs) {
2420 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002421 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2422 continue;
2423 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002424 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2425 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002426 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002427 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002428 }
2429 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002430 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002431 }
2432 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002433 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002434 }
2435 }
2436 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2437 output = outputOffloaded;
2438 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2439 output = outputDeepBuffer;
2440 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2441 output = outputPrimary;
2442 } else {
2443 output = outputs[0];
2444 }
2445 activeOnly = false;
2446 }
2447
2448 if (output != mMusicEffectOutput) {
2449 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2450 mMusicEffectOutput = output;
2451 }
2452
2453 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002454 return output;
2455}
2456
Eric Laurent36829f92017-04-07 19:04:42 -07002457audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2458{
2459 return selectOutputForMusicEffects();
2460}
2461
Eric Laurente0720872014-03-11 09:30:41 -07002462status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002463 audio_io_handle_t io,
2464 uint32_t strategy,
2465 int session,
2466 int id)
2467{
2468 ssize_t index = mOutputs.indexOfKey(io);
2469 if (index < 0) {
2470 index = mInputs.indexOfKey(io);
2471 if (index < 0) {
2472 ALOGW("registerEffect() unknown io %d", io);
2473 return INVALID_OPERATION;
2474 }
2475 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002476 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002477}
2478
Eric Laurentc75307b2015-03-17 15:29:32 -07002479bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2480{
Eric Laurent28d09f02016-03-08 10:43:05 -08002481 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002482 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2483 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002484 continue;
2485 }
2486 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2487 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002488 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002489}
2490
2491bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2492{
2493 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2494}
2495
Eric Laurente0720872014-03-11 09:30:41 -07002496bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002497{
2498 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002499 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002500 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002501 return true;
2502 }
2503 }
2504 return false;
2505}
2506
Eric Laurent275e8e92014-11-30 15:14:47 -08002507// Register a list of custom mixes with their attributes and format.
2508// When a mix is registered, corresponding input and output profiles are
2509// added to the remote submix hw module. The profile contains only the
2510// parameters (sampling rate, format...) specified by the mix.
2511// The corresponding input remote submix device is also connected.
2512//
2513// When a remote submix device is connected, the address is checked to select the
2514// appropriate profile and the corresponding input or output stream is opened.
2515//
2516// When capture starts, getInputForAttr() will:
2517// - 1 look for a mix matching the address passed in attribtutes tags if any
2518// - 2 if none found, getDeviceForInputSource() will:
2519// - 2.1 look for a mix matching the attributes source
2520// - 2.2 if none found, default to device selection by policy rules
2521// At this time, the corresponding output remote submix device is also connected
2522// and active playback use cases can be transferred to this mix if needed when reconnecting
2523// after AudioTracks are invalidated
2524//
2525// When playback starts, getOutputForAttr() will:
2526// - 1 look for a mix matching the address passed in attribtutes tags if any
2527// - 2 if none found, look for a mix matching the attributes usage
2528// - 3 if none found, default to device and output selection by policy rules.
2529
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002530status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002531{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002532 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2533 status_t res = NO_ERROR;
2534
2535 sp<HwModule> rSubmixModule;
2536 // examine each mix's route type
2537 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002538 AudioMix mix = mixes[i];
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002539 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
Eric Laurent97ac8712018-07-27 18:59:02 -07002540 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002541 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002542 break;
2543 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002544 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002545 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002546 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002547 rSubmixModule = mHwModules.getModuleFromName(
2548 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2549 if (rSubmixModule == 0) {
2550 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2551 i);
2552 res = INVALID_OPERATION;
2553 break;
2554 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002555 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002556
Eric Laurent97ac8712018-07-27 18:59:02 -07002557 String8 address = mix.mDeviceAddress;
2558 if (mix.mMixType == MIX_TYPE_PLAYERS) {
2559 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2560 } else {
2561 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
2562 }
François Gaffie036e1e92015-03-19 10:16:24 +01002563
Eric Laurent97ac8712018-07-27 18:59:02 -07002564 if (mPolicyMixes.registerMix(address, mix, 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002565 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002566 res = INVALID_OPERATION;
2567 break;
2568 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002569 audio_config_t outputConfig = mix.mFormat;
2570 audio_config_t inputConfig = mix.mFormat;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002571 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2572 // stereo and let audio flinger do the channel conversion if needed.
2573 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2574 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2575 rSubmixModule->addOutputProfile(address, &outputConfig,
2576 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2577 rSubmixModule->addInputProfile(address, &inputConfig,
2578 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002579
Eric Laurent97ac8712018-07-27 18:59:02 -07002580 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002581 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2582 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2583 address.string(), "remote-submix");
2584 } else {
2585 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2586 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2587 address.string(), "remote-submix");
2588 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002589 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2590 String8 address = mix.mDeviceAddress;
2591 audio_devices_t device = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002592 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2593 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002594
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002595 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002596 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2597 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2598 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2599 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2600 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2601 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002602 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2603 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002604 if (mPolicyMixes.registerMix(address, mix, desc) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002605 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002606 } else {
2607 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002608 }
2609 break;
2610 }
2611 }
2612
2613 if (res != NO_ERROR) {
2614 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002615 i, device, address.string());
2616 res = INVALID_OPERATION;
2617 break;
2618 } else if (!foundOutput) {
2619 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2620 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002621 res = INVALID_OPERATION;
2622 break;
2623 }
Eric Laurentc722f302014-12-10 11:21:49 -08002624 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002625 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002626 if (res != NO_ERROR) {
2627 unregisterPolicyMixes(mixes);
2628 }
2629 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002630}
2631
2632status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2633{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002634 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002635 status_t res = NO_ERROR;
2636 sp<HwModule> rSubmixModule;
2637 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002638 for (const auto& mix : mixes) {
2639 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002640
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002641 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002642 rSubmixModule = mHwModules.getModuleFromName(
2643 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2644 if (rSubmixModule == 0) {
2645 res = INVALID_OPERATION;
2646 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002647 }
2648 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002649
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002650 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002651
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002652 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2653 res = INVALID_OPERATION;
2654 continue;
2655 }
2656
2657 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2658 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2659 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2660 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2661 address.string(), "remote-submix");
2662 }
2663 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2664 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2665 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2666 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2667 address.string(), "remote-submix");
2668 }
2669 rSubmixModule->removeOutputProfile(address);
2670 rSubmixModule->removeInputProfile(address);
2671
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002672 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2673 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002674 res = INVALID_OPERATION;
2675 continue;
2676 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002677 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002678 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002679 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002680}
2681
Eric Laurente552edb2014-03-10 17:42:56 -07002682
Eric Laurente0720872014-03-11 09:30:41 -07002683status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002684{
Eric Laurente552edb2014-03-10 17:42:56 -07002685 String8 result;
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002686 result.appendFormat("\nAudioPolicyManager Dump: %p\n", this);
2687 result.appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07002688 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002689 std::string stateLiteral;
2690 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002691 result.appendFormat(" Phone state: %s\n", stateLiteral.c_str());
2692 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
2693 "communications", "media", "record", "dock", "system",
2694 "HDMI system audio", "encoded surround output", "vibrate ringing" };
2695 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
2696 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
2697 result.appendFormat(" Force use for %s: %d\n",
2698 forceUses[i], mEngine->getForceUse(i));
2699 }
2700 result.appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
2701 result.appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
2702 result.appendFormat(" Config source: %s\n", getConfig().getSource().c_str());
François Gaffie2110e042015-03-24 08:41:51 +01002703 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002704
François Gaffie112b0af2015-11-19 16:13:25 +01002705 mAvailableOutputDevices.dump(fd, String8("Available output"));
2706 mAvailableInputDevices.dump(fd, String8("Available input"));
Mikhail Naganovd4120142017-12-06 15:49:22 -08002707 mHwModulesAll.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002708 mOutputs.dump(fd);
2709 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002710 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002711 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002712 mAudioPatches.dump(fd);
Mikhail Naganov44344b02016-12-13 11:21:02 -08002713 mPolicyMixes.dump(fd);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07002714 mAudioSources.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002715
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002716 if (!mSurroundFormats.empty()) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07002717 result = String8("\nEnabled Surround Formats:\n");
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002718 size_t i = 0;
2719 for (const auto& fmt : mSurroundFormats) {
2720 result.append(i++ == 0 ? " " : ", ");
2721 std::string sfmt;
2722 FormatConverter::toString(fmt, sfmt);
2723 result.appendFormat("%s", sfmt.c_str());
2724 }
2725 result.append("\n");
2726 write(fd, result.string(), result.size());
2727 }
2728
Eric Laurente552edb2014-03-10 17:42:56 -07002729 return NO_ERROR;
2730}
2731
2732// This function checks for the parameters which can be offloaded.
2733// This can be enhanced depending on the capability of the DSP and policy
2734// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002735bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002736{
2737 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002738 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002739 offloadInfo.sample_rate, offloadInfo.channel_mask,
2740 offloadInfo.format,
2741 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2742 offloadInfo.has_video);
2743
Andy Hung2ddee192015-12-18 17:34:44 -08002744 if (mMasterMono) {
2745 return false; // no offloading if mono is set.
2746 }
2747
Eric Laurente552edb2014-03-10 17:42:56 -07002748 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07002749 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
2750 ALOGV("offload disabled by audio.offload.disable");
2751 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002752 }
2753
2754 // Check if stream type is music, then only allow offload as of now.
2755 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2756 {
2757 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2758 return false;
2759 }
2760
2761 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002762 const bool allowOffloadWithVideo =
2763 property_get_bool("audio.offload.video", false /* default_value */);
2764 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002765 ALOGV("isOffloadSupported: has_video == true, returning false");
2766 return false;
2767 }
2768
2769 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07002770 const int min_duration_secs = property_get_int32(
2771 "audio.offload.min.duration.secs", -1 /* default_value */);
2772 if (min_duration_secs >= 0) {
2773 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
2774 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%d)",
2775 min_duration_secs);
Eric Laurente552edb2014-03-10 17:42:56 -07002776 return false;
2777 }
2778 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2779 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2780 return false;
2781 }
2782
2783 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2784 // creating an offloaded track and tearing it down immediately after start when audioflinger
2785 // detects there is an active non offloadable effect.
2786 // FIXME: We should check the audio session here but we do not have it in this context.
2787 // This may prevent offloading in rare situations where effects are left active by apps
2788 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002789 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002790 return false;
2791 }
2792
2793 // See if there is a profile to support this.
2794 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002795 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002796 offloadInfo.sample_rate,
2797 offloadInfo.format,
2798 offloadInfo.channel_mask,
2799 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002800 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2801 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002802}
2803
Eric Laurent6a94d692014-05-20 11:18:06 -07002804status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2805 audio_port_type_t type,
2806 unsigned int *num_ports,
2807 struct audio_port *ports,
2808 unsigned int *generation)
2809{
2810 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2811 generation == NULL) {
2812 return BAD_VALUE;
2813 }
2814 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2815 if (ports == NULL) {
2816 *num_ports = 0;
2817 }
2818
2819 size_t portsWritten = 0;
2820 size_t portsMax = *num_ports;
2821 *num_ports = 0;
2822 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002823 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2824 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002825 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002826 for (const auto& dev : mAvailableOutputDevices) {
2827 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002828 continue;
2829 }
2830 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002831 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002832 }
2833 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002834 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002835 }
2836 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002837 for (const auto& dev : mAvailableInputDevices) {
2838 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002839 continue;
2840 }
2841 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002842 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002843 }
2844 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002845 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002846 }
2847 }
2848 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2849 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2850 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2851 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2852 }
2853 *num_ports += mInputs.size();
2854 }
2855 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002856 size_t numOutputs = 0;
2857 for (size_t i = 0; i < mOutputs.size(); i++) {
2858 if (!mOutputs[i]->isDuplicated()) {
2859 numOutputs++;
2860 if (portsWritten < portsMax) {
2861 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2862 }
2863 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002864 }
Eric Laurent84c70242014-06-23 08:46:27 -07002865 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002866 }
2867 }
2868 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002869 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002870 return NO_ERROR;
2871}
2872
Eric Laurent99fcae42018-05-17 16:59:18 -07002873status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07002874{
Eric Laurent99fcae42018-05-17 16:59:18 -07002875 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
2876 return BAD_VALUE;
2877 }
2878 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
2879 if (dev != 0) {
2880 dev->toAudioPort(port);
2881 return NO_ERROR;
2882 }
2883 dev = mAvailableInputDevices.getDeviceFromId(port->id);
2884 if (dev != 0) {
2885 dev->toAudioPort(port);
2886 return NO_ERROR;
2887 }
2888 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
2889 if (out != 0) {
2890 out->toAudioPort(port);
2891 return NO_ERROR;
2892 }
2893 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
2894 if (in != 0) {
2895 in->toAudioPort(port);
2896 return NO_ERROR;
2897 }
2898 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002899}
2900
Eric Laurent6a94d692014-05-20 11:18:06 -07002901status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2902 audio_patch_handle_t *handle,
2903 uid_t uid)
2904{
2905 ALOGV("createAudioPatch()");
2906
2907 if (handle == NULL || patch == NULL) {
2908 return BAD_VALUE;
2909 }
2910 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2911
Mikhail Naganovac9858b2018-06-15 13:12:37 -07002912 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07002913 return BAD_VALUE;
2914 }
2915 // only one source per audio patch supported for now
2916 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002917 return INVALID_OPERATION;
2918 }
Eric Laurent874c42872014-08-08 15:13:39 -07002919
2920 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002921 return INVALID_OPERATION;
2922 }
Eric Laurent874c42872014-08-08 15:13:39 -07002923 for (size_t i = 0; i < patch->num_sinks; i++) {
2924 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2925 return INVALID_OPERATION;
2926 }
2927 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002928
2929 sp<AudioPatch> patchDesc;
2930 ssize_t index = mAudioPatches.indexOfKey(*handle);
2931
Eric Laurent6a94d692014-05-20 11:18:06 -07002932 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2933 patch->sources[0].role,
2934 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002935#if LOG_NDEBUG == 0
2936 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002937 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002938 patch->sinks[i].role,
2939 patch->sinks[i].type);
2940 }
2941#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002942
2943 if (index >= 0) {
2944 patchDesc = mAudioPatches.valueAt(index);
2945 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2946 mUidCached, patchDesc->mUid, uid);
2947 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2948 return INVALID_OPERATION;
2949 }
2950 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002951 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002952 }
2953
2954 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002955 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002956 if (outputDesc == NULL) {
2957 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2958 return BAD_VALUE;
2959 }
Eric Laurent84c70242014-06-23 08:46:27 -07002960 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2961 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002962 if (patchDesc != 0) {
2963 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2964 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2965 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2966 return BAD_VALUE;
2967 }
2968 }
Eric Laurent874c42872014-08-08 15:13:39 -07002969 DeviceVector devices;
2970 for (size_t i = 0; i < patch->num_sinks; i++) {
2971 // Only support mix to devices connection
2972 // TODO add support for mix to mix connection
2973 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2974 ALOGV("createAudioPatch() source mix but sink is not a device");
2975 return INVALID_OPERATION;
2976 }
2977 sp<DeviceDescriptor> devDesc =
2978 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2979 if (devDesc == 0) {
2980 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2981 return BAD_VALUE;
2982 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002983
François Gaffie53615e22015-03-19 09:24:12 +01002984 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002985 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002986 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002987 NULL, // updatedSamplingRate
2988 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002989 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002990 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002991 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002992 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002993 ALOGV("createAudioPatch() profile not supported for device %08x",
2994 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002995 return INVALID_OPERATION;
2996 }
2997 devices.add(devDesc);
2998 }
2999 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003000 return INVALID_OPERATION;
3001 }
Eric Laurent874c42872014-08-08 15:13:39 -07003002
Eric Laurent6a94d692014-05-20 11:18:06 -07003003 // TODO: reconfigure output format and channels here
3004 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07003005 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07003006 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003007 index = mAudioPatches.indexOfKey(*handle);
3008 if (index >= 0) {
3009 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3010 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
3011 }
3012 patchDesc = mAudioPatches.valueAt(index);
3013 patchDesc->mUid = uid;
3014 ALOGV("createAudioPatch() success");
3015 } else {
3016 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
3017 return INVALID_OPERATION;
3018 }
3019 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3020 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3021 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003022 // only one sink supported when connecting an input device to a mix
3023 if (patch->num_sinks > 1) {
3024 return INVALID_OPERATION;
3025 }
François Gaffie53615e22015-03-19 09:24:12 +01003026 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003027 if (inputDesc == NULL) {
3028 return BAD_VALUE;
3029 }
3030 if (patchDesc != 0) {
3031 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3032 return BAD_VALUE;
3033 }
3034 }
3035 sp<DeviceDescriptor> devDesc =
3036 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
3037 if (devDesc == 0) {
3038 return BAD_VALUE;
3039 }
3040
François Gaffie53615e22015-03-19 09:24:12 +01003041 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08003042 devDesc->mAddress,
3043 patch->sinks[0].sample_rate,
3044 NULL, /*updatedSampleRate*/
3045 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003046 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003047 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003048 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003049 // FIXME for the parameter type,
3050 // and the NONE
3051 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003052 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003053 return INVALID_OPERATION;
3054 }
3055 // TODO: reconfigure output format and channels here
3056 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01003057 devDesc->type(), inputDesc->mIoHandle);
3058 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003059 index = mAudioPatches.indexOfKey(*handle);
3060 if (index >= 0) {
3061 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3062 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
3063 }
3064 patchDesc = mAudioPatches.valueAt(index);
3065 patchDesc->mUid = uid;
3066 ALOGV("createAudioPatch() success");
3067 } else {
3068 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
3069 return INVALID_OPERATION;
3070 }
3071 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3072 // device to device connection
3073 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003074 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003075 return BAD_VALUE;
3076 }
3077 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003078 sp<DeviceDescriptor> srcDeviceDesc =
3079 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07003080 if (srcDeviceDesc == 0) {
3081 return BAD_VALUE;
3082 }
Eric Laurent874c42872014-08-08 15:13:39 -07003083
Eric Laurent6a94d692014-05-20 11:18:06 -07003084 //update source and sink with our own data as the data passed in the patch may
3085 // be incomplete.
3086 struct audio_patch newPatch = *patch;
3087 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003088
Eric Laurent874c42872014-08-08 15:13:39 -07003089 for (size_t i = 0; i < patch->num_sinks; i++) {
3090 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3091 ALOGV("createAudioPatch() source device but one sink is not a device");
3092 return INVALID_OPERATION;
3093 }
3094
3095 sp<DeviceDescriptor> sinkDeviceDesc =
3096 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3097 if (sinkDeviceDesc == 0) {
3098 return BAD_VALUE;
3099 }
3100 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
3101
Eric Laurent3bcf8592015-04-03 12:13:24 -07003102 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003103 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003104 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08003105 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003106 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003107 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003108 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003109 return INVALID_OPERATION;
3110 }
Eric Laurent874c42872014-08-08 15:13:39 -07003111 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01003112 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003113 // if the sink device is reachable via an opened output stream, request to go via
3114 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07003115 audio_io_handle_t output = selectOutput(outputs,
3116 AUDIO_OUTPUT_FLAG_NONE,
3117 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07003118 if (output != AUDIO_IO_HANDLE_NONE) {
3119 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3120 if (outputDesc->isDuplicated()) {
3121 return INVALID_OPERATION;
3122 }
3123 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003124 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003125 newPatch.num_sources = 2;
3126 }
Eric Laurent83b88082014-06-20 18:31:16 -07003127 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003128 }
3129 // TODO: check from routing capabilities in config file and other conflicting patches
3130
Mikhail Naganovdc769682018-05-04 15:34:08 -07003131 status_t status = installPatch(__func__, index, handle, &newPatch, 0, uid, &patchDesc);
3132 if (status != NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003133 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3134 status);
3135 return INVALID_OPERATION;
3136 }
3137 } else {
3138 return BAD_VALUE;
3139 }
3140 } else {
3141 return BAD_VALUE;
3142 }
3143 return NO_ERROR;
3144}
3145
3146status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3147 uid_t uid)
3148{
3149 ALOGV("releaseAudioPatch() patch %d", handle);
3150
3151 ssize_t index = mAudioPatches.indexOfKey(handle);
3152
3153 if (index < 0) {
3154 return BAD_VALUE;
3155 }
3156 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3157 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3158 mUidCached, patchDesc->mUid, uid);
3159 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3160 return INVALID_OPERATION;
3161 }
3162
3163 struct audio_patch *patch = &patchDesc->mPatch;
3164 patchDesc->mUid = mUidCached;
3165 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003166 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003167 if (outputDesc == NULL) {
3168 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3169 return BAD_VALUE;
3170 }
3171
Eric Laurentc75307b2015-03-17 15:29:32 -07003172 setOutputDevice(outputDesc,
3173 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07003174 true,
3175 0,
3176 NULL);
3177 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3178 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003179 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003180 if (inputDesc == NULL) {
3181 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3182 return BAD_VALUE;
3183 }
3184 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003185 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003186 true,
3187 NULL);
3188 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003189 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3190 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3191 status, patchDesc->mAfPatchHandle);
3192 removeAudioPatch(patchDesc->mHandle);
3193 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003194 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003195 } else {
3196 return BAD_VALUE;
3197 }
3198 } else {
3199 return BAD_VALUE;
3200 }
3201 return NO_ERROR;
3202}
3203
3204status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3205 struct audio_patch *patches,
3206 unsigned int *generation)
3207{
François Gaffie53615e22015-03-19 09:24:12 +01003208 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003209 return BAD_VALUE;
3210 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003211 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003212 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003213}
3214
Eric Laurente1715a42014-05-20 11:30:42 -07003215status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003216{
Eric Laurente1715a42014-05-20 11:30:42 -07003217 ALOGV("setAudioPortConfig()");
3218
3219 if (config == NULL) {
3220 return BAD_VALUE;
3221 }
3222 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3223 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003224 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3225 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003226 }
3227
Eric Laurenta121f902014-06-03 13:32:54 -07003228 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003229 if (config->type == AUDIO_PORT_TYPE_MIX) {
3230 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003231 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003232 if (outputDesc == NULL) {
3233 return BAD_VALUE;
3234 }
Eric Laurent84c70242014-06-23 08:46:27 -07003235 ALOG_ASSERT(!outputDesc->isDuplicated(),
3236 "setAudioPortConfig() called on duplicated output %d",
3237 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003238 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003239 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003240 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003241 if (inputDesc == NULL) {
3242 return BAD_VALUE;
3243 }
Eric Laurenta121f902014-06-03 13:32:54 -07003244 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003245 } else {
3246 return BAD_VALUE;
3247 }
3248 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3249 sp<DeviceDescriptor> deviceDesc;
3250 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3251 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3252 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3253 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3254 } else {
3255 return BAD_VALUE;
3256 }
3257 if (deviceDesc == NULL) {
3258 return BAD_VALUE;
3259 }
Eric Laurenta121f902014-06-03 13:32:54 -07003260 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003261 } else {
3262 return BAD_VALUE;
3263 }
3264
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003265 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003266 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3267 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003268 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003269 audioPortConfig->toAudioPortConfig(&newConfig, config);
3270 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003271 }
Eric Laurenta121f902014-06-03 13:32:54 -07003272 if (status != NO_ERROR) {
3273 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003274 }
Eric Laurente1715a42014-05-20 11:30:42 -07003275
3276 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003277}
3278
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003279void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3280{
Eric Laurentd60560a2015-04-10 11:31:20 -07003281 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003282 clearAudioPatches(uid);
3283 clearSessionRoutes(uid);
3284}
3285
Eric Laurent6a94d692014-05-20 11:18:06 -07003286void AudioPolicyManager::clearAudioPatches(uid_t uid)
3287{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003288 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003289 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3290 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003291 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003292 }
3293 }
3294}
3295
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003296void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3297 audio_io_handle_t ouptutToSkip)
3298{
3299 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3300 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3301 for (size_t j = 0; j < mOutputs.size(); j++) {
3302 if (mOutputs.keyAt(j) == ouptutToSkip) {
3303 continue;
3304 }
3305 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3306 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3307 continue;
3308 }
3309 // If the default device for this strategy is on another output mix,
3310 // invalidate all tracks in this strategy to force re connection.
3311 // Otherwise select new device on the output mix.
3312 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003313 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003314 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3315 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3316 }
3317 }
3318 } else {
3319 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3320 setOutputDevice(outputDesc, newDevice, false);
3321 }
3322 }
3323}
3324
3325void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3326{
3327 // remove output routes associated with this uid
3328 SortedVector<routing_strategy> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07003329 for (size_t i = 0; i < mOutputs.size(); i++) {
3330 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3331 TrackClientMap clients = outputDesc->clientsMap();
3332 for (const auto& client : clients) {
3333 if (client.second->hasPreferredDevice() && client.second->uid() == uid) {
3334 client.second->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3335 affectedStrategies.add(getStrategy(client.second->stream()));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003336 }
3337 }
3338 }
3339 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003340 for (const auto& strategy : affectedStrategies) {
3341 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003342 }
3343
3344 // remove input routes associated with this uid
3345 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07003346 for (size_t i = 0; i < mInputs.size(); i++) {
3347 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
3348 RecordClientMap clients = inputDesc->clientsMap();
3349 for (const auto& client : clients) {
3350 if (client.second->hasPreferredDevice() && client.second->uid() == uid) {
3351 client.second->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3352 affectedSources.add(client.second->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003353 }
3354 }
3355 }
3356 // reroute inputs if necessary
3357 SortedVector<audio_io_handle_t> inputsToClose;
3358 for (size_t i = 0; i < mInputs.size(); i++) {
3359 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003360 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003361 inputsToClose.add(inputDesc->mIoHandle);
3362 }
3363 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003364 for (const auto& input : inputsToClose) {
3365 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003366 }
3367}
3368
Eric Laurentd60560a2015-04-10 11:31:20 -07003369void AudioPolicyManager::clearAudioSources(uid_t uid)
3370{
3371 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003372 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3373 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07003374 stopAudioSource(mAudioSources.keyAt(i));
3375 }
3376 }
3377}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003378
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003379status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3380 audio_io_handle_t *ioHandle,
3381 audio_devices_t *device)
3382{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003383 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3384 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003385 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003386
François Gaffiedf372692015-03-19 10:43:27 +01003387 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003388}
3389
Eric Laurentd60560a2015-04-10 11:31:20 -07003390status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003391 const audio_attributes_t *attributes,
3392 audio_port_handle_t *portId,
3393 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003394{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003395 ALOGV("%s", __FUNCTION__);
3396 *portId = AUDIO_PORT_HANDLE_NONE;
3397
3398 if (source == NULL || attributes == NULL || portId == NULL) {
3399 ALOGW("%s invalid argument: source %p attributes %p handle %p",
3400 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003401 return BAD_VALUE;
3402 }
3403
Eric Laurentd60560a2015-04-10 11:31:20 -07003404 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3405 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003406 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
3407 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003408 return INVALID_OPERATION;
3409 }
3410
3411 sp<DeviceDescriptor> srcDeviceDesc =
3412 mAvailableInputDevices.getDevice(source->ext.device.type,
3413 String8(source->ext.device.address));
3414 if (srcDeviceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003415 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003416 return BAD_VALUE;
3417 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003418
3419 *portId = AudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07003420
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003421 struct audio_patch dummyPatch = {};
Eric Laurentd60560a2015-04-10 11:31:20 -07003422 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003423
3424 sp<SourceClientDescriptor> sourceDesc =
3425 new SourceClientDescriptor(*portId, uid, *attributes, patchDesc, srcDeviceDesc,
Eric Laurent97ac8712018-07-27 18:59:02 -07003426 streamTypefromAttributesInt(attributes),
3427 getStrategyForAttr(attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07003428
3429 status_t status = connectAudioSource(sourceDesc);
3430 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003431 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003432 }
3433 return status;
3434}
3435
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003436status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003437{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003438 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003439
3440 // make sure we only have one patch per source.
3441 disconnectAudioSource(sourceDesc);
3442
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003443 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003444 routing_strategy strategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003445 audio_stream_type_t stream = sourceDesc->stream();
3446 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->srcDevice();
Eric Laurentd60560a2015-04-10 11:31:20 -07003447
3448 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3449 sp<DeviceDescriptor> sinkDeviceDesc =
3450 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3451
3452 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003453
3454 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3455 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003456 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003457 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3458 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3459 // create patch between src device and output device
3460 // create Hwoutput and add to mHwOutputs
3461 } else {
3462 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3463 audio_io_handle_t output =
3464 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3465 if (output == AUDIO_IO_HANDLE_NONE) {
3466 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3467 return INVALID_OPERATION;
3468 }
3469 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3470 if (outputDesc->isDuplicated()) {
3471 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3472 return INVALID_OPERATION;
3473 }
Eric Laurent733ce942017-12-07 12:18:25 -08003474 status_t status = outputDesc->start();
3475 if (status != NO_ERROR) {
3476 return status;
3477 }
3478
Eric Laurentd60560a2015-04-10 11:31:20 -07003479 // create a special patch with no sink and two sources:
3480 // - the second source indicates to PatchPanel through which output mix this patch should
3481 // be connected as well as the stream type for volume control
3482 // - the sink is defined by whatever output device is currently selected for the output
3483 // though which this patch is routed.
Mikhail Naganovdc769682018-05-04 15:34:08 -07003484 PatchBuilder patchBuilder;
3485 patchBuilder.addSource(srcDeviceDesc).addSource(outputDesc, { .stream = stream });
3486 status = mpClientInterface->createAudioPatch(patchBuilder.patch(),
Eric Laurentd60560a2015-04-10 11:31:20 -07003487 &afPatchHandle,
3488 0);
3489 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3490 status, afPatchHandle);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003491 sourceDesc->patchDesc()->mPatch = *patchBuilder.patch();
Eric Laurentd60560a2015-04-10 11:31:20 -07003492 if (status != NO_ERROR) {
3493 ALOGW("%s patch panel could not connect device patch, error %d",
3494 __FUNCTION__, status);
3495 return INVALID_OPERATION;
3496 }
3497 uint32_t delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07003498 status = startSource(outputDesc, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003499
3500 if (status != NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003501 mpClientInterface->releaseAudioPatch(sourceDesc->patchDesc()->mAfPatchHandle, 0);
Eric Laurentd60560a2015-04-10 11:31:20 -07003502 return status;
3503 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003504 sourceDesc->setSwOutput(outputDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003505 if (delayMs != 0) {
3506 usleep(delayMs * 1000);
3507 }
3508 }
3509
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003510 sourceDesc->patchDesc()->mAfPatchHandle = afPatchHandle;
3511 addAudioPatch(sourceDesc->patchDesc()->mHandle, sourceDesc->patchDesc());
Eric Laurentd60560a2015-04-10 11:31:20 -07003512
3513 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003514}
3515
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003516status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07003517{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003518 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
3519 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003520 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003521 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003522 return BAD_VALUE;
3523 }
3524 status_t status = disconnectAudioSource(sourceDesc);
3525
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003526 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003527 return status;
3528}
3529
Andy Hung2ddee192015-12-18 17:34:44 -08003530status_t AudioPolicyManager::setMasterMono(bool mono)
3531{
3532 if (mMasterMono == mono) {
3533 return NO_ERROR;
3534 }
3535 mMasterMono = mono;
3536 // if enabling mono we close all offloaded devices, which will invalidate the
3537 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3538 // for recreating the new AudioTrack as non-offloaded PCM.
3539 //
3540 // If disabling mono, we leave all tracks as is: we don't know which clients
3541 // and tracks are able to be recreated as offloaded. The next "song" should
3542 // play back offloaded.
3543 if (mMasterMono) {
3544 Vector<audio_io_handle_t> offloaded;
3545 for (size_t i = 0; i < mOutputs.size(); ++i) {
3546 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3547 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3548 offloaded.push(desc->mIoHandle);
3549 }
3550 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003551 for (const auto& handle : offloaded) {
3552 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003553 }
3554 }
3555 // update master mono for all remaining outputs
3556 for (size_t i = 0; i < mOutputs.size(); ++i) {
3557 updateMono(mOutputs.keyAt(i));
3558 }
3559 return NO_ERROR;
3560}
3561
3562status_t AudioPolicyManager::getMasterMono(bool *mono)
3563{
3564 *mono = mMasterMono;
3565 return NO_ERROR;
3566}
3567
Eric Laurentac9cef52017-06-09 15:46:26 -07003568float AudioPolicyManager::getStreamVolumeDB(
3569 audio_stream_type_t stream, int index, audio_devices_t device)
3570{
3571 return computeVolume(stream, index, device);
3572}
3573
jiabin81772902018-04-02 17:52:27 -07003574status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3575 audio_format_t *surroundFormats,
3576 bool *surroundFormatsEnabled,
3577 bool reported)
3578{
3579 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3580 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3581 return BAD_VALUE;
3582 }
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003583 ALOGV("getSurroundFormats() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p"
3584 " reported %d", *numSurroundFormats, surroundFormats, surroundFormatsEnabled, reported);
jiabin81772902018-04-02 17:52:27 -07003585
3586 // Only return value if there is HDMI output.
3587 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3588 return INVALID_OPERATION;
3589 }
3590
3591 size_t formatsWritten = 0;
3592 size_t formatsMax = *numSurroundFormats;
3593 *numSurroundFormats = 0;
Mikhail Naganov2563f232018-09-27 14:48:01 -07003594 std::unordered_set<audio_format_t> formats;
jiabin81772902018-04-02 17:52:27 -07003595 if (reported) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003596 // Return formats from HDMI profiles, that have already been resolved by
3597 // checkOutputsForDevice().
3598 DeviceVector hdmiOutputDevs = mAvailableOutputDevices.getDevicesFromTypeMask(
3599 AUDIO_DEVICE_OUT_HDMI);
3600 for (size_t i = 0; i < hdmiOutputDevs.size(); i++) {
3601 FormatVector supportedFormats =
3602 hdmiOutputDevs[i]->getAudioPort()->getAudioProfiles().getSupportedFormats();
3603 for (size_t j = 0; j < supportedFormats.size(); j++) {
3604 if (std::find(std::begin(SURROUND_FORMATS),
3605 std::end(SURROUND_FORMATS),
3606 supportedFormats[j]) != std::end(SURROUND_FORMATS)) {
3607 formats.insert(supportedFormats[j]);
3608 } else if (std::find(std::begin(AAC_FORMATS),
3609 std::end(AAC_FORMATS),
3610 supportedFormats[j]) != std::end(AAC_FORMATS)) {
3611 // if any format in AAC_FORMATS is reported, insert AUDIO_FORMAT_AAC_LC as this
3612 // is the only AAC format used in the TvSettings UI for all AAC formats.
3613 formats.insert(AUDIO_FORMAT_AAC_LC);
3614 }
3615 }
jiabin81772902018-04-02 17:52:27 -07003616 }
3617 } else {
3618 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003619 formats.insert(SURROUND_FORMATS[i]);
jiabin81772902018-04-02 17:52:27 -07003620 }
3621 }
Mikhail Naganov2563f232018-09-27 14:48:01 -07003622 for (const auto& format: formats) {
jiabin81772902018-04-02 17:52:27 -07003623 if (formatsWritten < formatsMax) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003624 surroundFormats[formatsWritten] = format;
jiabin81772902018-04-02 17:52:27 -07003625 bool formatEnabled = false;
Mikhail Naganov2563f232018-09-27 14:48:01 -07003626 if (format == AUDIO_FORMAT_AAC_LC) {
3627 for (size_t j = 0; j < ARRAY_SIZE(AAC_FORMATS) && !formatEnabled; j++) {
jiabin81772902018-04-02 17:52:27 -07003628 formatEnabled =
Mikhail Naganov2563f232018-09-27 14:48:01 -07003629 mSurroundFormats.find(AAC_FORMATS[j]) != mSurroundFormats.end();
jiabin81772902018-04-02 17:52:27 -07003630 }
3631 } else {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003632 formatEnabled = mSurroundFormats.find(format) != mSurroundFormats.end();
jiabin81772902018-04-02 17:52:27 -07003633 }
3634 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3635 }
3636 (*numSurroundFormats)++;
3637 }
3638 return NO_ERROR;
3639}
3640
3641status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3642{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003643 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
jiabin81772902018-04-02 17:52:27 -07003644 // Check if audio format is a surround formats.
3645 bool isSurroundFormat = false;
3646 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3647 if (audioFormat == SURROUND_FORMATS[i]) {
3648 isSurroundFormat = true;
3649 break;
3650 }
3651 }
3652 if (!isSurroundFormat) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003653 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07003654 return BAD_VALUE;
3655 }
3656
3657 // Should only be called when MANUAL.
3658 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3659 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
3660 if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003661 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07003662 return INVALID_OPERATION;
3663 }
3664
3665 if ((mSurroundFormats.find(audioFormat) != mSurroundFormats.end() && enabled)
3666 || (mSurroundFormats.find(audioFormat) == mSurroundFormats.end() && !enabled)) {
3667 return NO_ERROR;
3668 }
3669
3670 // The operation is valid only when there is HDMI output available.
3671 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003672 ALOGW("%s() no HDMI out devices found", __func__);
jiabin81772902018-04-02 17:52:27 -07003673 return INVALID_OPERATION;
3674 }
3675
Mikhail Naganov2563f232018-09-27 14:48:01 -07003676 std::unordered_set<audio_format_t> surroundFormatsBackup(mSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07003677 if (enabled) {
3678 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3679 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3680 mSurroundFormats.insert(AAC_FORMATS[i]);
3681 }
3682 } else {
3683 mSurroundFormats.insert(audioFormat);
3684 }
3685 } else {
3686 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3687 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3688 mSurroundFormats.erase(AAC_FORMATS[i]);
3689 }
3690 } else {
3691 mSurroundFormats.erase(audioFormat);
3692 }
3693 }
3694
3695 sp<SwAudioOutputDescriptor> outputDesc;
3696 bool profileUpdated = false;
Mikhail Naganov708e0382018-05-30 09:53:04 -07003697 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003698 AUDIO_DEVICE_OUT_HDMI);
3699 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3700 // Simulate reconnection to update enabled surround sound formats.
3701 String8 address = hdmiOutputDevices[i]->mAddress;
3702 String8 name = hdmiOutputDevices[i]->getName();
3703 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3704 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3705 address.c_str(),
3706 name.c_str());
3707 if (status != NO_ERROR) {
3708 continue;
3709 }
3710 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3711 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3712 address.c_str(),
3713 name.c_str());
3714 profileUpdated |= (status == NO_ERROR);
3715 }
Mikhail Naganov708e0382018-05-30 09:53:04 -07003716 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003717 AUDIO_DEVICE_IN_HDMI);
3718 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3719 // Simulate reconnection to update enabled surround sound formats.
3720 String8 address = hdmiInputDevices[i]->mAddress;
3721 String8 name = hdmiInputDevices[i]->getName();
3722 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3723 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3724 address.c_str(),
3725 name.c_str());
3726 if (status != NO_ERROR) {
3727 continue;
3728 }
3729 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3730 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3731 address.c_str(),
3732 name.c_str());
3733 profileUpdated |= (status == NO_ERROR);
3734 }
3735
3736 // Undo the surround formats change due to no audio profiles updated.
3737 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003738 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov2563f232018-09-27 14:48:01 -07003739 mSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07003740 }
3741
3742 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3743}
3744
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003745void AudioPolicyManager::setRecordSilenced(uid_t uid, bool silenced)
3746{
3747 ALOGV("AudioPolicyManager:setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
3748
3749 Vector<sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
3750 for (size_t i = 0; i < activeInputs.size(); i++) {
3751 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
Eric Laurent8f42ea12018-08-08 09:08:25 -07003752 RecordClientVector clients = activeDesc->clientsList(true /*activeOnly*/);
3753 for (const auto& client : clients) {
3754 if (uid == client->uid()) {
3755 client->setSilenced(silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003756 }
3757 }
3758 }
3759}
3760
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003761status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003762{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003763 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003764
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003765 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003766 if (patchDesc == 0) {
3767 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003768 sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003769 return BAD_VALUE;
3770 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003771 removeAudioPatch(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003772
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003773 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003774 if (swOutputDesc != 0) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003775 status_t status = stopSource(swOutputDesc, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08003776 if (status == NO_ERROR) {
3777 swOutputDesc->stop();
3778 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003779 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3780 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003781 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003782 if (hwOutputDesc != 0) {
3783 // release patch between src device and output device
3784 // close Hwoutput and remove from mHwOutputs
3785 } else {
3786 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3787 }
3788 }
3789 return NO_ERROR;
3790}
3791
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003792sp<SourceClientDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
Eric Laurentd60560a2015-04-10 11:31:20 -07003793 audio_io_handle_t output, routing_strategy strategy)
3794{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003795 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07003796 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003797 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3798 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003799 routing_strategy sourceStrategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003800 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003801 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3802 source = sourceDesc;
3803 break;
3804 }
3805 }
3806 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003807}
3808
Eric Laurente552edb2014-03-10 17:42:56 -07003809// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003810// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003811// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003812uint32_t AudioPolicyManager::nextAudioPortGeneration()
3813{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003814 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003815}
3816
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003817#ifdef USE_XML_AUDIO_POLICY_CONF
3818// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3819static const char *kConfigLocationList[] =
3820 {"/odm/etc", "/vendor/etc", "/system/etc"};
3821static const int kConfigLocationListSize =
3822 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3823
3824static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3825 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07003826 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003827 status_t ret;
3828
Petri Gyntherf497f292018-04-17 18:46:10 -07003829 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
3830 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
3831 // A2DP offload supported but disabled: try to use special XML file
3832 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
3833 }
3834 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3835
3836 for (const char* fileName : fileNames) {
3837 for (int i = 0; i < kConfigLocationListSize; i++) {
Petri Gyntherf497f292018-04-17 18:46:10 -07003838 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
3839 "%s/%s", kConfigLocationList[i], fileName);
Mikhail Naganova289aea2018-09-17 15:26:23 -07003840 ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile, &config);
Petri Gyntherf497f292018-04-17 18:46:10 -07003841 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003842 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07003843 return ret;
3844 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003845 }
3846 }
3847 return ret;
3848}
3849#endif
3850
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003851AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
3852 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07003853 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07003854 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003855 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07003856 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003857 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003858#ifdef USE_XML_AUDIO_POLICY_CONF
3859 mVolumeCurves(new VolumeCurvesCollection()),
3860 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08003861 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003862#else
3863 mVolumeCurves(new StreamDescriptorCollection()),
3864 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
3865 mDefaultOutputDevice),
3866#endif
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003867 mAudioPortGeneration(1),
3868 mBeaconMuteRefCount(0),
3869 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003870 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003871 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003872 mMasterMono(false),
Chris Thornton2b864642017-06-27 21:26:07 -07003873 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE),
3874 mHasComputedSoundTriggerSupportsConcurrentCapture(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003875{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003876}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003877
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003878AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
3879 : AudioPolicyManager(clientInterface, false /*forTesting*/)
3880{
3881 loadConfig();
3882 initialize();
3883}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003884
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003885void AudioPolicyManager::loadConfig() {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003886#ifdef USE_XML_AUDIO_POLICY_CONF
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003887 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003888#else
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003889 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, getConfig()) != NO_ERROR)
3890 && (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, getConfig()) != NO_ERROR)) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003891#endif
3892 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003893 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01003894 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003895}
3896
3897status_t AudioPolicyManager::initialize() {
3898 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01003899
3900 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003901 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3902 if (!engineInstance) {
3903 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003904 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003905 }
3906 // Retrieve the Policy Manager Interface
3907 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3908 if (mEngine == NULL) {
3909 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003910 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003911 }
3912 mEngine->setObserver(this);
3913 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003914 if (status != NO_ERROR) {
3915 LOG_FATAL("Policy engine not initialized(err=%d)", status);
3916 return status;
3917 }
François Gaffie2110e042015-03-24 08:41:51 +01003918
Eric Laurent3a4311c2014-03-17 12:00:47 -07003919 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003920 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003921 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3922 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Mikhail Naganovd4120142017-12-06 15:49:22 -08003923 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003924 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08003925 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
3926 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003927 continue;
3928 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08003929 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07003930 // open all output streams needed to access attached devices
3931 // except for direct output streams that are only opened when they are actually
3932 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003933 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003934 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003935 if (!outProfile->canOpenNewIo()) {
3936 ALOGE("Invalid Output profile max open count %u for profile %s",
3937 outProfile->maxOpenCount, outProfile->getTagName().c_str());
3938 continue;
3939 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003940 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003941 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003942 continue;
3943 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003944 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003945 mTtsOutputAvailable = true;
3946 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003947
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003948 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003949 continue;
3950 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003951 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003952 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3953 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003954 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003955 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003956 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003957 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003958 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003959 if ((profileType & outputDeviceTypes) == 0) {
3960 continue;
3961 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003962 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3963 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003964 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov708e0382018-05-30 09:53:04 -07003965 const DeviceVector &devicesForType = supportedDevices.getDevicesFromTypeMask(
3966 profileType);
Eric Laurentc40d9692016-04-13 19:14:13 -07003967 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3968 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003969 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08003970 status_t status = outputDesc->open(nullptr, profileType, address,
3971 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07003972
3973 if (status != NO_ERROR) {
3974 ALOGW("Cannot open output stream for device %08x on hw module %s",
3975 outputDesc->mDevice,
Mikhail Naganovd4120142017-12-06 15:49:22 -08003976 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003977 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003978 for (const auto& dev : supportedDevices) {
3979 ssize_t index = mAvailableOutputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07003980 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003981 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003982 mAvailableOutputDevices[index]->attach(hwModule);
Eric Laurentd78f1532014-09-16 16:38:20 -07003983 }
3984 }
3985 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003986 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003987 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003988 }
3989 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003990 setOutputDevice(outputDesc,
Eric Laurentfe231122017-11-17 17:48:06 -08003991 profileType,
Eric Laurentc40d9692016-04-13 19:14:13 -07003992 true,
3993 0,
3994 NULL,
Eric Laurentfe231122017-11-17 17:48:06 -08003995 address);
Eric Laurentd78f1532014-09-16 16:38:20 -07003996 }
Eric Laurente552edb2014-03-10 17:42:56 -07003997 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003998 // open input streams needed to access attached devices to validate
3999 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004000 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004001 if (!inProfile->canOpenNewIo()) {
4002 ALOGE("Invalid Input profile max open count %u for profile %s",
4003 inProfile->maxOpenCount, inProfile->getTagName().c_str());
4004 continue;
4005 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004006 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004007 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004008 continue;
4009 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004010 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07004011 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004012 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
4013
Eric Laurentd78f1532014-09-16 16:38:20 -07004014 if ((profileType & inputDeviceTypes) == 0) {
4015 continue;
4016 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08004017 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08004018 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004019
Mikhail Naganov708e0382018-05-30 09:53:04 -07004020 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(profileType);
Eric Laurent53b810e2017-12-10 17:25:10 -08004021 // the inputs vector must be of size >= 1, but we don't want to crash here
4022 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
4023 : String8("");
4024 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
4025 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
4026
Eric Laurentd78f1532014-09-16 16:38:20 -07004027 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004028 status_t status = inputDesc->open(nullptr,
4029 profileType,
Eric Laurent53b810e2017-12-10 17:25:10 -08004030 address,
Eric Laurentfe231122017-11-17 17:48:06 -08004031 AUDIO_SOURCE_MIC,
4032 AUDIO_INPUT_FLAG_NONE,
4033 &input);
Eric Laurentd78f1532014-09-16 16:38:20 -07004034
4035 if (status == NO_ERROR) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004036 for (const auto& dev : inProfile->getSupportedDevices()) {
4037 ssize_t index = mAvailableInputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07004038 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07004039 if (index >= 0) {
4040 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
4041 if (!devDesc->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004042 devDesc->attach(hwModule);
Eric Laurent83efe1c2017-07-09 16:51:08 -07004043 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07004044 }
Eric Laurentd78f1532014-09-16 16:38:20 -07004045 }
4046 }
Eric Laurentfe231122017-11-17 17:48:06 -08004047 inputDesc->close();
Eric Laurentd78f1532014-09-16 16:38:20 -07004048 } else {
4049 ALOGW("Cannot open input stream for device %08x on hw module %s",
Eric Laurentfe231122017-11-17 17:48:06 -08004050 profileType,
Mikhail Naganovd4120142017-12-06 15:49:22 -08004051 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07004052 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004053 }
4054 }
4055 // make sure all attached devices have been allocated a unique ID
4056 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004057 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004058 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004059 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
4060 continue;
4061 }
François Gaffie2110e042015-03-24 08:41:51 +01004062 // The device is now validated and can be appended to the available devices of the engine
4063 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
4064 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004065 i++;
4066 }
4067 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004068 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01004069 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004070 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
4071 continue;
4072 }
François Gaffie2110e042015-03-24 08:41:51 +01004073 // The device is now validated and can be appended to the available devices of the engine
4074 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
4075 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004076 i++;
4077 }
4078 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004079 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01004080 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004081 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004082 }
jiabin9ff780e2018-03-19 18:19:52 -07004083 // If microphones address is empty, set it according to device type
4084 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
4085 if (mAvailableInputDevices[i]->mAddress.isEmpty()) {
4086 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
4087 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
4088 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
4089 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BACK_MICROPHONE_ADDRESS);
4090 }
4091 }
4092 }
Eric Laurente552edb2014-03-10 17:42:56 -07004093
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004094 if (mPrimaryOutput == 0) {
4095 ALOGE("Failed to open primary output");
4096 status = NO_INIT;
4097 }
Eric Laurente552edb2014-03-10 17:42:56 -07004098
4099 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004100 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004101}
4102
Eric Laurente0720872014-03-11 09:30:41 -07004103AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004104{
Eric Laurente552edb2014-03-10 17:42:56 -07004105 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004106 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004107 }
4108 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004109 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004110 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004111 mAvailableOutputDevices.clear();
4112 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004113 mOutputs.clear();
4114 mInputs.clear();
4115 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004116 mHwModulesAll.clear();
jiabin81772902018-04-02 17:52:27 -07004117 mSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004118}
4119
Eric Laurente0720872014-03-11 09:30:41 -07004120status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004121{
Eric Laurent87ffa392015-05-22 10:32:38 -07004122 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004123}
4124
Eric Laurente552edb2014-03-10 17:42:56 -07004125// ---
4126
Eric Laurent98e38192018-02-15 18:31:53 -08004127void AudioPolicyManager::addOutput(audio_io_handle_t output,
4128 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004129{
Eric Laurent1c333e22014-05-20 10:48:17 -07004130 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08004131 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004132 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004133 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004134 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004135}
4136
François Gaffie53615e22015-03-19 09:24:12 +01004137void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4138{
4139 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004140 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004141}
4142
Eric Laurent98e38192018-02-15 18:31:53 -08004143void AudioPolicyManager::addInput(audio_io_handle_t input,
4144 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004145{
Eric Laurent1c333e22014-05-20 10:48:17 -07004146 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004147 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004148}
Eric Laurente552edb2014-03-10 17:42:56 -07004149
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004150void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08004151 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004152 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004153 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08004154 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004155 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08004156 if (devDesc != 0) {
4157 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
4158 desc->mIoHandle, address.string());
4159 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004160 }
4161}
4162
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004163status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004164 audio_policy_dev_state_t state,
4165 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004166 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07004167{
François Gaffie53615e22015-03-19 09:24:12 +01004168 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07004169 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004170
4171 if (audio_device_is_digital(device)) {
4172 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004173 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004174 }
Eric Laurente552edb2014-03-10 17:42:56 -07004175
Eric Laurent3b73df72014-03-11 09:06:29 -07004176 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004177 // first list already open outputs that can be routed to this device
4178 for (size_t i = 0; i < mOutputs.size(); i++) {
4179 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07004180 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004181 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004182 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
4183 outputs.add(mOutputs.keyAt(i));
4184 } else {
4185 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08004186 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004187 }
Eric Laurente552edb2014-03-10 17:42:56 -07004188 }
4189 }
4190 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004191 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004192 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004193 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4194 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004195 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004196 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004197 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004198 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004199 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4200 j, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004201 }
Eric Laurente552edb2014-03-10 17:42:56 -07004202 }
4203 }
4204 }
4205
Eric Laurent7b279bb2015-12-14 10:18:23 -08004206 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004207
Eric Laurente552edb2014-03-10 17:42:56 -07004208 if (profiles.isEmpty() && outputs.isEmpty()) {
4209 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4210 return BAD_VALUE;
4211 }
4212
4213 // open outputs for matching profiles if needed. Direct outputs are also opened to
4214 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4215 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004216 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004217
4218 // nothing to do if one output is already opened for this profile
4219 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004220 for (j = 0; j < outputs.size(); j++) {
4221 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004222 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004223 // matching profile: save the sample rates, format and channel masks supported
4224 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07004225 if (audio_device_is_digital(device)) {
4226 devDesc->importAudioPort(profile);
4227 }
Eric Laurente552edb2014-03-10 17:42:56 -07004228 break;
4229 }
4230 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004231 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004232 continue;
4233 }
4234
Eric Laurent3974e3b2017-12-07 17:58:43 -08004235 if (!profile->canOpenNewIo()) {
4236 ALOGW("Max Output number %u already opened for this profile %s",
4237 profile->maxOpenCount, profile->getTagName().c_str());
4238 continue;
4239 }
4240
Eric Laurent83efe1c2017-07-09 16:51:08 -07004241 ALOGV("opening output for device %08x with params %s profile %p name %s",
4242 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004243 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004244 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004245 status_t status = desc->open(nullptr, device, address,
4246 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004247
Eric Laurentfe231122017-11-17 17:48:06 -08004248 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004249 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004250 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004251 char *param = audio_device_address_to_parameter(device, address);
4252 mpClientInterface->setParameters(output, String8(param));
4253 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004254 }
Phil Burk00eeb322016-03-31 12:41:00 -07004255 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004256 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004257 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004258 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004259 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004260 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004261 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004262 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004263 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4264 profile->pickAudioProfile(
4265 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004266 config.offload_info.sample_rate = config.sample_rate;
4267 config.offload_info.channel_mask = config.channel_mask;
4268 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004269
4270 status_t status = desc->open(&config, device, address, AUDIO_STREAM_DEFAULT,
4271 AUDIO_OUTPUT_FLAG_NONE, &output);
4272 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004273 output = AUDIO_IO_HANDLE_NONE;
4274 }
Eric Laurentd4692962014-05-05 18:13:44 -07004275 }
4276
Eric Laurentcf2c0212014-07-25 16:20:43 -07004277 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004278 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01004279 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004280 sp<AudioPolicyMix> policyMix;
4281 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004282 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
4283 address.string());
4284 }
François Gaffie036e1e92015-03-19 10:16:24 +01004285 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07004286 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01004287
Eric Laurent87ffa392015-05-22 10:32:38 -07004288 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4289 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004290 // no duplicated output for direct outputs and
4291 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004292 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004293
Eric Laurentd4692962014-05-05 18:13:44 -07004294 //TODO: configure audio effect output stage here
4295
4296 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004297 sp<SwAudioOutputDescriptor> dupOutputDesc =
4298 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4299 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4300 &duplicatedOutput);
4301 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004302 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004303 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004304 } else {
4305 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004306 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004307 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004308 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004309 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004310 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004311 }
Eric Laurente552edb2014-03-10 17:42:56 -07004312 }
4313 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004314 } else {
4315 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004316 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004317 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004318 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004319 profiles.removeAt(profile_index);
4320 profile_index--;
4321 } else {
4322 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004323 // Load digital format info only for digital devices
4324 if (audio_device_is_digital(device)) {
4325 devDesc->importAudioPort(profile);
4326 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004327
François Gaffie53615e22015-03-19 09:24:12 +01004328 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004329 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4330 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004331 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004332 NULL/*patch handle*/, address.string());
4333 }
Eric Laurente552edb2014-03-10 17:42:56 -07004334 ALOGV("checkOutputsForDevice(): adding output %d", output);
4335 }
4336 }
4337
4338 if (profiles.isEmpty()) {
4339 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4340 return BAD_VALUE;
4341 }
Eric Laurentd4692962014-05-05 18:13:44 -07004342 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004343 // check if one opened output is not needed any more after disconnecting one device
4344 for (size_t i = 0; i < mOutputs.size(); i++) {
4345 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004346 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004347 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004348 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004349 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004350 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004351 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004352 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4353 mOutputs.keyAt(i));
4354 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004355 }
Eric Laurente552edb2014-03-10 17:42:56 -07004356 }
4357 }
Eric Laurentd4692962014-05-05 18:13:44 -07004358 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004359 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004360 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4361 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004362 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004363 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004364 "clearing direct output profile %zu on module %s",
4365 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004366 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004367 }
4368 }
4369 }
4370 }
4371 return NO_ERROR;
4372}
4373
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004374status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004375 audio_policy_dev_state_t state,
4376 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004377 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004378{
Paul McLean9080a4c2015-06-18 08:24:02 -07004379 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004380 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004381
4382 if (audio_device_is_digital(device)) {
4383 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004384 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004385 }
4386
Eric Laurentd4692962014-05-05 18:13:44 -07004387 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4388 // first list already open inputs that can be routed to this device
4389 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4390 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004391 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004392 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4393 inputs.add(mInputs.keyAt(input_index));
4394 }
4395 }
4396
4397 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004398 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004399 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004400 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004401 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004402 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004403 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004404
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004405 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004406 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004407 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004408 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004409 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4410 profile_index, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004411 }
Eric Laurentd4692962014-05-05 18:13:44 -07004412 }
4413 }
4414 }
4415
4416 if (profiles.isEmpty() && inputs.isEmpty()) {
4417 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4418 return BAD_VALUE;
4419 }
4420
4421 // open inputs for matching profiles if needed. Direct inputs are also opened to
4422 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4423 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4424
Eric Laurent1c333e22014-05-20 10:48:17 -07004425 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004426
Eric Laurentd4692962014-05-05 18:13:44 -07004427 // nothing to do if one input is already opened for this profile
4428 size_t input_index;
4429 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4430 desc = mInputs.valueAt(input_index);
4431 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004432 if (audio_device_is_digital(device)) {
4433 devDesc->importAudioPort(profile);
4434 }
Eric Laurentd4692962014-05-05 18:13:44 -07004435 break;
4436 }
4437 }
4438 if (input_index != mInputs.size()) {
4439 continue;
4440 }
4441
Eric Laurent3974e3b2017-12-07 17:58:43 -08004442 if (!profile->canOpenNewIo()) {
4443 ALOGW("Max Input number %u already opened for this profile %s",
4444 profile->maxOpenCount, profile->getTagName().c_str());
4445 continue;
4446 }
4447
Eric Laurentfe231122017-11-17 17:48:06 -08004448 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004449 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004450 status_t status = desc->open(nullptr,
4451 device,
4452 address,
4453 AUDIO_SOURCE_MIC,
4454 AUDIO_INPUT_FLAG_NONE,
4455 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004456
Eric Laurentcf2c0212014-07-25 16:20:43 -07004457 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004458 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004459 char *param = audio_device_address_to_parameter(device, address);
4460 mpClientInterface->setParameters(input, String8(param));
4461 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004462 }
Phil Burk00eeb322016-03-31 12:41:00 -07004463 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004464 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004465 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004466 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004467 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004468 }
4469
4470 if (input != 0) {
4471 addInput(input, desc);
4472 }
4473 } // endif input != 0
4474
Eric Laurentcf2c0212014-07-25 16:20:43 -07004475 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004476 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004477 profiles.removeAt(profile_index);
4478 profile_index--;
4479 } else {
4480 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004481 if (audio_device_is_digital(device)) {
4482 devDesc->importAudioPort(profile);
4483 }
Eric Laurentd4692962014-05-05 18:13:44 -07004484 ALOGV("checkInputsForDevice(): adding input %d", input);
4485 }
4486 } // end scan profiles
4487
4488 if (profiles.isEmpty()) {
4489 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4490 return BAD_VALUE;
4491 }
4492 } else {
4493 // Disconnect
4494 // check if one opened input is not needed any more after disconnecting one device
4495 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4496 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004497 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004498 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4499 mInputs.keyAt(input_index));
4500 inputs.add(mInputs.keyAt(input_index));
4501 }
4502 }
4503 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004504 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004505 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004506 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004507 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004508 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004509 if (profile->supportDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004510 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4511 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004512 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004513 }
4514 }
4515 }
4516 } // end disconnect
4517
4518 return NO_ERROR;
4519}
4520
4521
Eric Laurente0720872014-03-11 09:30:41 -07004522void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004523{
4524 ALOGV("closeOutput(%d)", output);
4525
Eric Laurentc75307b2015-03-17 15:29:32 -07004526 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004527 if (outputDesc == NULL) {
4528 ALOGW("closeOutput() unknown output %d", output);
4529 return;
4530 }
François Gaffie036e1e92015-03-19 10:16:24 +01004531 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004532
Eric Laurente552edb2014-03-10 17:42:56 -07004533 // look for duplicated outputs connected to the output being removed.
4534 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004535 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004536 if (dupOutputDesc->isDuplicated() &&
4537 (dupOutputDesc->mOutput1 == outputDesc ||
4538 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004539 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004540 if (dupOutputDesc->mOutput1 == outputDesc) {
4541 outputDesc2 = dupOutputDesc->mOutput2;
4542 } else {
4543 outputDesc2 = dupOutputDesc->mOutput1;
4544 }
4545 // As all active tracks on duplicated output will be deleted,
4546 // and as they were also referenced on the other output, the reference
4547 // count for their stream type must be adjusted accordingly on
4548 // the other output.
Eric Laurent733ce942017-12-07 12:18:25 -08004549 bool wasActive = outputDesc2->isActive();
Eric Laurent3b73df72014-03-11 09:06:29 -07004550 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurent592dd7b2018-08-05 18:58:48 -07004551 int activeCount = dupOutputDesc->streamActiveCount((audio_stream_type_t)j);
4552 outputDesc2->changeStreamActiveCount((audio_stream_type_t)j,-activeCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004553 }
Eric Laurent733ce942017-12-07 12:18:25 -08004554 // stop() will be a no op if the output is still active but is needed in case all
4555 // active streams refcounts where cleared above
4556 if (wasActive) {
4557 outputDesc2->stop();
4558 }
Eric Laurente552edb2014-03-10 17:42:56 -07004559 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4560 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4561
4562 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004563 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004564 }
4565 }
4566
Eric Laurent05b90f82014-08-27 15:32:29 -07004567 nextAudioPortGeneration();
4568
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004569 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004570 if (index >= 0) {
4571 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004572 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004573 mAudioPatches.removeItemsAt(index);
4574 mpClientInterface->onAudioPatchListUpdate();
4575 }
4576
Eric Laurentfe231122017-11-17 17:48:06 -08004577 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004578
François Gaffie53615e22015-03-19 09:24:12 +01004579 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004580 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10004581
4582 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
4583 // no direct outputs are open.
4584 if (getMsdAudioOutDeviceTypes() != AUDIO_DEVICE_NONE) {
4585 bool directOutputOpen = false;
4586 for (size_t i = 0; i < mOutputs.size(); i++) {
4587 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
4588 directOutputOpen = true;
4589 break;
4590 }
4591 }
4592 if (!directOutputOpen) {
4593 ALOGV("no direct outputs open, reset MSD patch");
4594 setMsdPatch();
4595 }
4596 }
Eric Laurent05b90f82014-08-27 15:32:29 -07004597}
4598
4599void AudioPolicyManager::closeInput(audio_io_handle_t input)
4600{
4601 ALOGV("closeInput(%d)", input);
4602
4603 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4604 if (inputDesc == NULL) {
4605 ALOGW("closeInput() unknown input %d", input);
4606 return;
4607 }
4608
Eric Laurent6a94d692014-05-20 11:18:06 -07004609 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004610
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004611 audio_devices_t device = inputDesc->mDevice;
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004612 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004613 if (index >= 0) {
4614 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004615 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004616 mAudioPatches.removeItemsAt(index);
4617 mpClientInterface->onAudioPatchListUpdate();
4618 }
4619
Eric Laurentfe231122017-11-17 17:48:06 -08004620 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004621 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004622
4623 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
4624 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
4625 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
4626 SoundTrigger::setCaptureState(false);
4627 }
Eric Laurente552edb2014-03-10 17:42:56 -07004628}
4629
Eric Laurentc75307b2015-03-17 15:29:32 -07004630SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4631 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004632 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004633{
4634 SortedVector<audio_io_handle_t> outputs;
4635
4636 ALOGVV("getOutputsForDevice() device %04x", device);
4637 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004638 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004639 i, openOutputs.valueAt(i)->isDuplicated(),
4640 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004641 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4642 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4643 outputs.add(openOutputs.keyAt(i));
4644 }
4645 }
4646 return outputs;
4647}
4648
Mikhail Naganov37977152018-07-11 15:54:44 -07004649void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
4650{
4651 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
4652 // output is suspended before any tracks are moved to it
4653 checkA2dpSuspend();
4654 checkOutputForAllStrategies();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004655 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07004656 updateDevicesAndOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004657 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
4658 setMsdPatch();
4659 }
Mikhail Naganov37977152018-07-11 15:54:44 -07004660}
4661
Eric Laurente0720872014-03-11 09:30:41 -07004662void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004663{
4664 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4665 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4666 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4667 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4668
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004669 // also take into account external policy-related changes: add all outputs which are
4670 // associated with policies in the "before" and "after" output vectors
4671 ALOGVV("checkOutputForStrategy(): policy related outputs");
4672 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004673 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004674 if (desc != 0 && desc->mPolicyMix != NULL) {
4675 srcOutputs.add(desc->mIoHandle);
4676 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4677 }
4678 }
4679 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004680 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004681 if (desc != 0 && desc->mPolicyMix != NULL) {
4682 dstOutputs.add(desc->mIoHandle);
4683 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4684 }
4685 }
4686
Mikhail Naganov9de8bd12018-07-23 16:41:31 -07004687 if (srcOutputs != dstOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004688 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4689 // audio from invalidated tracks will be rendered when unmuting
4690 uint32_t maxLatency = 0;
4691 for (audio_io_handle_t srcOut : srcOutputs) {
4692 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4693 if (desc != 0 && maxLatency < desc->latency()) {
4694 maxLatency = desc->latency();
4695 }
4696 }
Eric Laurente552edb2014-03-10 17:42:56 -07004697 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4698 strategy, srcOutputs[0], dstOutputs[0]);
4699 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004700 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004701 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4702 if (desc != 0 && isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004703 setStrategyMute(strategy, true, desc);
Eric Laurentac3a6902018-05-11 16:39:10 -07004704 setStrategyMute(strategy, false, desc, maxLatency * LATENCY_MUTE_FACTOR, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004705 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004706 sp<SourceClientDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004707 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004708 if (source != 0){
4709 connectAudioSource(source);
4710 }
Eric Laurente552edb2014-03-10 17:42:56 -07004711 }
4712
4713 // Move effects associated to this strategy from previous output to new output
4714 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004715 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004716 }
4717 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004718 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004719 if (getStrategy((audio_stream_type_t)i) == strategy) {
4720 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004721 }
4722 }
4723 }
4724}
4725
Eric Laurente0720872014-03-11 09:30:41 -07004726void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004727{
François Gaffie2110e042015-03-24 08:41:51 +01004728 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004729 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004730 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004731 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004732 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004733 checkOutputForStrategy(STRATEGY_SONIFICATION);
4734 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004735 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004736 checkOutputForStrategy(STRATEGY_MEDIA);
4737 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004738 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004739}
4740
Eric Laurente0720872014-03-11 09:30:41 -07004741void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004742{
François Gaffie53615e22015-03-19 09:24:12 +01004743 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004744 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004745 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004746 return;
4747 }
4748
Eric Laurent3a4311c2014-03-17 12:00:47 -07004749 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004750 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4751 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4752 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004753
4754 // if suspended, restore A2DP output if:
4755 // ((SCO device is NOT connected) ||
4756 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4757 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004758 //
Eric Laurentf732e072016-08-03 19:30:28 -07004759 // if not suspended, suspend A2DP output if:
4760 // (SCO device is connected) &&
4761 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4762 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004763 //
4764 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004765 if (!isScoConnected ||
4766 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4767 AUDIO_POLICY_FORCE_BT_SCO) &&
4768 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4769 AUDIO_POLICY_FORCE_BT_SCO) &&
4770 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004771 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004772
4773 mpClientInterface->restoreOutput(a2dpOutput);
4774 mA2dpSuspended = false;
4775 }
4776 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004777 if (isScoConnected &&
4778 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4779 AUDIO_POLICY_FORCE_BT_SCO) ||
4780 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4781 AUDIO_POLICY_FORCE_BT_SCO) ||
4782 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004783 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004784
4785 mpClientInterface->suspendOutput(a2dpOutput);
4786 mA2dpSuspended = true;
4787 }
4788 }
4789}
4790
Eric Laurent97ac8712018-07-27 18:59:02 -07004791template <class IoDescriptor, class Filter>
4792sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4793 IoDescriptor& desc, Filter filter, bool& active, const DeviceVector& devices)
4794{
4795 auto activeClients = desc->clientsList(true /*activeOnly*/);
4796 auto activeClientsWithRoute =
4797 desc->clientsList(true /*activeOnly*/, filter, true /*preferredDevice*/);
4798 active = activeClients.size() > 0;
4799 if (active && activeClients.size() == activeClientsWithRoute.size()) {
4800 return devices.getDeviceFromId(activeClientsWithRoute[0]->preferredDeviceId());
4801 }
4802 return nullptr;
4803}
4804
4805template <class IoCollection, class Filter>
4806sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4807 IoCollection& ioCollection, Filter filter, const DeviceVector& devices)
4808{
4809 sp<DeviceDescriptor> device;
4810 for (size_t i = 0; i < ioCollection.size(); i++) {
4811 auto desc = ioCollection.valueAt(i);
4812 bool active;
4813 sp<DeviceDescriptor> curDevice = findPreferredDevice(desc, filter, active, devices);
4814 if (active && curDevice == nullptr) {
4815 return nullptr;
4816 } else if (curDevice != nullptr) {
4817 device = curDevice;
4818 }
4819 }
4820 return device;
4821}
4822
Eric Laurentc75307b2015-03-17 15:29:32 -07004823audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4824 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004825{
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004826 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004827 if (index >= 0) {
4828 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4829 if (patchDesc->mUid != mUidCached) {
4830 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004831 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004832 return outputDesc->device();
4833 }
4834 }
4835
Eric Laurent97ac8712018-07-27 18:59:02 -07004836 // Honor explicit routing requests only if no client using default routing is active on this
4837 // input: a specific app can not force routing for other apps by setting a preferred device.
4838 bool active; // unused
4839 sp<DeviceDescriptor> deviceDesc =
4840 findPreferredDevice(outputDesc, STRATEGY_NONE, active, mAvailableOutputDevices);
4841 if (deviceDesc != nullptr) {
4842 return deviceDesc->type();
Eric Laurentf3a5a602018-05-22 18:42:55 -07004843 }
4844
Eric Laurente552edb2014-03-10 17:42:56 -07004845 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004846 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004847 // use device for strategy enforced audible
4848 // 2: we are in call or the strategy phone is active on the output:
4849 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004850 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004851 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004852 // 4: the strategy for enforced audible is active but not enforced on the output:
4853 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004854 // 5: the strategy accessibility is active on the output:
4855 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004856 // 6: the strategy "respectful" sonification is active on the output:
4857 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004858 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004859 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004860 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004861 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004862 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004863 // use device for strategy t-t-s
Eric Laurent484e9272018-06-07 17:29:23 -07004864
4865 // FIXME: extend use of isStrategyActiveOnSameModule() to all strategies
4866 // with a refined rule considering mutually exclusive devices (using same backend)
4867 // as opposed to all streams on the same audio HAL module.
Eric Laurent97ac8712018-07-27 18:59:02 -07004868 audio_devices_t device = AUDIO_DEVICE_NONE;
François Gaffiead3183e2015-03-18 16:55:35 +01004869 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004870 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004871 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4872 } else if (isInCall() ||
Eric Laurent484e9272018-06-07 17:29:23 -07004873 isStrategyActiveOnSameModule(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004874 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
Yung Ti Su3e7eb5e2018-06-13 11:48:42 +08004875 } else if (isStrategyActiveOnSameModule(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004876 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004877 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
4878 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004879 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4880 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004881 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004882 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004883 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004884 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004885 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004886 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004887 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004888 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004889 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004890 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004891 }
4892
Eric Laurent1c333e22014-05-20 10:48:17 -07004893 ALOGV("getNewOutputDevice() selected device %x", device);
4894 return device;
4895}
4896
Eric Laurentfb66dd92016-01-28 18:32:03 -08004897audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004898{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004899 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004900
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004901 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004902 if (index >= 0) {
4903 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4904 if (patchDesc->mUid != mUidCached) {
4905 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004906 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004907 return inputDesc->mDevice;
4908 }
4909 }
4910
Eric Laurent97ac8712018-07-27 18:59:02 -07004911 // Honor explicit routing requests only if no client using default routing is active on this
4912 // input: a specific app can not force routing for other apps by setting a preferred device.
4913 bool active;
4914 sp<DeviceDescriptor> deviceDesc =
4915 findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
4916 if (deviceDesc != nullptr) {
4917 return deviceDesc->type();
4918 }
4919
Eric Laurentdc95a252018-04-12 12:46:56 -07004920 // If we are not in call and no client is active on this input, this methods returns
4921 // AUDIO_DEVICE_NONE, causing the patch on the input stream to be released.
Eric Laurentfb66dd92016-01-28 18:32:03 -08004922 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
Eric Laurentdc95a252018-04-12 12:46:56 -07004923 if (source == AUDIO_SOURCE_DEFAULT && isInCall()) {
4924 source = AUDIO_SOURCE_VOICE_COMMUNICATION;
4925 }
4926 if (source != AUDIO_SOURCE_DEFAULT) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08004927 device = getDeviceAndMixForInputSource(source);
4928 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004929
Eric Laurente552edb2014-03-10 17:42:56 -07004930 return device;
4931}
4932
Eric Laurent794fde22016-03-11 09:50:45 -08004933bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4934 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004935 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004936}
4937
Eric Laurente0720872014-03-11 09:30:41 -07004938uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004939 return (uint32_t)getStrategy(stream);
4940}
4941
Eric Laurente0720872014-03-11 09:30:41 -07004942audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004943 // By checking the range of stream before calling getStrategy, we avoid
4944 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4945 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004946 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004947 return AUDIO_DEVICE_NONE;
4948 }
Eric Laurentb0688d62018-08-14 15:49:18 -07004949 audio_devices_t activeDevices = AUDIO_DEVICE_NONE;
Eric Laurent28d09f02016-03-08 10:43:05 -08004950 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004951 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4952 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004953 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004954 }
Eric Laurent794fde22016-03-11 09:50:45 -08004955 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004956 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004957 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Eric Laurentb0688d62018-08-14 15:49:18 -07004958 devices |= curDevices;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004959 for (audio_io_handle_t output : getOutputsForDevice(curDevices, mOutputs)) {
4960 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08004961 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurentb0688d62018-08-14 15:49:18 -07004962 activeDevices |= outputDesc->device();
Eric Laurent28d09f02016-03-08 10:43:05 -08004963 }
4964 }
Eric Laurente552edb2014-03-10 17:42:56 -07004965 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004966
Eric Laurentb0688d62018-08-14 15:49:18 -07004967 // Favor devices selected on active streams if any to report correct device in case of
4968 // explicit device selection
4969 if (activeDevices != AUDIO_DEVICE_NONE) {
4970 devices = activeDevices;
4971 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004972 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4973 and doesn't really need to.*/
4974 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4975 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4976 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4977 }
Eric Laurente552edb2014-03-10 17:42:56 -07004978 return devices;
4979}
4980
François Gaffie2110e042015-03-24 08:41:51 +01004981routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4982{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004983 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004984 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004985}
4986
Eric Laurent97ac8712018-07-27 18:59:02 -07004987routing_strategy AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004988 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004989 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004990 return STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004991 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004992 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004993 return STRATEGY_ENFORCED_AUDIBLE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004994 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004995 // usage to strategy mapping
Eric Laurent97ac8712018-07-27 18:59:02 -07004996 return mEngine->getStrategyForUsage(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004997}
4998
Eric Laurente0720872014-03-11 09:30:41 -07004999void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005000 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005001 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07005002 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
5003 updateDevicesAndOutputs();
5004 break;
5005 default:
5006 break;
5007 }
5008}
5009
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005010uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07005011
5012 // skip beacon mute management if a dedicated TTS output is available
5013 if (mTtsOutputAvailable) {
5014 return 0;
5015 }
5016
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005017 switch(event) {
5018 case STARTING_OUTPUT:
5019 mBeaconMuteRefCount++;
5020 break;
5021 case STOPPING_OUTPUT:
5022 if (mBeaconMuteRefCount > 0) {
5023 mBeaconMuteRefCount--;
5024 }
5025 break;
5026 case STARTING_BEACON:
5027 mBeaconPlayingRefCount++;
5028 break;
5029 case STOPPING_BEACON:
5030 if (mBeaconPlayingRefCount > 0) {
5031 mBeaconPlayingRefCount--;
5032 }
5033 break;
5034 }
5035
5036 if (mBeaconMuteRefCount > 0) {
5037 // any playback causes beacon to be muted
5038 return setBeaconMute(true);
5039 } else {
5040 // no other playback: unmute when beacon starts playing, mute when it stops
5041 return setBeaconMute(mBeaconPlayingRefCount == 0);
5042 }
5043}
5044
5045uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5046 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5047 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5048 // keep track of muted state to avoid repeating mute/unmute operations
5049 if (mBeaconMuted != mute) {
5050 // mute/unmute AUDIO_STREAM_TTS on all outputs
5051 ALOGV("\t muting %d", mute);
5052 uint32_t maxLatency = 0;
5053 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005054 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005055 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07005056 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005057 0 /*delay*/, AUDIO_DEVICE_NONE);
5058 const uint32_t latency = desc->latency() * 2;
5059 if (latency > maxLatency) {
5060 maxLatency = latency;
5061 }
5062 }
5063 mBeaconMuted = mute;
5064 return maxLatency;
5065 }
5066 return 0;
5067}
5068
Eric Laurente0720872014-03-11 09:30:41 -07005069audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01005070 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005071{
Eric Laurent97ac8712018-07-27 18:59:02 -07005072 // Honor explicit routing requests only if all active clients have a preferred route in which
5073 // case the last active client route is used
5074 sp<DeviceDescriptor> deviceDesc = findPreferredDevice(mOutputs, strategy, mAvailableOutputDevices);
5075 if (deviceDesc != nullptr) {
5076 return deviceDesc->type();
Paul McLeanaa981192015-03-21 09:55:15 -07005077 }
5078
Eric Laurente552edb2014-03-10 17:42:56 -07005079 if (fromCache) {
5080 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
5081 strategy, mDeviceForStrategy[strategy]);
5082 return mDeviceForStrategy[strategy];
5083 }
François Gaffie2110e042015-03-24 08:41:51 +01005084 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07005085}
5086
Eric Laurente0720872014-03-11 09:30:41 -07005087void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005088{
5089 for (int i = 0; i < NUM_STRATEGIES; i++) {
5090 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
5091 }
5092 mPreviousOutputs = mOutputs;
5093}
5094
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005095uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005096 audio_devices_t prevDevice,
5097 uint32_t delayMs)
5098{
5099 // mute/unmute strategies using an incompatible device combination
5100 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5101 // if unmuting, unmute only after the specified delay
5102 if (outputDesc->isDuplicated()) {
5103 return 0;
5104 }
5105
5106 uint32_t muteWaitMs = 0;
5107 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07005108 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005109
5110 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
5111 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07005112 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07005113 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
5114 bool doMute = false;
5115
5116 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
5117 doMute = true;
5118 outputDesc->mStrategyMutedByDevice[i] = true;
5119 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
5120 doMute = true;
5121 outputDesc->mStrategyMutedByDevice[i] = false;
5122 }
Eric Laurent99401132014-05-07 19:48:15 -07005123 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005124 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005125 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005126 // skip output if it does not share any device with current output
5127 if ((desc->supportedDevices() & outputDesc->supportedDevices())
5128 == AUDIO_DEVICE_NONE) {
5129 continue;
5130 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005131 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07005132 mute ? "muting" : "unmuting", i, curDevice);
5133 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005134 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005135 if (mute) {
5136 // FIXME: should not need to double latency if volume could be applied
5137 // immediately by the audioflinger mixer. We must account for the delay
5138 // between now and the next time the audioflinger thread for this output
5139 // will process a buffer (which corresponds to one buffer size,
5140 // usually 1/2 or 1/4 of the latency).
5141 if (muteWaitMs < desc->latency() * 2) {
5142 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005143 }
5144 }
5145 }
5146 }
5147 }
5148 }
5149
Eric Laurent99401132014-05-07 19:48:15 -07005150 // temporary mute output if device selection changes to avoid volume bursts due to
5151 // different per device volumes
5152 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005153 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5154 // temporary mute duration is conservatively set to 4 times the reported latency
5155 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5156 if (muteWaitMs < tempMuteWaitMs) {
5157 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005158 }
Eric Laurentdc462862016-07-19 12:29:53 -07005159
Eric Laurent99401132014-05-07 19:48:15 -07005160 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005161 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005162 // make sure that we do not start the temporary mute period too early in case of
5163 // delayed device change
5164 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005165 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07005166 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07005167 }
5168 }
5169 }
5170
Eric Laurente552edb2014-03-10 17:42:56 -07005171 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5172 if (muteWaitMs > delayMs) {
5173 muteWaitMs -= delayMs;
5174 usleep(muteWaitMs * 1000);
5175 return muteWaitMs;
5176 }
5177 return 0;
5178}
5179
Eric Laurentc75307b2015-03-17 15:29:32 -07005180uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005181 audio_devices_t device,
5182 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07005183 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005184 audio_patch_handle_t *patchHandle,
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005185 const char *address,
5186 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005187{
Eric Laurentc75307b2015-03-17 15:29:32 -07005188 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005189 AudioParameter param;
5190 uint32_t muteWaitMs;
5191
5192 if (outputDesc->isDuplicated()) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005193 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs,
5194 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
5195 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs,
5196 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005197 return muteWaitMs;
5198 }
5199 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5200 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07005201 if ((device != AUDIO_DEVICE_NONE) &&
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005202 ((device & outputDesc->supportedDevices()) == AUDIO_DEVICE_NONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005203 return 0;
5204 }
5205
5206 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07005207 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07005208
5209 audio_devices_t prevDevice = outputDesc->mDevice;
5210
Paul McLeanaa981192015-03-21 09:55:15 -07005211 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005212
5213 if (device != AUDIO_DEVICE_NONE) {
5214 outputDesc->mDevice = device;
5215 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005216
5217 // if the outputs are not materially active, there is no need to mute.
5218 if (requiresMuteCheck) {
5219 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
5220 } else {
5221 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5222 muteWaitMs = 0;
5223 }
Eric Laurente552edb2014-03-10 17:42:56 -07005224
5225 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005226 // the requested device is AUDIO_DEVICE_NONE
5227 // OR the requested device is the same as current device
5228 // AND force is not specified
5229 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07005230 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07005231 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
5232 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005233 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005234 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005235 return muteWaitMs;
5236 }
5237
5238 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07005239
Eric Laurente552edb2014-03-10 17:42:56 -07005240 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07005241 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005242 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005243 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07005244 DeviceVector deviceList;
5245 if ((address == NULL) || (strlen(address) == 0)) {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005246 deviceList = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurentc40d9692016-04-13 19:14:13 -07005247 } else {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005248 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
5249 device, String8(address));
5250 if (deviceDesc) deviceList.add(deviceDesc);
Eric Laurentc40d9692016-04-13 19:14:13 -07005251 }
5252
Eric Laurent1c333e22014-05-20 10:48:17 -07005253 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005254 PatchBuilder patchBuilder;
5255 patchBuilder.addSource(outputDesc);
Eric Laurent1c333e22014-05-20 10:48:17 -07005256 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005257 patchBuilder.addSink(deviceList.itemAt(i));
Eric Laurent1c333e22014-05-20 10:48:17 -07005258 }
Mikhail Naganovdc769682018-05-04 15:34:08 -07005259 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005260 }
bryant_liuf5e7e792014-08-19 20:07:05 +08005261
5262 // inform all input as well
5263 for (size_t i = 0; i < mInputs.size(); i++) {
5264 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01005265 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08005266 AudioParameter inputCmd = AudioParameter();
5267 ALOGV("%s: inform input %d of device:%d", __func__,
5268 inputDescriptor->mIoHandle, device);
5269 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
5270 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
5271 inputCmd.toString(),
5272 delayMs);
5273 }
5274 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005275 }
Eric Laurente552edb2014-03-10 17:42:56 -07005276
5277 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07005278 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005279
5280 return muteWaitMs;
5281}
5282
Eric Laurentc75307b2015-03-17 15:29:32 -07005283status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005284 int delayMs,
5285 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005286{
Eric Laurent6a94d692014-05-20 11:18:06 -07005287 ssize_t index;
5288 if (patchHandle) {
5289 index = mAudioPatches.indexOfKey(*patchHandle);
5290 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005291 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005292 }
5293 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005294 return INVALID_OPERATION;
5295 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005296 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5297 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005298 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005299 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005300 removeAudioPatch(patchDesc->mHandle);
5301 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005302 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005303 return status;
5304}
5305
5306status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5307 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005308 bool force,
5309 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005310{
5311 status_t status = NO_ERROR;
5312
Eric Laurent1f2f2232014-06-02 12:01:23 -07005313 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005314 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5315 inputDesc->mDevice = device;
5316
Mikhail Naganov708e0382018-05-30 09:53:04 -07005317 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005318 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005319 PatchBuilder patchBuilder;
5320 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005321 // AUDIO_SOURCE_HOTWORD is for internal use only:
5322 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07005323 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5324 auto result = usecase;
5325 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5326 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5327 }
5328 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07005329 //only one input device for now
Mikhail Naganovdc769682018-05-04 15:34:08 -07005330 addSource(deviceList.itemAt(0));
5331 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005332 }
5333 }
5334 return status;
5335}
5336
Eric Laurent6a94d692014-05-20 11:18:06 -07005337status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5338 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005339{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005340 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005341 ssize_t index;
5342 if (patchHandle) {
5343 index = mAudioPatches.indexOfKey(*patchHandle);
5344 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005345 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005346 }
5347 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005348 return INVALID_OPERATION;
5349 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005350 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5351 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005352 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005353 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005354 removeAudioPatch(patchDesc->mHandle);
5355 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005356 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005357 return status;
5358}
5359
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005360sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005361 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005362 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005363 audio_format_t& format,
5364 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005365 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005366{
5367 // Choose an input profile based on the requested capture parameters: select the first available
5368 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005369 //
5370 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5371 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005372
Glenn Kasten730b9262018-03-29 15:01:26 -07005373 sp<IOProfile> firstInexact;
5374 uint32_t updatedSamplingRate = 0;
5375 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5376 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005377 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005378 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005379 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005380 //updatedFormat = format;
Eric Laurent275e8e92014-11-30 15:14:47 -08005381 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005382 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005383 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005384 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005385 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005386 &channelMask /*updatedChannelMask*/,
5387 // FIXME ugly cast
5388 (audio_output_flags_t) flags,
5389 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005390 return profile;
5391 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005392 if (firstInexact == nullptr && profile->isCompatibleProfile(device, address,
5393 samplingRate,
5394 &updatedSamplingRate,
5395 format,
5396 &updatedFormat,
5397 channelMask,
5398 &updatedChannelMask,
5399 // FIXME ugly cast
5400 (audio_output_flags_t) flags,
5401 false /*exactMatchRequiredForInputFlags*/)) {
5402 firstInexact = profile;
5403 }
5404
Eric Laurente552edb2014-03-10 17:42:56 -07005405 }
5406 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005407 if (firstInexact != nullptr) {
5408 samplingRate = updatedSamplingRate;
5409 format = updatedFormat;
5410 channelMask = updatedChannelMask;
5411 return firstInexact;
5412 }
Eric Laurente552edb2014-03-10 17:42:56 -07005413 return NULL;
5414}
5415
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005416
5417audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005418 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005419{
Eric Laurent97ac8712018-07-27 18:59:02 -07005420 // Honor explicit routing requests only if all active clients have a preferred route in which
5421 // case the last active client route is used
5422 sp<DeviceDescriptor> deviceDesc =
5423 findPreferredDevice(mInputs, inputSource, mAvailableInputDevices);
5424 if (deviceDesc != nullptr) {
5425 return deviceDesc->type();
5426 }
5427
5428
François Gaffie036e1e92015-03-19 10:16:24 +01005429 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5430 audio_devices_t selectedDeviceFromMix =
5431 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005432
François Gaffie036e1e92015-03-19 10:16:24 +01005433 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5434 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005435 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005436 return getDeviceForInputSource(inputSource);
5437}
5438
5439audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5440{
Eric Laurent97ac8712018-07-27 18:59:02 -07005441 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005442}
5443
Eric Laurente0720872014-03-11 09:30:41 -07005444float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005445 int index,
5446 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005447{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005448 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005449
5450 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5451 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5452 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5453 // the ringtone volume
5454 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5455 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5456 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5457 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5458 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5459 }
5460
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005461 // in-call: always cap volume by voice volume + some low headroom
5462 if ((stream != AUDIO_STREAM_VOICE_CALL) &&
Eric Laurent7731b5a2018-04-06 15:47:22 -07005463 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005464 switch (stream) {
5465 case AUDIO_STREAM_SYSTEM:
5466 case AUDIO_STREAM_RING:
5467 case AUDIO_STREAM_MUSIC:
5468 case AUDIO_STREAM_ALARM:
5469 case AUDIO_STREAM_NOTIFICATION:
5470 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5471 case AUDIO_STREAM_DTMF:
5472 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005473 int voiceVolumeIndex =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005474 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, device);
Eric Laurent7731b5a2018-04-06 15:47:22 -07005475 const float maxVoiceVolDb =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005476 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, device)
Eric Laurent7731b5a2018-04-06 15:47:22 -07005477 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005478 if (volumeDB > maxVoiceVolDb) {
5479 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5480 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5481 volumeDB = maxVoiceVolDb;
5482 }
5483 } break;
5484 default:
5485 break;
5486 }
5487 }
5488
Eric Laurente552edb2014-03-10 17:42:56 -07005489 // if a headset is connected, apply the following rules to ring tones and notifications
5490 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005491 // - always attenuate notifications volume by 6dB
5492 // - attenuate ring tones volume by 6dB unless music is not playing and
5493 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005494 // - if music is playing, always limit the volume to current music volume,
5495 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005496 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005497 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5498 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5499 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005500 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005501 AUDIO_DEVICE_OUT_USB_HEADSET |
5502 AUDIO_DEVICE_OUT_HEARING_AID)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005503 ((stream_strategy == STRATEGY_SONIFICATION)
5504 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005505 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005506 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005507 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005508 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005509 // when the phone is ringing we must consider that music could have been paused just before
5510 // by the music application and behave as if music was active if the last music track was
5511 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005512 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005513 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005514 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005515 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005516 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005517 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5518 musicDevice),
5519 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005520 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5521 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005522 if (volumeDB > minVolDB) {
5523 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005524 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005525 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005526 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5527 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5528 // on A2DP, also ensure notification volume is not too low compared to media when
5529 // intended to be played
5530 if ((volumeDB > -96.0f) &&
5531 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5532 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5533 stream, device,
5534 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5535 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5536 }
5537 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005538 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5539 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005540 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005541 }
5542 }
5543
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005544 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005545}
5546
Eric Laurent3839bc02018-07-10 18:33:34 -07005547int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
5548 audio_stream_type_t srcStream,
5549 audio_stream_type_t dstStream)
5550{
5551 if (srcStream == dstStream) {
5552 return srcIndex;
5553 }
5554 float minSrc = (float)mVolumeCurves->getVolumeIndexMin(srcStream);
5555 float maxSrc = (float)mVolumeCurves->getVolumeIndexMax(srcStream);
5556 float minDst = (float)mVolumeCurves->getVolumeIndexMin(dstStream);
5557 float maxDst = (float)mVolumeCurves->getVolumeIndexMax(dstStream);
5558
5559 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
5560}
5561
Eric Laurente0720872014-03-11 09:30:41 -07005562status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005563 int index,
5564 const sp<AudioOutputDescriptor>& outputDesc,
5565 audio_devices_t device,
5566 int delayMs,
5567 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005568{
Eric Laurente552edb2014-03-10 17:42:56 -07005569 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005570 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005571 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005572 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005573 return NO_ERROR;
5574 }
François Gaffie2110e042015-03-24 08:41:51 +01005575 audio_policy_forced_cfg_t forceUseForComm =
5576 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005577 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005578 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5579 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005580 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005581 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005582 return INVALID_OPERATION;
5583 }
5584
Eric Laurentc75307b2015-03-17 15:29:32 -07005585 if (device == AUDIO_DEVICE_NONE) {
5586 device = outputDesc->device();
5587 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005588
Eric Laurentffbc80f2015-03-18 18:30:19 -07005589 float volumeDb = computeVolume(stream, index, device);
HW Leeda7581e2018-05-22 18:31:34 +08005590 if (outputDesc->isFixedVolume(device) ||
5591 // Force VoIP volume to max for bluetooth SCO
5592 ((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
5593 (device & AUDIO_DEVICE_OUT_ALL_SCO) != 0)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005594 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005595 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005596
Eric Laurentffbc80f2015-03-18 18:30:19 -07005597 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005598
Eric Laurent3b73df72014-03-11 09:06:29 -07005599 if (stream == AUDIO_STREAM_VOICE_CALL ||
5600 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005601 float voiceVolume;
5602 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005603 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurent3839bc02018-07-10 18:33:34 -07005604 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005605 } else {
5606 voiceVolume = 1.0;
5607 }
5608
Eric Laurent18fba842016-03-31 14:41:26 -07005609 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005610 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5611 mLastVoiceVolume = voiceVolume;
5612 }
5613 }
5614
5615 return NO_ERROR;
5616}
5617
Eric Laurentc75307b2015-03-17 15:29:32 -07005618void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5619 audio_devices_t device,
5620 int delayMs,
5621 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005622{
Eric Laurentc75307b2015-03-17 15:29:32 -07005623 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005624
Eric Laurent794fde22016-03-11 09:50:45 -08005625 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005626 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005627 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005628 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005629 device,
5630 delayMs,
5631 force);
5632 }
5633}
5634
Eric Laurente0720872014-03-11 09:30:41 -07005635void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005636 bool on,
5637 const sp<AudioOutputDescriptor>& outputDesc,
5638 int delayMs,
5639 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005640{
Eric Laurent72249d52015-06-08 11:12:15 -07005641 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5642 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005643 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005644 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005645 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005646 }
5647 }
5648}
5649
Eric Laurente0720872014-03-11 09:30:41 -07005650void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005651 bool on,
5652 const sp<AudioOutputDescriptor>& outputDesc,
5653 int delayMs,
5654 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005655{
Eric Laurente552edb2014-03-10 17:42:56 -07005656 if (device == AUDIO_DEVICE_NONE) {
5657 device = outputDesc->device();
5658 }
5659
Eric Laurentc75307b2015-03-17 15:29:32 -07005660 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5661 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005662
5663 if (on) {
5664 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005665 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005666 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005667 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005668 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005669 }
5670 }
5671 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5672 outputDesc->mMuteCount[stream]++;
5673 } else {
5674 if (outputDesc->mMuteCount[stream] == 0) {
5675 ALOGV("setStreamMute() unmuting non muted stream!");
5676 return;
5677 }
5678 if (--outputDesc->mMuteCount[stream] == 0) {
5679 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005680 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005681 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005682 device,
5683 delayMs);
5684 }
5685 }
5686}
5687
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005688audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5689{
5690 // flags to stream type mapping
5691 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5692 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5693 }
5694 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5695 return AUDIO_STREAM_BLUETOOTH_SCO;
5696 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005697 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5698 return AUDIO_STREAM_TTS;
5699 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005700
Ari Hausman-Cohen5c00d012018-06-26 17:09:11 -07005701 return audio_usage_to_stream_type(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005702}
Eric Laurente83b55d2014-11-14 10:06:21 -08005703
François Gaffie53615e22015-03-19 09:24:12 +01005704bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5705{
Eric Laurente83b55d2014-11-14 10:06:21 -08005706 // has flags that map to a strategy?
5707 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5708 return true;
5709 }
5710
5711 // has known usage?
5712 switch (paa->usage) {
5713 case AUDIO_USAGE_UNKNOWN:
5714 case AUDIO_USAGE_MEDIA:
5715 case AUDIO_USAGE_VOICE_COMMUNICATION:
5716 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5717 case AUDIO_USAGE_ALARM:
5718 case AUDIO_USAGE_NOTIFICATION:
5719 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5720 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5721 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5722 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5723 case AUDIO_USAGE_NOTIFICATION_EVENT:
5724 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5725 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5726 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5727 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005728 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005729 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005730 break;
5731 default:
5732 return false;
5733 }
5734 return true;
5735}
5736
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005737bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005738 routing_strategy strategy, uint32_t inPastMs,
5739 nsecs_t sysTime) const
5740{
5741 if ((sysTime == 0) && (inPastMs != 0)) {
5742 sysTime = systemTime();
5743 }
Eric Laurent794fde22016-03-11 09:50:45 -08005744 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005745 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurent97ac8712018-07-27 18:59:02 -07005746 (STRATEGY_NONE == strategy)) &&
François Gaffiead3183e2015-03-18 16:55:35 +01005747 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5748 return true;
5749 }
5750 }
5751 return false;
5752}
5753
Eric Laurent484e9272018-06-07 17:29:23 -07005754bool AudioPolicyManager::isStrategyActiveOnSameModule(const sp<AudioOutputDescriptor>& outputDesc,
5755 routing_strategy strategy, uint32_t inPastMs,
5756 nsecs_t sysTime) const
5757{
5758 for (size_t i = 0; i < mOutputs.size(); i++) {
5759 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5760 if (outputDesc->sharesHwModuleWith(desc)
5761 && isStrategyActive(desc, strategy, inPastMs, sysTime)) {
5762 return true;
5763 }
5764 }
5765 return false;
5766}
5767
François Gaffie2110e042015-03-24 08:41:51 +01005768audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5769{
5770 return mEngine->getForceUse(usage);
5771}
5772
5773bool AudioPolicyManager::isInCall()
5774{
5775 return isStateInCall(mEngine->getPhoneState());
5776}
5777
5778bool AudioPolicyManager::isStateInCall(int state)
5779{
5780 return is_state_in_call(state);
5781}
5782
Eric Laurentd60560a2015-04-10 11:31:20 -07005783void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5784{
5785 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005786 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5787 if (sourceDesc->srcDevice()->equals(deviceDesc)) {
5788 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->portId());
5789 stopAudioSource(sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005790 }
5791 }
5792
5793 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5794 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5795 bool release = false;
5796 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5797 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5798 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5799 source->ext.device.type == deviceDesc->type()) {
5800 release = true;
5801 }
5802 }
5803 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5804 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5805 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5806 sink->ext.device.type == deviceDesc->type()) {
5807 release = true;
5808 }
5809 }
5810 if (release) {
5811 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5812 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5813 }
5814 }
5815}
5816
Phil Burk09bc4612016-02-24 15:58:15 -08005817// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005818void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5819 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005820 // TODO Set this based on Config properties.
5821 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005822
5823 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5824 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005825 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005826
jiabin81772902018-04-02 17:52:27 -07005827 // If MANUAL, keep the supported surround sound formats as current enabled ones.
5828 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
5829 formats.clear();
5830 for (auto it = mSurroundFormats.begin(); it != mSurroundFormats.end(); it++) {
5831 formats.add(*it);
Phil Burk09bc4612016-02-24 15:58:15 -08005832 }
jiabin81772902018-04-02 17:52:27 -07005833 // Always enable IEC61937 when in MANUAL mode.
5834 formats.add(AUDIO_FORMAT_IEC61937);
5835 } else { // NEVER, AUTO or ALWAYS
5836 // Analyze original support for various formats.
5837 bool supportsAC3 = false;
5838 bool supportsOtherSurround = false;
5839 bool supportsIEC61937 = false;
5840 mSurroundFormats.clear();
5841 for (ssize_t formatIndex = 0; formatIndex < (ssize_t)formats.size(); formatIndex++) {
5842 audio_format_t format = formats[formatIndex];
5843 switch (format) {
5844 case AUDIO_FORMAT_AC3:
5845 supportsAC3 = true;
5846 break;
5847 case AUDIO_FORMAT_E_AC3:
5848 case AUDIO_FORMAT_DTS:
5849 case AUDIO_FORMAT_DTS_HD:
5850 // If ALWAYS, remove all other surround formats here
5851 // since we will add them later.
5852 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5853 formats.removeAt(formatIndex);
5854 formatIndex--;
5855 }
5856 supportsOtherSurround = true;
5857 break;
5858 case AUDIO_FORMAT_IEC61937:
5859 supportsIEC61937 = true;
5860 break;
5861 default:
5862 break;
5863 }
5864 }
Phil Burk09bc4612016-02-24 15:58:15 -08005865
jiabin81772902018-04-02 17:52:27 -07005866 // Modify formats based on surround preferences.
5867 // If NEVER, remove support for surround formats.
5868 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5869 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5870 // Remove surround sound related formats.
5871 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5872 audio_format_t format = formats[formatIndex];
5873 switch(format) {
5874 case AUDIO_FORMAT_AC3:
5875 case AUDIO_FORMAT_E_AC3:
5876 case AUDIO_FORMAT_DTS:
5877 case AUDIO_FORMAT_DTS_HD:
5878 case AUDIO_FORMAT_IEC61937:
5879 formats.removeAt(formatIndex);
5880 break;
5881 default:
5882 formatIndex++; // keep it
5883 break;
5884 }
5885 }
5886 supportsAC3 = false;
5887 supportsOtherSurround = false;
5888 supportsIEC61937 = false;
5889 }
5890 } else { // AUTO or ALWAYS
5891 // Most TVs support AC3 even if they do not report it in the EDID.
5892 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
5893 && !supportsAC3) {
5894 formats.add(AUDIO_FORMAT_AC3);
5895 supportsAC3 = true;
5896 }
5897
5898 // If ALWAYS, add support for raw surround formats if all are missing.
5899 // This assumes that if any of these formats are reported by the HAL
5900 // then the report is valid and should not be modified.
5901 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5902 formats.add(AUDIO_FORMAT_E_AC3);
5903 formats.add(AUDIO_FORMAT_DTS);
5904 formats.add(AUDIO_FORMAT_DTS_HD);
5905 supportsOtherSurround = true;
5906 }
5907
5908 // Add support for IEC61937 if any raw surround supported.
5909 // The HAL could do this but add it here, just in case.
5910 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
5911 formats.add(AUDIO_FORMAT_IEC61937);
5912 supportsIEC61937 = true;
5913 }
5914
5915 // Add reported surround sound formats to enabled surround formats.
5916 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
Phil Burk07ac1142016-03-25 13:39:29 -07005917 audio_format_t format = formats[formatIndex];
5918 switch(format) {
5919 case AUDIO_FORMAT_AC3:
5920 case AUDIO_FORMAT_E_AC3:
5921 case AUDIO_FORMAT_DTS:
5922 case AUDIO_FORMAT_DTS_HD:
jiabin81772902018-04-02 17:52:27 -07005923 case AUDIO_FORMAT_AAC_LC:
5924 case AUDIO_FORMAT_DOLBY_TRUEHD:
5925 case AUDIO_FORMAT_E_AC3_JOC:
5926 mSurroundFormats.insert(format);
Phil Burk07ac1142016-03-25 13:39:29 -07005927 default:
Phil Burk07ac1142016-03-25 13:39:29 -07005928 break;
5929 }
Phil Burk09bc4612016-02-24 15:58:15 -08005930 }
Phil Burk07ac1142016-03-25 13:39:29 -07005931 }
Phil Burk09bc4612016-02-24 15:58:15 -08005932 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005933}
5934
5935// Modify the list of channel masks supported.
5936void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
5937 ChannelsVector &channelMasks = *channelMasksPtr;
5938 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5939 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5940
5941 // If NEVER, then remove support for channelMasks > stereo.
5942 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5943 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5944 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5945 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5946 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5947 channelMasks.removeAt(maskIndex);
5948 } else {
5949 maskIndex++;
5950 }
5951 }
jiabin81772902018-04-02 17:52:27 -07005952 // If ALWAYS or MANUAL, then make sure we at least support 5.1
5953 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
5954 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005955 bool supports5dot1 = false;
5956 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005957 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005958 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5959 supports5dot1 = true;
5960 break;
5961 }
5962 }
5963 // If not then add 5.1 support.
5964 if (!supports5dot1) {
5965 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
5966 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
5967 }
Phil Burk09bc4612016-02-24 15:58:15 -08005968 }
5969}
5970
Phil Burk00eeb322016-03-31 12:41:00 -07005971void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
5972 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005973 AudioProfileVector &profiles)
5974{
5975 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07005976
François Gaffie112b0af2015-11-19 16:13:25 +01005977 // Format MUST be checked first to update the list of AudioProfile
5978 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005979 reply = mpClientInterface->getParameters(
5980 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07005981 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005982 AudioParameter repliedParameters(reply);
5983 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005984 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005985 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5986 return;
5987 }
Phil Burk09bc4612016-02-24 15:58:15 -08005988 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07005989 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005990 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005991 }
Phil Burk09bc4612016-02-24 15:58:15 -08005992 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005993 }
François Gaffie112b0af2015-11-19 16:13:25 +01005994
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005995 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08005996 ChannelsVector channelMasks;
5997 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005998 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07005999 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01006000
6001 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006002 reply = mpClientInterface->getParameters(
6003 ioHandle,
6004 requestedParameters.toString() + ";" +
6005 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01006006 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006007 AudioParameter repliedParameters(reply);
6008 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006009 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006010 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01006011 }
6012 }
6013 if (profiles.hasDynamicChannelsFor(format)) {
6014 reply = mpClientInterface->getParameters(ioHandle,
6015 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07006016 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01006017 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006018 AudioParameter repliedParameters(reply);
6019 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006020 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006021 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07006022 if (device == AUDIO_DEVICE_OUT_HDMI) {
6023 filterSurroundChannelMasks(&channelMasks);
6024 }
François Gaffie112b0af2015-11-19 16:13:25 +01006025 }
6026 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08006027 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006028 }
6029}
Eric Laurentd60560a2015-04-10 11:31:20 -07006030
Mikhail Naganovdc769682018-05-04 15:34:08 -07006031status_t AudioPolicyManager::installPatch(const char *caller,
6032 audio_patch_handle_t *patchHandle,
6033 AudioIODescriptorInterface *ioDescriptor,
6034 const struct audio_patch *patch,
6035 int delayMs)
6036{
6037 ssize_t index = mAudioPatches.indexOfKey(
6038 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6039 *patchHandle : ioDescriptor->getPatchHandle());
6040 sp<AudioPatch> patchDesc;
6041 status_t status = installPatch(
6042 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6043 if (status == NO_ERROR) {
6044 ioDescriptor->setPatchHandle(patchDesc->mHandle);
6045 }
6046 return status;
6047}
6048
6049status_t AudioPolicyManager::installPatch(const char *caller,
6050 ssize_t index,
6051 audio_patch_handle_t *patchHandle,
6052 const struct audio_patch *patch,
6053 int delayMs,
6054 uid_t uid,
6055 sp<AudioPatch> *patchDescPtr)
6056{
6057 sp<AudioPatch> patchDesc;
6058 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6059 if (index >= 0) {
6060 patchDesc = mAudioPatches.valueAt(index);
6061 afPatchHandle = patchDesc->mAfPatchHandle;
6062 }
6063
6064 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6065 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6066 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6067 if (status == NO_ERROR) {
6068 if (index < 0) {
6069 patchDesc = new AudioPatch(patch, uid);
6070 addAudioPatch(patchDesc->mHandle, patchDesc);
6071 } else {
6072 patchDesc->mPatch = *patch;
6073 }
6074 patchDesc->mAfPatchHandle = afPatchHandle;
6075 if (patchHandle) {
6076 *patchHandle = patchDesc->mHandle;
6077 }
6078 nextAudioPortGeneration();
6079 mpClientInterface->onAudioPatchListUpdate();
6080 }
6081 if (patchDescPtr) *patchDescPtr = patchDesc;
6082 return status;
6083}
6084
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006085} // namespace android