blob: 600f9685cbff5d51497bccd8a432c15b76a95ecc [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
Nadav Bar766fb022018-01-07 12:18:03 +02001016 status = outputDesc->open(config, device, address, stream, *flags, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07001017
1018 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001019 if (status != NO_ERROR ||
Eric Laurentfe231122017-11-17 17:48:06 -08001020 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
Andy Hung5659ed52018-04-30 10:31:26 -07001021 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->mFormat) ||
Eric Laurentfe231122017-11-17 17:48:06 -08001022 (config->channel_mask != 0 && config->channel_mask != outputDesc->mChannelMask)) {
1023 ALOGV("getOutputForDevice() failed opening direct output: output %d sample rate %d %d,"
1024 "format %d %d, channel mask %04x %04x", output, config->sample_rate,
1025 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
1026 config->channel_mask, outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001027 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001028 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07001029 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001030 // fall back to mixer output if possible when the direct output could not be open
Eric Laurentfe231122017-11-17 17:48:06 -08001031 if (audio_is_linear_pcm(config->format) &&
1032 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -08001033 goto non_direct_output;
1034 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001035 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001036 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001037 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -08001038 outputDesc->mDirectClientSession = session;
1039
Eric Laurente552edb2014-03-10 17:42:56 -07001040 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001041 mPreviousOutputs = mOutputs;
Eric Laurentf4e63452017-11-06 19:31:46 +00001042 ALOGV("getOutputForDevice() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001043 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001044 return output;
1045 }
1046
Eric Laurentb732cf52014-09-24 19:08:21 -07001047non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001048
1049 // A request for HW A/V sync cannot fallback to a mixed output because time
1050 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001051 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001052 return AUDIO_IO_HANDLE_NONE;
1053 }
1054
Eric Laurente552edb2014-03-10 17:42:56 -07001055 // ignoring channel mask due to downmix capability in mixer
1056
1057 // open a non direct output
1058
1059 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001060 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001061 // get which output is suitable for the specified stream. The actual
1062 // routing change will happen when startOutput() will be called
1063 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1064
Eric Laurent8838a382014-09-08 16:44:28 -07001065 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001066 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1067 output = selectOutput(outputs, *flags, config->format);
Eric Laurente552edb2014-03-10 17:42:56 -07001068 }
Eric Laurentf4e63452017-11-06 19:31:46 +00001069 ALOGW_IF((output == 0), "getOutputForDevice() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001070 "sampling rate %d, format %#x, channels %#x, flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +02001071 stream, config->sample_rate, config->format, config->channel_mask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001072
Eric Laurente552edb2014-03-10 17:42:56 -07001073 return output;
1074}
1075
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001076sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
1077 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1078 if (msdModule != 0) {
1079 DeviceVector msdInputDevices = mAvailableInputDevices.getDevicesFromHwModule(
1080 msdModule->getHandle());
1081 if (!msdInputDevices.isEmpty()) return msdInputDevices.itemAt(0);
1082 }
1083 return 0;
1084}
1085
1086audio_devices_t AudioPolicyManager::getMsdAudioOutDeviceTypes() const {
1087 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1088 if (msdModule != 0) {
1089 return mAvailableOutputDevices.getDeviceTypesFromHwModule(msdModule->getHandle());
1090 }
1091 return AUDIO_DEVICE_NONE;
1092}
1093
1094const AudioPatchCollection AudioPolicyManager::getMsdPatches() const {
1095 AudioPatchCollection msdPatches;
1096 audio_module_handle_t msdModuleHandle = mHwModules.getModuleFromName(
1097 AUDIO_HARDWARE_MODULE_ID_MSD)->getHandle();
1098 if (msdModuleHandle == AUDIO_MODULE_HANDLE_NONE) return msdPatches;
1099 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1100 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1101 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1102 const struct audio_port_config *source = &patch->mPatch.sources[j];
1103 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1104 source->ext.device.hw_module == msdModuleHandle) {
1105 msdPatches.addAudioPatch(patch->mHandle, patch);
1106 }
1107 }
1108 }
1109 return msdPatches;
1110}
1111
1112status_t AudioPolicyManager::getBestMsdAudioProfileFor(audio_devices_t outputDevice,
1113 bool hwAvSync, audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1114{
1115 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1116 if (msdModule == nullptr) {
1117 ALOGE("%s() unable to get MSD module", __func__);
1118 return NO_INIT;
1119 }
1120 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(outputDevice);
1121 if (deviceModule == nullptr) {
1122 ALOGE("%s() unable to get module for %#x", __func__, outputDevice);
1123 return NO_INIT;
1124 }
1125 const InputProfileCollection &inputProfiles = msdModule->getInputProfiles();
1126 if (inputProfiles.isEmpty()) {
1127 ALOGE("%s() no input profiles for MSD module", __func__);
1128 return NO_INIT;
1129 }
1130 const OutputProfileCollection &outputProfiles = deviceModule->getOutputProfiles();
1131 if (outputProfiles.isEmpty()) {
1132 ALOGE("%s() no output profiles for device %#x", __func__, outputDevice);
1133 return NO_INIT;
1134 }
1135 AudioProfileVector msdProfiles;
1136 // Each IOProfile represents a MixPort from audio_policy_configuration.xml
1137 for (const auto &inProfile : inputProfiles) {
1138 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0)) {
1139 msdProfiles.appendVector(inProfile->getAudioProfiles());
1140 }
1141 }
1142 AudioProfileVector deviceProfiles;
1143 for (const auto &outProfile : outputProfiles) {
1144 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0)) {
1145 deviceProfiles.appendVector(outProfile->getAudioProfiles());
1146 }
1147 }
1148 struct audio_config_base bestSinkConfig;
1149 status_t result = msdProfiles.findBestMatchingOutputConfig(deviceProfiles,
1150 compressedFormatsOrder, surroundChannelMasksOrder, true /*preferHigherSamplingRates*/,
1151 &bestSinkConfig);
1152 if (result != NO_ERROR) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001153 ALOGD("%s() no matching profiles found for device: %#x, hwAvSync: %d",
1154 __func__, outputDevice, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001155 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001156 }
1157 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1158 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1159 sinkConfig->format = bestSinkConfig.format;
1160 // For encoded streams force direct flag to prevent downstream mixing.
1161 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1162 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
1163 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1164 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1165 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1166 sourceConfig->format = bestSinkConfig.format;
1167 // Copy input stream directly without any processing (e.g. resampling).
1168 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1169 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1170 if (hwAvSync) {
1171 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1172 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1173 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1174 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1175 }
1176 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1177 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1178 sinkConfig->config_mask |= config_mask;
1179 sourceConfig->config_mask |= config_mask;
1180 return NO_ERROR;
1181}
1182
1183PatchBuilder AudioPolicyManager::buildMsdPatch(audio_devices_t outputDevice) const
1184{
1185 PatchBuilder patchBuilder;
1186 patchBuilder.addSource(getMsdAudioInDevice()).
1187 addSink(findDevice(mAvailableOutputDevices, outputDevice));
1188 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1189 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
1190 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1191 // For now, we just forcefully try with HwAvSync first.
1192 status_t res = getBestMsdAudioProfileFor(outputDevice, true /*hwAvSync*/,
1193 &sourceConfig, &sinkConfig) == NO_ERROR ? NO_ERROR :
1194 getBestMsdAudioProfileFor(
1195 outputDevice, false /*hwAvSync*/, &sourceConfig, &sinkConfig);
1196 if (res == NO_ERROR) {
1197 // Found a matching profile for encoded audio. Re-create PatchBuilder with this config.
1198 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1199 }
1200 ALOGV("%s() no matching profile found. Fall through to default PCM patch"
1201 " supporting PCM format conversion.", __func__);
1202 return patchBuilder;
1203}
1204
1205status_t AudioPolicyManager::setMsdPatch(audio_devices_t outputDevice) {
1206 ALOGV("%s() for outputDevice %#x", __func__, outputDevice);
1207 if (outputDevice == AUDIO_DEVICE_NONE) {
1208 // Use media strategy for unspecified output device. This should only
1209 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1210 // therefore invalidate explicit routing requests.
1211 outputDevice = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
1212 }
1213 PatchBuilder patchBuilder = buildMsdPatch(outputDevice);
1214 const struct audio_patch* patch = patchBuilder.patch();
1215 const AudioPatchCollection msdPatches = getMsdPatches();
1216 if (!msdPatches.isEmpty()) {
1217 LOG_ALWAYS_FATAL_IF(msdPatches.size() > 1,
1218 "The current MSD prototype only supports one output patch");
1219 sp<AudioPatch> currentPatch = msdPatches.valueAt(0);
1220 if (audio_patches_are_equal(&currentPatch->mPatch, patch)) {
1221 return NO_ERROR;
1222 }
1223 releaseAudioPatch(currentPatch->mHandle, mUidCached);
1224 }
1225 status_t status = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1226 patch, 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1227 ALOGE_IF(status != NO_ERROR, "%s() error %d creating MSD audio patch", __func__, status);
1228 ALOGI_IF(status == NO_ERROR, "%s() Patch created from MSD_IN to "
1229 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__, outputDevice,
1230 patch->sources[0].format, patch->sources[0].channel_mask, patch->sources[0].sample_rate);
1231 return status;
1232}
1233
Eric Laurente0720872014-03-11 09:30:41 -07001234audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001235 audio_output_flags_t flags,
1236 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001237{
1238 // select one output among several that provide a path to a particular device or set of
1239 // devices (the list was previously build by getOutputsForDevice()).
1240 // The priority is as follows:
1241 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001242 // 2: the output with the bit depth the closest to the requested one
1243 // 3: the primary output
1244 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001245
1246 if (outputs.size() == 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001247 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001248 }
1249 if (outputs.size() == 1) {
1250 return outputs[0];
1251 }
1252
1253 int maxCommonFlags = 0;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001254 audio_io_handle_t outputForFlags = AUDIO_IO_HANDLE_NONE;
1255 audio_io_handle_t outputForPrimary = AUDIO_IO_HANDLE_NONE;
1256 audio_io_handle_t outputForFormat = AUDIO_IO_HANDLE_NONE;
Eric Laurente6930022016-02-11 10:20:40 -08001257 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1258 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001259
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001260 for (audio_io_handle_t output : outputs) {
1261 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001262 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001263 // if a valid format is specified, skip output if not compatible
1264 if (format != AUDIO_FORMAT_INVALID) {
1265 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Andy Hung5659ed52018-04-30 10:31:26 -07001266 if (format != outputDesc->mFormat) {
Eric Laurent8838a382014-09-08 16:44:28 -07001267 continue;
1268 }
1269 } else if (!audio_is_linear_pcm(format)) {
1270 continue;
1271 }
Eric Laurente6930022016-02-11 10:20:40 -08001272 if (AudioPort::isBetterFormatMatch(
1273 outputDesc->mFormat, bestFormat, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001274 outputForFormat = output;
Eric Laurente6930022016-02-11 10:20:40 -08001275 bestFormat = outputDesc->mFormat;
1276 }
Eric Laurent8838a382014-09-08 16:44:28 -07001277 }
1278
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001279 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001280 if (commonFlags >= maxCommonFlags) {
1281 if (commonFlags == maxCommonFlags) {
Andy Hungc9901522017-11-10 20:07:54 -08001282 if (format != AUDIO_FORMAT_INVALID
1283 && AudioPort::isBetterFormatMatch(
1284 outputDesc->mFormat, bestFormatForFlags, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001285 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001286 bestFormatForFlags = outputDesc->mFormat;
1287 }
1288 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001289 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001290 maxCommonFlags = commonFlags;
1291 bestFormatForFlags = outputDesc->mFormat;
1292 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001293 ALOGV("selectOutput() commonFlags for output %d, %04x", output, commonFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001294 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001295 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001296 outputForPrimary = output;
Eric Laurente552edb2014-03-10 17:42:56 -07001297 }
1298 }
1299 }
1300
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001301 if (outputForFlags != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001302 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001303 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001304 if (outputForFormat != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001305 return outputForFormat;
1306 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001307 if (outputForPrimary != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001308 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001309 }
1310
1311 return outputs[0];
1312}
1313
Eric Laurent8fc147b2018-07-22 19:13:55 -07001314status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001315{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001316 ALOGV("%s portId %d", __FUNCTION__, portId);
1317
1318 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1319 if (outputDesc == 0) {
1320 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001321 return BAD_VALUE;
1322 }
Eric Laurent97ac8712018-07-27 18:59:02 -07001323 sp<TrackClientDescriptor> client = outputDesc->clientsMap()[portId];
Eric Laurente552edb2014-03-10 17:42:56 -07001324
Eric Laurent8fc147b2018-07-22 19:13:55 -07001325 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001326 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001327
Eric Laurent733ce942017-12-07 12:18:25 -08001328 status_t status = outputDesc->start();
1329 if (status != NO_ERROR) {
1330 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001331 }
1332
Eric Laurent97ac8712018-07-27 18:59:02 -07001333 uint32_t delayMs;
1334 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001335
1336 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001337 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001338 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001339 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001340 if (delayMs != 0) {
1341 usleep(delayMs * 1000);
1342 }
1343
1344 return status;
1345}
1346
Eric Laurent97ac8712018-07-27 18:59:02 -07001347status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1348 const sp<TrackClientDescriptor>& client,
1349 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001350{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001351 // cannot start playback of STREAM_TTS if any other output is being used
1352 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001353
1354 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001355 audio_stream_type_t stream = client->stream();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001356 if (stream == AUDIO_STREAM_TTS) {
1357 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001358 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001359 return INVALID_OPERATION;
1360 } else {
1361 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1362 }
1363 } else {
1364 // some playback other than beacon starts
1365 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1366 }
1367
Eric Laurent77305a62016-07-25 16:39:22 -07001368 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001369 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001370 bool force = !outputDesc->isActive() &&
1371 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001372
Eric Laurent97ac8712018-07-27 18:59:02 -07001373 audio_devices_t device = AUDIO_DEVICE_NONE;
1374 AudioMix *policyMix = NULL;
1375 const char *address = NULL;
1376 if (outputDesc->mPolicyMix != NULL) {
1377 policyMix = outputDesc->mPolicyMix;
1378 address = policyMix->mDeviceAddress.string();
1379 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1380 device = policyMix->mDeviceType;
1381 } else {
1382 device = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1383 }
1384 }
1385
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001386 // requiresMuteCheck is false when we can bypass mute strategy.
1387 // It covers a common case when there is no materially active audio
1388 // and muting would result in unnecessary delay and dropped audio.
1389 const uint32_t outputLatencyMs = outputDesc->latency();
1390 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1391
Eric Laurente552edb2014-03-10 17:42:56 -07001392 // increment usage count for this stream on the requested output:
1393 // NOTE that the usage count is the same for duplicated output and hardware output which is
1394 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001395 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001396
1397 if (client->hasPreferredDevice(true)) {
1398 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
1399 if (device != outputDesc->device()) {
1400 checkStrategyRoute(getStrategy(stream), outputDesc->mIoHandle);
1401 }
1402 }
Eric Laurente552edb2014-03-10 17:42:56 -07001403
Eric Laurent36829f92017-04-07 19:04:42 -07001404 if (stream == AUDIO_STREAM_MUSIC) {
1405 selectOutputForMusicEffects();
1406 }
1407
Eric Laurent592dd7b2018-08-05 18:58:48 -07001408 if (outputDesc->streamActiveCount(stream) == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001409 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001410 if (device == AUDIO_DEVICE_NONE) {
1411 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001412 }
Eric Laurent36829f92017-04-07 19:04:42 -07001413
Eric Laurente552edb2014-03-10 17:42:56 -07001414 routing_strategy strategy = getStrategy(stream);
1415 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001416 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1417 (beaconMuteLatency > 0);
1418 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001419 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001420 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001421 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001422 // An output has a shared device if
1423 // - managed by the same hw module
1424 // - supports the currently selected device
1425 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
1426 && (desc->supportedDevices() & device) != AUDIO_DEVICE_NONE;
1427
Eric Laurent77305a62016-07-25 16:39:22 -07001428 // force a device change if any other output is:
1429 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001430 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001431 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001432 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001433 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001434 // change the device currently selected by the other output.
1435 if (sharedDevice &&
Eric Laurent77305a62016-07-25 16:39:22 -07001436 desc->device() != device &&
Eric Laurent77305a62016-07-25 16:39:22 -07001437 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001438 force = true;
1439 }
1440 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001441 // a notification so that audio focus effect can propagate, or that a mute/unmute
1442 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001443 const uint32_t latencyMs = desc->latency();
1444 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1445
1446 if (shouldWait && isActive && (waitMs < latencyMs)) {
1447 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001448 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001449
1450 // Require mute check if another output is on a shared device
1451 // and currently active to have proper drain and avoid pops.
1452 // Note restoring AudioTracks onto this output needs to invoke
1453 // a volume ramp if there is no mute.
1454 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001455 }
1456 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001457
1458 const uint32_t muteWaitMs =
1459 setOutputDevice(outputDesc, device, force, 0, NULL, address, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001460
Eric Laurente552edb2014-03-10 17:42:56 -07001461 // apply volume rules for current stream and device if necessary
1462 checkAndSetVolume(stream,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001463 mVolumeCurves->getVolumeIndex(stream, outputDesc->device()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001464 outputDesc,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001465 outputDesc->device());
Eric Laurente552edb2014-03-10 17:42:56 -07001466
1467 // update the outputs if starting an output with a stream that can affect notification
1468 // routing
1469 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001470
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001471 // force reevaluating accessibility routing when ringtone or alarm starts
1472 if (strategy == STRATEGY_SONIFICATION) {
1473 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1474 }
Eric Laurentdc462862016-07-19 12:29:53 -07001475
1476 if (waitMs > muteWaitMs) {
1477 *delayMs = waitMs - muteWaitMs;
1478 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001479
1480 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1481 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1482 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1483 // change occurs after the MixerThread starts and causes a stream volume
1484 // glitch.
1485 //
1486 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001487 }
Eric Laurentdc462862016-07-19 12:29:53 -07001488
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001489 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1490 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1491 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1492 }
1493
Eric Laurent97ac8712018-07-27 18:59:02 -07001494 // Automatically enable the remote submix input when output is started on a re routing mix
1495 // of type MIX_TYPE_RECORDERS
1496 if (audio_is_remote_submix_device(device) && policyMix != NULL &&
1497 policyMix->mMixType == MIX_TYPE_RECORDERS) {
1498 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1499 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1500 address,
1501 "remote-submix");
1502 }
1503
Eric Laurente552edb2014-03-10 17:42:56 -07001504 return NO_ERROR;
1505}
1506
Eric Laurent8fc147b2018-07-22 19:13:55 -07001507status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001508{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001509 ALOGV("%s portId %d", __FUNCTION__, portId);
1510
1511 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1512 if (outputDesc == 0) {
1513 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001514 return BAD_VALUE;
1515 }
Eric Laurent97ac8712018-07-27 18:59:02 -07001516 sp<TrackClientDescriptor> client = outputDesc->clientsMap()[portId];
Eric Laurente552edb2014-03-10 17:42:56 -07001517
Eric Laurent97ac8712018-07-27 18:59:02 -07001518 ALOGV("stopOutput() output %d, stream %d, session %d",
1519 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07001520
Eric Laurent97ac8712018-07-27 18:59:02 -07001521 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08001522
Eric Laurent733ce942017-12-07 12:18:25 -08001523 if (status == NO_ERROR ) {
1524 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001525 }
1526 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001527}
1528
Eric Laurent97ac8712018-07-27 18:59:02 -07001529status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1530 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07001531{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001532 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07001533 audio_stream_type_t stream = client->stream();
1534
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001535 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1536
Eric Laurent592dd7b2018-08-05 18:58:48 -07001537 if (outputDesc->streamActiveCount(stream) > 0) {
1538 if (outputDesc->streamActiveCount(stream) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001539 // Automatically disable the remote submix input when output is stopped on a
1540 // re routing mix of type MIX_TYPE_RECORDERS
1541 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1542 outputDesc->mPolicyMix != NULL &&
1543 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1544 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1545 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1546 outputDesc->mPolicyMix->mDeviceAddress,
1547 "remote-submix");
1548 }
1549 }
1550 bool forceDeviceUpdate = false;
1551 if (client->hasPreferredDevice(true)) {
1552 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1553 forceDeviceUpdate = true;
1554 }
1555
Eric Laurente552edb2014-03-10 17:42:56 -07001556 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07001557 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07001558
Eric Laurente552edb2014-03-10 17:42:56 -07001559 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001560 if (outputDesc->streamActiveCount(stream) == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001561 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001562 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001563 // delay the device switch by twice the latency because stopOutput() is executed when
1564 // the track stop() command is received and at that time the audio track buffer can
1565 // still contain data that needs to be drained. The latency only covers the audio HAL
1566 // and kernel buffers. Also the latency does not always include additional delay in the
1567 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001568 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001569
1570 // force restoring the device selection on other active outputs if it differs from the
1571 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001572 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001573 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001574 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001575 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001576 desc->isActive() &&
1577 outputDesc->sharesHwModuleWith(desc) &&
1578 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001579 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1580 bool force = desc->device() != newDevice2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001581
Eric Laurentc75307b2015-03-17 15:29:32 -07001582 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001583 newDevice2,
1584 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001585 delayMs);
1586 // re-apply device specific volume if not done by setOutputDevice()
1587 if (!force) {
1588 applyStreamVolumes(desc, newDevice2, delayMs);
1589 }
Eric Laurente552edb2014-03-10 17:42:56 -07001590 }
1591 }
1592 // update the outputs if stopping one with a stream that can affect notification routing
1593 handleNotificationRoutingForStream(stream);
1594 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001595
1596 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1597 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1598 setStrategyMute(STRATEGY_SONIFICATION, false, outputDesc);
1599 }
1600
Eric Laurent36829f92017-04-07 19:04:42 -07001601 if (stream == AUDIO_STREAM_MUSIC) {
1602 selectOutputForMusicEffects();
1603 }
Eric Laurente552edb2014-03-10 17:42:56 -07001604 return NO_ERROR;
1605 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001606 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001607 return INVALID_OPERATION;
1608 }
1609}
1610
Eric Laurent8fc147b2018-07-22 19:13:55 -07001611void AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001612{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001613 ALOGV("%s portId %d", __FUNCTION__, portId);
1614
1615 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1616 if (outputDesc == 0) {
1617 ALOGW("releaseOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001618 return;
1619 }
Eric Laurent97ac8712018-07-27 18:59:02 -07001620 sp<TrackClientDescriptor> client = outputDesc->clientsMap()[portId];
Eric Laurent8fc147b2018-07-22 19:13:55 -07001621
1622 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001623
Eric Laurent8fc147b2018-07-22 19:13:55 -07001624 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1625 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001626 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07001627 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001628 return;
1629 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001630 if (--outputDesc->mDirectOpenCount == 0) {
1631 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07001632 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001633 }
1634 }
Eric Laurent97ac8712018-07-27 18:59:02 -07001635 outputDesc->clientsMap().erase(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001636}
1637
1638
Eric Laurentcaf7f482014-11-25 17:50:47 -08001639status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1640 audio_io_handle_t *input,
1641 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001642 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001643 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001644 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001645 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001646 input_type_t *inputType,
1647 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001648{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001649 ALOGV("getInputForAttr() source %d, sampling rate %d, format %#x, channel mask %#x,"
Eric Laurentcaf7f482014-11-25 17:50:47 -08001650 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001651 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001652
Eric Laurentad2e7b92017-09-14 20:06:42 -07001653 status_t status = NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -08001654 // handle legacy remote submix case where the address was not always specified
1655 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001656 audio_source_t halInputSource;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001657 audio_source_t inputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001658 AudioMix *policyMix = NULL;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001659 DeviceVector inputDevices;
Eric Laurent8fc147b2018-07-22 19:13:55 -07001660 sp<AudioInputDescriptor> inputDesc;
1661 sp<RecordClientDescriptor> clientDesc;
1662 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001663 bool isSoundTrigger;
1664 audio_devices_t device;
1665
1666 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1667 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1668 return INVALID_OPERATION;
1669 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001670
Eric Laurentfe231122017-11-17 17:48:06 -08001671 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1672 inputSource = AUDIO_SOURCE_MIC;
1673 }
1674
Paul McLean466dc8e2015-04-17 13:15:36 -06001675 // Explicit routing?
1676 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -07001677 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
jiabinc0c831a2018-01-29 17:55:15 -08001678 deviceDesc = mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001679 }
Paul McLean466dc8e2015-04-17 13:15:36 -06001680
Eric Laurentad2e7b92017-09-14 20:06:42 -07001681 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1682 // possible
1683 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1684 *input != AUDIO_IO_HANDLE_NONE) {
1685 ssize_t index = mInputs.indexOfKey(*input);
1686 if (index < 0) {
1687 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1688 status = BAD_VALUE;
1689 goto error;
1690 }
1691 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001692 RecordClientVector clients = inputDesc->getClientsForSession(session);
1693 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001694 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1695 status = BAD_VALUE;
1696 goto error;
1697 }
1698 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1699 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001700 // corresponds to a new client and is only permitted from the same UID.
1701 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07001702 if (clients.size() > 1) {
1703 for (const auto& client : clients) {
1704 // The client map is ordered by key values (portId) and portIds are allocated
1705 // incrementaly. So the first client in this list is the one opened by audio flinger
1706 // when the mmap stream is created and should be ignored as it does not correspond
1707 // to an actual client
1708 if (client == *clients.cbegin()) {
1709 continue;
1710 }
1711 if (uid != client->uid() && !client->isSilenced()) {
1712 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
1713 uid, client->portId(), client->uid());
1714 status = INVALID_OPERATION;
1715 goto error;
1716 }
Eric Laurent331679c2018-04-16 17:03:16 -07001717 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001718 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001719 *inputType = API_INPUT_LEGACY;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001720 device = inputDesc->mDevice;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001721
Eric Laurent8f42ea12018-08-08 09:08:25 -07001722 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001723 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001724 }
1725
1726 *input = AUDIO_IO_HANDLE_NONE;
1727 *inputType = API_INPUT_INVALID;
1728
Eric Laurentad2e7b92017-09-14 20:06:42 -07001729 halInputSource = inputSource;
1730
Eric Laurentc447ded2015-01-06 08:47:05 -08001731 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001732 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001733 status = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
1734 if (status != NO_ERROR) {
1735 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001736 }
1737 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001738 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1739 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001740 } else {
Eric Laurent97ac8712018-07-27 18:59:02 -07001741 if (deviceDesc != 0) {
1742 device = deviceDesc->type();
1743 } else {
1744 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
1745 }
Eric Laurent275e8e92014-11-30 15:14:47 -08001746 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001747 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001748 status = BAD_VALUE;
1749 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001750 }
Eric Laurentc722f302014-12-10 11:21:49 -08001751 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001752 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001753 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1754 // there is an external policy, but this input is attached to a mix of recorders,
1755 // meaning it receives audio injected into the framework, so the recorder doesn't
1756 // know about it and is therefore considered "legacy"
1757 *inputType = API_INPUT_LEGACY;
1758 } else {
1759 // recording a mix of players defined by an external policy, we're rerouting for
1760 // an external policy
1761 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1762 }
Eric Laurentc722f302014-12-10 11:21:49 -08001763 } else if (audio_is_remote_submix_device(device)) {
1764 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001765 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001766 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1767 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001768 } else {
1769 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001770 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001771
Eric Laurent599c7582015-12-07 18:05:55 -08001772 }
1773
Eric Laurent8f42ea12018-08-08 09:08:25 -07001774 *input = getInputForDevice(device, address, session, inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001775 config, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001776 policyMix);
1777 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001778 status = INVALID_OPERATION;
1779 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001780 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001781
Eric Laurent8f42ea12018-08-08 09:08:25 -07001782exit:
1783
Mikhail Naganov708e0382018-05-30 09:53:04 -07001784 inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -07001785 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
Eric Laurent8f42ea12018-08-08 09:08:25 -07001786 : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07001787
Eric Laurent8f42ea12018-08-08 09:08:25 -07001788 isSoundTrigger = inputSource == AUDIO_SOURCE_HOTWORD &&
1789 mSoundTriggerSessions.indexOfKey(session) > 0;
1790 *portId = AudioPort::getNextUniqueId();
1791
Eric Laurent8fc147b2018-07-22 19:13:55 -07001792 clientDesc = new RecordClientDescriptor(*portId, uid, session,
Eric Laurent8f42ea12018-08-08 09:08:25 -07001793 *attr, *config, requestedDeviceId,
1794 inputSource,flags, isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001795 inputDesc = mInputs.valueFor(*input);
Eric Laurent97ac8712018-07-27 18:59:02 -07001796 inputDesc->clientsMap().emplace(*portId, clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001797
1798 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
1799 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001800
Eric Laurent599c7582015-12-07 18:05:55 -08001801 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001802
1803error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07001804 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001805}
1806
1807
1808audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1809 String8 address,
1810 audio_session_t session,
Eric Laurent599c7582015-12-07 18:05:55 -08001811 audio_source_t inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001812 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08001813 audio_input_flags_t flags,
1814 AudioMix *policyMix)
1815{
1816 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1817 audio_source_t halInputSource = inputSource;
1818 bool isSoundTrigger = false;
1819
1820 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1821 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1822 if (index >= 0) {
1823 input = mSoundTriggerSessions.valueFor(session);
1824 isSoundTrigger = true;
1825 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1826 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1827 } else {
1828 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001829 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001830 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08001831 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001832 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001833 }
1834
Andy Hungf129b032015-04-07 13:45:50 -07001835 // find a compatible input profile (not necessarily identical in parameters)
1836 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08001837 // sampling rate and flags may be updated by getInputProfile
1838 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
1839 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07001840 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08001841 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07001842 audio_input_flags_t profileFlags = flags;
1843 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07001844 profileFormat = config->format; // reset each time through loop, in case it is updated
Eric Laurent275e8e92014-11-30 15:14:47 -08001845 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001846 profileSamplingRate, profileFormat, profileChannelMask,
1847 profileFlags);
1848 if (profile != 0) {
1849 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001850 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1851 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001852 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1853 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1854 } else { // fail
Glenn Kastenfaa10a62017-05-25 15:52:05 -07001855 ALOGW("getInputForDevice() could not find profile for device 0x%X, "
Eric Laurentfe231122017-11-17 17:48:06 -08001856 "sampling rate %u, format %#x, channel mask 0x%X, flags %#x",
1857 device, config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001858 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001859 }
Eric Laurente552edb2014-03-10 17:42:56 -07001860 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001861 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08001862 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08001863 if (samplingRate == 0) {
1864 samplingRate = profileSamplingRate;
1865 }
Eric Laurente552edb2014-03-10 17:42:56 -07001866
Eric Laurent322b4d22015-04-03 15:57:54 -07001867 if (profile->getModuleHandle() == 0) {
1868 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001869 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001870 }
1871
Eric Laurent3974e3b2017-12-07 17:58:43 -08001872 if (!profile->canOpenNewIo()) {
1873 return AUDIO_IO_HANDLE_NONE;
1874 }
1875
Eric Laurentfe231122017-11-17 17:48:06 -08001876 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001877
Eric Laurentfe231122017-11-17 17:48:06 -08001878 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
1879 lConfig.sample_rate = profileSamplingRate;
1880 lConfig.channel_mask = profileChannelMask;
1881 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07001882
Eric Laurent53b810e2017-12-10 17:25:10 -08001883 if (address == "") {
Mikhail Naganov708e0382018-05-30 09:53:04 -07001884 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -08001885 // the inputs vector must be of size >= 1, but we don't want to crash here
1886 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress : String8("");
1887 }
1888
Eric Laurentfe231122017-11-17 17:48:06 -08001889 status_t status = inputDesc->open(&lConfig, device, address,
1890 halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001891
1892 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001893 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08001894 (profileSamplingRate != lConfig.sample_rate) ||
1895 !audio_formats_match(profileFormat, lConfig.format) ||
1896 (profileChannelMask != lConfig.channel_mask)) {
1897 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001898 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08001899 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001900 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001901 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07001902 }
Eric Laurent599c7582015-12-07 18:05:55 -08001903 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001904 }
1905
Eric Laurentc722f302014-12-10 11:21:49 -08001906 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001907
Eric Laurent599c7582015-12-07 18:05:55 -08001908 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001909 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001910
Eric Laurent599c7582015-12-07 18:05:55 -08001911 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001912}
1913
Eric Laurentbb948092017-01-23 18:33:30 -08001914//static
1915bool AudioPolicyManager::isConcurrentSource(audio_source_t source)
1916{
1917 return (source == AUDIO_SOURCE_HOTWORD) ||
1918 (source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
1919 (source == AUDIO_SOURCE_FM_TUNER);
1920}
1921
Chris Thornton2b864642017-06-27 21:26:07 -07001922// FIXME: remove when concurrent capture is ready. This is a hack to work around bug b/63083537.
1923bool AudioPolicyManager::soundTriggerSupportsConcurrentCapture() {
1924 if (!mHasComputedSoundTriggerSupportsConcurrentCapture) {
1925 bool soundTriggerSupportsConcurrentCapture = false;
1926 unsigned int numModules = 0;
1927 struct sound_trigger_module_descriptor* nModules = NULL;
1928
1929 status_t status = SoundTrigger::listModules(nModules, &numModules);
1930 if (status == NO_ERROR && numModules != 0) {
1931 nModules = (struct sound_trigger_module_descriptor*) calloc(
1932 numModules, sizeof(struct sound_trigger_module_descriptor));
1933 if (nModules == NULL) {
1934 // We failed to malloc the buffer, so just say no for now, and hope that we have more
1935 // ram the next time this function is called.
1936 ALOGE("Failed to allocate buffer for module descriptors");
1937 return false;
1938 }
1939
1940 status = SoundTrigger::listModules(nModules, &numModules);
1941 if (status == NO_ERROR) {
1942 soundTriggerSupportsConcurrentCapture = true;
1943 for (size_t i = 0; i < numModules; ++i) {
1944 soundTriggerSupportsConcurrentCapture &=
1945 nModules[i].properties.concurrent_capture;
1946 }
1947 }
1948 free(nModules);
1949 }
1950 mSoundTriggerSupportsConcurrentCapture = soundTriggerSupportsConcurrentCapture;
1951 mHasComputedSoundTriggerSupportsConcurrentCapture = true;
1952 }
1953 return mSoundTriggerSupportsConcurrentCapture;
1954}
1955
Eric Laurentfb66dd92016-01-28 18:32:03 -08001956
Eric Laurent8fc147b2018-07-22 19:13:55 -07001957status_t AudioPolicyManager::startInput(audio_port_handle_t portId,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001958 bool silenced,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001959 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07001960{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001961 *concurrency = API_INPUT_CONCURRENCY_NONE;
1962
1963 ALOGV("%s portId %d", __FUNCTION__, portId);
1964
1965 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
1966 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07001967 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001968 return BAD_VALUE;
1969 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001970 audio_io_handle_t input = inputDesc->mIoHandle;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001971 sp<RecordClientDescriptor> client = inputDesc->clientsMap()[portId];
1972 if (client->active()) {
1973 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
1974 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07001975 }
1976
Eric Laurent8f42ea12018-08-08 09:08:25 -07001977 audio_session_t session = client->session();
1978
1979 ALOGV("%s input:%d, session:%d, silenced:%d, concurrency:%d)",
1980 __FUNCTION__, input, session, silenced, *concurrency);
1981
Eric Laurent74708e72017-04-07 17:13:42 -07001982 if (!is_virtual_input_device(inputDesc->mDevice)) {
1983 if (mCallTxPatch != 0 &&
1984 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1985 ALOGW("startInput(%d) failed: call in progress", input);
Ray Essick84e84a52018-05-03 18:45:07 -07001986 *concurrency |= API_INPUT_CONCURRENCY_CALL;
Eric Laurent74708e72017-04-07 17:13:42 -07001987 return INVALID_OPERATION;
1988 }
1989
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001990 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07001991
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001992 // If a UID is idle and records silence and another not silenced recording starts
1993 // from another UID (idle or active) we stop the current idle UID recording in
1994 // favor of the new one - "There can be only one" TM
1995 if (!silenced) {
1996 for (const auto& activeDesc : activeInputs) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07001997 if ((activeDesc->getAudioPort()->getFlags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001998 activeDesc->getId() == inputDesc->getId()) {
1999 continue;
2000 }
2001
Eric Laurent8f42ea12018-08-08 09:08:25 -07002002 RecordClientVector activeClients = activeDesc->clientsList(true /*activeOnly*/);
2003 for (const auto& activeClient : activeClients) {
2004 if (activeClient->isSilenced()) {
2005 closeClient(activeClient->portId());
2006 ALOGV("%s client %d stopping silenced client %d", __FUNCTION__,
2007 portId, activeClient->portId());
2008 activeInputs = mInputs.getActiveInputs();
2009 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002010 }
2011 }
2012 }
2013
2014 for (const auto& activeDesc : activeInputs) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002015 if ((client->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
Eric Laurentcb4dae22017-07-01 19:39:32 -07002016 activeDesc->getId() == inputDesc->getId()) {
2017 continue;
2018 }
2019
Eric Laurent74708e72017-04-07 17:13:42 -07002020 audio_source_t activeSource = activeDesc->inputSource(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002021 if (client->source() == AUDIO_SOURCE_HOTWORD) {
Eric Laurent74708e72017-04-07 17:13:42 -07002022 if (activeSource == AUDIO_SOURCE_HOTWORD) {
2023 if (activeDesc->hasPreemptedSession(session)) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002024 ALOGW("%s input %d failed for HOTWORD: "
2025 "other input %d already started for HOTWORD", __FUNCTION__,
Eric Laurent74708e72017-04-07 17:13:42 -07002026 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07002027 *concurrency |= API_INPUT_CONCURRENCY_HOTWORD;
Eric Laurent74708e72017-04-07 17:13:42 -07002028 return INVALID_OPERATION;
2029 }
2030 } else {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002031 ALOGV("%s input %d failed for HOTWORD: other input %d already started",
2032 __FUNCTION__, input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07002033 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07002034 return INVALID_OPERATION;
2035 }
2036 } else {
2037 if (activeSource != AUDIO_SOURCE_HOTWORD) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002038 ALOGW("%s input %d failed: other input %d already started", __FUNCTION__,
Eric Laurent74708e72017-04-07 17:13:42 -07002039 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07002040 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07002041 return INVALID_OPERATION;
2042 }
2043 }
2044 }
2045
Chris Thornton2b864642017-06-27 21:26:07 -07002046 // We only need to check if the sound trigger session supports concurrent capture if the
2047 // input is also a sound trigger input. Otherwise, we should preempt any hotword stream
2048 // that's running.
2049 const bool allowConcurrentWithSoundTrigger =
2050 inputDesc->isSoundTrigger() ? soundTriggerSupportsConcurrentCapture() : false;
2051
Eric Laurent74708e72017-04-07 17:13:42 -07002052 // if capture is allowed, preempt currently active HOTWORD captures
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002053 for (const auto& activeDesc : activeInputs) {
Chris Thornton2b864642017-06-27 21:26:07 -07002054 if (allowConcurrentWithSoundTrigger && activeDesc->isSoundTrigger()) {
2055 continue;
2056 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002057 RecordClientVector activeHotwordClients =
2058 activeDesc->clientsList(true, AUDIO_SOURCE_HOTWORD);
2059 if (activeHotwordClients.size() > 0) {
Eric Laurent74708e72017-04-07 17:13:42 -07002060 SortedVector<audio_session_t> sessions = activeDesc->getPreemptedSessions();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002061
2062 for (const auto& activeClient : activeHotwordClients) {
2063 *concurrency |= API_INPUT_CONCURRENCY_PREEMPT;
2064 sessions.add(activeClient->session());
2065 closeClient(activeClient->portId());
2066 ALOGV("%s input %d for HOTWORD preempting HOTWORD input %d", __FUNCTION__,
2067 input, activeDesc->mIoHandle);
2068 }
2069
Eric Laurent74708e72017-04-07 17:13:42 -07002070 inputDesc->setPreemptedSessions(sessions);
Eric Laurent74708e72017-04-07 17:13:42 -07002071 }
2072 }
2073 }
Eric Laurente552edb2014-03-10 17:42:56 -07002074
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002075 // Make sure we start with the correct silence state
Eric Laurent8f42ea12018-08-08 09:08:25 -07002076 client->setSilenced(silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002077
Eric Laurent313d1e72016-01-29 09:56:57 -08002078 // increment activity count before calling getNewInputDevice() below as only active sessions
2079 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002080 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002081
Eric Laurent8f42ea12018-08-08 09:08:25 -07002082 // indicate active capture to sound trigger service if starting capture from a mic on
2083 // primary HW module
2084 audio_devices_t device = getNewInputDevice(inputDesc);
2085 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002086
Eric Laurent8f42ea12018-08-08 09:08:25 -07002087 status_t status = inputDesc->start();
2088 if (status != NO_ERROR) {
2089 inputDesc->setClientActive(client, false);
2090 return status;
2091 }
2092
2093 if (inputDesc->activeCount() == 1) {
2094 // if input maps to a dynamic policy with an activity listener, notify of state change
2095 if ((inputDesc->mPolicyMix != NULL)
2096 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2097 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2098 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002099 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002100
Eric Laurent8f42ea12018-08-08 09:08:25 -07002101 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2102 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2103 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
2104 SoundTrigger::setCaptureState(true);
2105 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002106
Eric Laurent8f42ea12018-08-08 09:08:25 -07002107 // automatically enable the remote submix output when input is started if not
2108 // used by a policy mix of type MIX_TYPE_RECORDERS
2109 // For remote submix (a virtual device), we open only one input per capture request.
2110 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2111 String8 address = String8("");
2112 if (inputDesc->mPolicyMix == NULL) {
2113 address = String8("0");
2114 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2115 address = inputDesc->mPolicyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002116 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002117 if (address != "") {
2118 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2119 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2120 address, "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08002121 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002122 }
Eric Laurente552edb2014-03-10 17:42:56 -07002123 }
2124
Eric Laurent8f42ea12018-08-08 09:08:25 -07002125 ALOGV("%s input %d source = %d exit", __FUNCTION__, input, client->source());
Eric Laurente552edb2014-03-10 17:42:56 -07002126
Eric Laurente552edb2014-03-10 17:42:56 -07002127 return NO_ERROR;
2128}
2129
Eric Laurent8fc147b2018-07-22 19:13:55 -07002130status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002131{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002132 ALOGV("%s portId %d", __FUNCTION__, portId);
2133
2134 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2135 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002136 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002137 return BAD_VALUE;
2138 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002139 audio_io_handle_t input = inputDesc->mIoHandle;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002140 sp<RecordClientDescriptor> client = inputDesc->clientsMap()[portId];
2141 if (!client->active()) {
2142 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002143 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002144 }
2145
Eric Laurent8f42ea12018-08-08 09:08:25 -07002146 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002147
Eric Laurent8f42ea12018-08-08 09:08:25 -07002148 inputDesc->stop();
2149 if (inputDesc->isActive()) {
2150 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2151 } else {
2152 // if input maps to a dynamic policy with an activity listener, notify of state change
2153 if ((inputDesc->mPolicyMix != NULL)
2154 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2155 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2156 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002157 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002158
2159 // automatically disable the remote submix output when input is stopped if not
2160 // used by a policy mix of type MIX_TYPE_RECORDERS
2161 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2162 String8 address = String8("");
2163 if (inputDesc->mPolicyMix == NULL) {
2164 address = String8("0");
2165 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2166 address = inputDesc->mPolicyMix->mDeviceAddress;
2167 }
2168 if (address != "") {
2169 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2170 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2171 address, "remote-submix");
2172 }
2173 }
2174
2175 audio_devices_t device = inputDesc->mDevice;
2176 resetInputDevice(input);
2177
2178 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2179 // primary HW module
2180 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2181 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2182 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
2183 SoundTrigger::setCaptureState(false);
2184 }
2185 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002186 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002187 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002188}
2189
Eric Laurent8fc147b2018-07-22 19:13:55 -07002190void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002191{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002192 ALOGV("%s portId %d", __FUNCTION__, portId);
2193
2194 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2195 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002196 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002197 return;
2198 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002199 sp<RecordClientDescriptor> client = inputDesc->clientsMap()[portId];
Eric Laurent8fc147b2018-07-22 19:13:55 -07002200 audio_io_handle_t input = inputDesc->mIoHandle;
2201
Eric Laurent8f42ea12018-08-08 09:08:25 -07002202 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002203
Eric Laurent8f42ea12018-08-08 09:08:25 -07002204 inputDesc->clientsMap().erase(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002205
Eric Laurent8f42ea12018-08-08 09:08:25 -07002206 if (inputDesc->clientsMap().size() > 0) {
2207 ALOGV("%s %zu clients remaining", __FUNCTION__, inputDesc->clientsMap().size());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002208 return;
2209 }
2210
Eric Laurent05b90f82014-08-27 15:32:29 -07002211 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002212 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002213 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002214}
2215
Eric Laurent8f42ea12018-08-08 09:08:25 -07002216void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002217{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002218 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002219
2220 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002221 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002222 }
2223}
2224
Eric Laurent8f42ea12018-08-08 09:08:25 -07002225void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2226{
2227 stopInput(portId);
2228 releaseInput(portId);
2229}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002230
Eric Laurentd4692962014-05-05 18:13:44 -07002231void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002232 bool patchRemoved = false;
2233
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002234 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002235 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002236 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002237 if (patch_index >= 0) {
2238 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002239 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002240 mAudioPatches.removeItemsAt(patch_index);
2241 patchRemoved = true;
2242 }
Eric Laurentfe231122017-11-17 17:48:06 -08002243 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002244 }
2245 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002246 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002247 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002248
2249 if (patchRemoved) {
2250 mpClientInterface->onAudioPatchListUpdate();
2251 }
Eric Laurentd4692962014-05-05 18:13:44 -07002252}
2253
Eric Laurente0720872014-03-11 09:30:41 -07002254void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002255 int indexMin,
2256 int indexMax)
2257{
2258 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002259 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002260
2261 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002262 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2263 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002264 continue;
2265 }
2266 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002267 }
Eric Laurente552edb2014-03-10 17:42:56 -07002268}
2269
Eric Laurente0720872014-03-11 09:30:41 -07002270status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002271 int index,
2272 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002273{
2274
Nadav Bar7c605f62017-12-25 00:01:52 +02002275 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2276 // app that has MODIFY_PHONE_STATE permission.
2277 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
2278 !(stream == AUDIO_STREAM_VOICE_CALL && index == 0)) ||
François Gaffied1ab2bd2015-12-02 18:20:06 +01002279 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002280 return BAD_VALUE;
2281 }
2282 if (!audio_is_output_device(device)) {
2283 return BAD_VALUE;
2284 }
2285
2286 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002287 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002288
Eric Laurent1fd372e2016-04-06 14:23:53 -07002289 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002290 stream, device, index);
2291
Eric Laurent28d09f02016-03-08 10:43:05 -08002292 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002293 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2294 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002295 continue;
2296 }
2297 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2298 }
Eric Laurente552edb2014-03-10 17:42:56 -07002299
Eric Laurent1fd372e2016-04-06 14:23:53 -07002300 // update volume on all outputs and streams matching the following:
2301 // - The requested stream (or a stream matching for volume control) is active on the output
2302 // - The device (or devices) selected by the strategy corresponding to this stream includes
2303 // the requested device
2304 // - For non default requested device, currently selected device on the output is either the
2305 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002306 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2307 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002308 status_t status = NO_ERROR;
2309 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002310 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2311 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08002312 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
Eric Laurent3839bc02018-07-10 18:33:34 -07002313 if (!(streamsMatchForvolume(stream, (audio_stream_type_t)curStream))) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002314 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002315 }
Eric Laurentdcd4ab12018-06-29 17:45:13 -07002316 if (!(desc->isStreamActive((audio_stream_type_t)curStream) || isInCall())) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002317 continue;
2318 }
Eric Laurent794fde22016-03-11 09:50:45 -08002319 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002320 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2321 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002322 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2323 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002324 continue;
2325 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002326 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002327 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002328 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07002329 applyVolume = (curDevice & curStreamDevice) != 0;
2330 } else {
2331 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002332 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002333 }
Eric Laurent3839bc02018-07-10 18:33:34 -07002334 // rescale index before applying to curStream as ranges may be different for
2335 // stream and curStream
2336 int idx = rescaleVolumeIndex(index, stream, (audio_stream_type_t)curStream);
Eric Laurente76f29c2016-09-14 17:17:53 -07002337 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002338 //FIXME: workaround for truncated touch sounds
2339 // delayed volume change for system stream to be removed when the problem is
2340 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002341 status_t volStatus =
Eric Laurent3839bc02018-07-10 18:33:34 -07002342 checkAndSetVolume((audio_stream_type_t)curStream, idx, desc, curDevice,
Eric Laurentdc462862016-07-19 12:29:53 -07002343 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002344 if (volStatus != NO_ERROR) {
2345 status = volStatus;
2346 }
2347 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002348 }
Eric Laurente552edb2014-03-10 17:42:56 -07002349 }
2350 return status;
2351}
2352
Eric Laurente0720872014-03-11 09:30:41 -07002353status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002354 int *index,
2355 audio_devices_t device)
2356{
2357 if (index == NULL) {
2358 return BAD_VALUE;
2359 }
2360 if (!audio_is_output_device(device)) {
2361 return BAD_VALUE;
2362 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002363 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002364 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002365 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002366 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2367 }
François Gaffiedfd74092015-03-19 12:10:59 +01002368 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002369
François Gaffied1ab2bd2015-12-02 18:20:06 +01002370 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002371 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2372 return NO_ERROR;
2373}
2374
Eric Laurent36829f92017-04-07 19:04:42 -07002375audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002376{
2377 // select one output among several suitable for global effects.
2378 // The priority is as follows:
2379 // 1: An offloaded output. If the effect ends up not being offloadable,
2380 // AudioFlinger will invalidate the track and the offloaded output
2381 // will be closed causing the effect to be moved to a PCM output.
2382 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002383 // 3: The primary output
2384 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002385
Eric Laurent3b73df72014-03-11 09:06:29 -07002386 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002387 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent36829f92017-04-07 19:04:42 -07002388 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002389
Eric Laurent36829f92017-04-07 19:04:42 -07002390 if (outputs.size() == 0) {
2391 return AUDIO_IO_HANDLE_NONE;
2392 }
Eric Laurente552edb2014-03-10 17:42:56 -07002393
Eric Laurent36829f92017-04-07 19:04:42 -07002394 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2395 bool activeOnly = true;
2396
2397 while (output == AUDIO_IO_HANDLE_NONE) {
2398 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2399 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2400 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2401
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002402 for (audio_io_handle_t output : outputs) {
2403 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002404 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2405 continue;
2406 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002407 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2408 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002409 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002410 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002411 }
2412 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002413 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002414 }
2415 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002416 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002417 }
2418 }
2419 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2420 output = outputOffloaded;
2421 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2422 output = outputDeepBuffer;
2423 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2424 output = outputPrimary;
2425 } else {
2426 output = outputs[0];
2427 }
2428 activeOnly = false;
2429 }
2430
2431 if (output != mMusicEffectOutput) {
2432 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2433 mMusicEffectOutput = output;
2434 }
2435
2436 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002437 return output;
2438}
2439
Eric Laurent36829f92017-04-07 19:04:42 -07002440audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2441{
2442 return selectOutputForMusicEffects();
2443}
2444
Eric Laurente0720872014-03-11 09:30:41 -07002445status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002446 audio_io_handle_t io,
2447 uint32_t strategy,
2448 int session,
2449 int id)
2450{
2451 ssize_t index = mOutputs.indexOfKey(io);
2452 if (index < 0) {
2453 index = mInputs.indexOfKey(io);
2454 if (index < 0) {
2455 ALOGW("registerEffect() unknown io %d", io);
2456 return INVALID_OPERATION;
2457 }
2458 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002459 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002460}
2461
Eric Laurentc75307b2015-03-17 15:29:32 -07002462bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2463{
Eric Laurent28d09f02016-03-08 10:43:05 -08002464 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002465 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2466 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002467 continue;
2468 }
2469 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2470 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002471 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002472}
2473
2474bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2475{
2476 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2477}
2478
Eric Laurente0720872014-03-11 09:30:41 -07002479bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002480{
2481 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002482 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002483 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002484 return true;
2485 }
2486 }
2487 return false;
2488}
2489
Eric Laurent275e8e92014-11-30 15:14:47 -08002490// Register a list of custom mixes with their attributes and format.
2491// When a mix is registered, corresponding input and output profiles are
2492// added to the remote submix hw module. The profile contains only the
2493// parameters (sampling rate, format...) specified by the mix.
2494// The corresponding input remote submix device is also connected.
2495//
2496// When a remote submix device is connected, the address is checked to select the
2497// appropriate profile and the corresponding input or output stream is opened.
2498//
2499// When capture starts, getInputForAttr() will:
2500// - 1 look for a mix matching the address passed in attribtutes tags if any
2501// - 2 if none found, getDeviceForInputSource() will:
2502// - 2.1 look for a mix matching the attributes source
2503// - 2.2 if none found, default to device selection by policy rules
2504// At this time, the corresponding output remote submix device is also connected
2505// and active playback use cases can be transferred to this mix if needed when reconnecting
2506// after AudioTracks are invalidated
2507//
2508// When playback starts, getOutputForAttr() will:
2509// - 1 look for a mix matching the address passed in attribtutes tags if any
2510// - 2 if none found, look for a mix matching the attributes usage
2511// - 3 if none found, default to device and output selection by policy rules.
2512
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002513status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002514{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002515 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2516 status_t res = NO_ERROR;
2517
2518 sp<HwModule> rSubmixModule;
2519 // examine each mix's route type
2520 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002521 AudioMix mix = mixes[i];
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002522 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
Eric Laurent97ac8712018-07-27 18:59:02 -07002523 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002524 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002525 break;
2526 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002527 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002528 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002529 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002530 rSubmixModule = mHwModules.getModuleFromName(
2531 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2532 if (rSubmixModule == 0) {
2533 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2534 i);
2535 res = INVALID_OPERATION;
2536 break;
2537 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002538 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002539
Eric Laurent97ac8712018-07-27 18:59:02 -07002540 String8 address = mix.mDeviceAddress;
2541 if (mix.mMixType == MIX_TYPE_PLAYERS) {
2542 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2543 } else {
2544 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
2545 }
François Gaffie036e1e92015-03-19 10:16:24 +01002546
Eric Laurent97ac8712018-07-27 18:59:02 -07002547 if (mPolicyMixes.registerMix(address, mix, 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002548 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002549 res = INVALID_OPERATION;
2550 break;
2551 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002552 audio_config_t outputConfig = mix.mFormat;
2553 audio_config_t inputConfig = mix.mFormat;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002554 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2555 // stereo and let audio flinger do the channel conversion if needed.
2556 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2557 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2558 rSubmixModule->addOutputProfile(address, &outputConfig,
2559 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2560 rSubmixModule->addInputProfile(address, &inputConfig,
2561 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002562
Eric Laurent97ac8712018-07-27 18:59:02 -07002563 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002564 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2565 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2566 address.string(), "remote-submix");
2567 } else {
2568 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2569 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2570 address.string(), "remote-submix");
2571 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002572 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2573 String8 address = mix.mDeviceAddress;
2574 audio_devices_t device = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002575 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2576 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002577
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002578 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002579 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2580 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2581 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2582 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2583 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2584 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002585 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2586 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002587 if (mPolicyMixes.registerMix(address, mix, desc) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002588 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002589 } else {
2590 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002591 }
2592 break;
2593 }
2594 }
2595
2596 if (res != NO_ERROR) {
2597 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002598 i, device, address.string());
2599 res = INVALID_OPERATION;
2600 break;
2601 } else if (!foundOutput) {
2602 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2603 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002604 res = INVALID_OPERATION;
2605 break;
2606 }
Eric Laurentc722f302014-12-10 11:21:49 -08002607 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002608 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002609 if (res != NO_ERROR) {
2610 unregisterPolicyMixes(mixes);
2611 }
2612 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002613}
2614
2615status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2616{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002617 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002618 status_t res = NO_ERROR;
2619 sp<HwModule> rSubmixModule;
2620 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002621 for (const auto& mix : mixes) {
2622 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002623
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002624 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002625 rSubmixModule = mHwModules.getModuleFromName(
2626 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2627 if (rSubmixModule == 0) {
2628 res = INVALID_OPERATION;
2629 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002630 }
2631 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002632
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002633 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002634
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002635 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2636 res = INVALID_OPERATION;
2637 continue;
2638 }
2639
2640 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2641 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2642 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2643 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2644 address.string(), "remote-submix");
2645 }
2646 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2647 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2648 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2649 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2650 address.string(), "remote-submix");
2651 }
2652 rSubmixModule->removeOutputProfile(address);
2653 rSubmixModule->removeInputProfile(address);
2654
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002655 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2656 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002657 res = INVALID_OPERATION;
2658 continue;
2659 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002660 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002661 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002662 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002663}
2664
Eric Laurente552edb2014-03-10 17:42:56 -07002665
Eric Laurente0720872014-03-11 09:30:41 -07002666status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002667{
Eric Laurente552edb2014-03-10 17:42:56 -07002668 String8 result;
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002669 result.appendFormat("\nAudioPolicyManager Dump: %p\n", this);
2670 result.appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07002671 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002672 std::string stateLiteral;
2673 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002674 result.appendFormat(" Phone state: %s\n", stateLiteral.c_str());
2675 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
2676 "communications", "media", "record", "dock", "system",
2677 "HDMI system audio", "encoded surround output", "vibrate ringing" };
2678 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
2679 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
2680 result.appendFormat(" Force use for %s: %d\n",
2681 forceUses[i], mEngine->getForceUse(i));
2682 }
2683 result.appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
2684 result.appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
2685 result.appendFormat(" Config source: %s\n", getConfig().getSource().c_str());
François Gaffie2110e042015-03-24 08:41:51 +01002686 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002687
François Gaffie112b0af2015-11-19 16:13:25 +01002688 mAvailableOutputDevices.dump(fd, String8("Available output"));
2689 mAvailableInputDevices.dump(fd, String8("Available input"));
Mikhail Naganovd4120142017-12-06 15:49:22 -08002690 mHwModulesAll.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002691 mOutputs.dump(fd);
2692 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002693 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002694 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002695 mAudioPatches.dump(fd);
Mikhail Naganov44344b02016-12-13 11:21:02 -08002696 mPolicyMixes.dump(fd);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07002697 mAudioSources.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002698
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002699 if (!mSurroundFormats.empty()) {
2700 result = String8("\nManually Enabled Surround Formats:\n");
2701 size_t i = 0;
2702 for (const auto& fmt : mSurroundFormats) {
2703 result.append(i++ == 0 ? " " : ", ");
2704 std::string sfmt;
2705 FormatConverter::toString(fmt, sfmt);
2706 result.appendFormat("%s", sfmt.c_str());
2707 }
2708 result.append("\n");
2709 write(fd, result.string(), result.size());
2710 }
2711
Eric Laurente552edb2014-03-10 17:42:56 -07002712 return NO_ERROR;
2713}
2714
2715// This function checks for the parameters which can be offloaded.
2716// This can be enhanced depending on the capability of the DSP and policy
2717// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002718bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002719{
2720 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002721 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002722 offloadInfo.sample_rate, offloadInfo.channel_mask,
2723 offloadInfo.format,
2724 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2725 offloadInfo.has_video);
2726
Andy Hung2ddee192015-12-18 17:34:44 -08002727 if (mMasterMono) {
2728 return false; // no offloading if mono is set.
2729 }
2730
Eric Laurente552edb2014-03-10 17:42:56 -07002731 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07002732 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
2733 ALOGV("offload disabled by audio.offload.disable");
2734 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002735 }
2736
2737 // Check if stream type is music, then only allow offload as of now.
2738 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2739 {
2740 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2741 return false;
2742 }
2743
2744 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002745 const bool allowOffloadWithVideo =
2746 property_get_bool("audio.offload.video", false /* default_value */);
2747 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002748 ALOGV("isOffloadSupported: has_video == true, returning false");
2749 return false;
2750 }
2751
2752 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07002753 const int min_duration_secs = property_get_int32(
2754 "audio.offload.min.duration.secs", -1 /* default_value */);
2755 if (min_duration_secs >= 0) {
2756 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
2757 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%d)",
2758 min_duration_secs);
Eric Laurente552edb2014-03-10 17:42:56 -07002759 return false;
2760 }
2761 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2762 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2763 return false;
2764 }
2765
2766 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2767 // creating an offloaded track and tearing it down immediately after start when audioflinger
2768 // detects there is an active non offloadable effect.
2769 // FIXME: We should check the audio session here but we do not have it in this context.
2770 // This may prevent offloading in rare situations where effects are left active by apps
2771 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002772 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002773 return false;
2774 }
2775
2776 // See if there is a profile to support this.
2777 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002778 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002779 offloadInfo.sample_rate,
2780 offloadInfo.format,
2781 offloadInfo.channel_mask,
2782 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002783 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2784 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002785}
2786
Eric Laurent6a94d692014-05-20 11:18:06 -07002787status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2788 audio_port_type_t type,
2789 unsigned int *num_ports,
2790 struct audio_port *ports,
2791 unsigned int *generation)
2792{
2793 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2794 generation == NULL) {
2795 return BAD_VALUE;
2796 }
2797 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2798 if (ports == NULL) {
2799 *num_ports = 0;
2800 }
2801
2802 size_t portsWritten = 0;
2803 size_t portsMax = *num_ports;
2804 *num_ports = 0;
2805 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002806 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2807 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002808 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002809 for (const auto& dev : mAvailableOutputDevices) {
2810 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002811 continue;
2812 }
2813 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002814 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002815 }
2816 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002817 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002818 }
2819 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002820 for (const auto& dev : mAvailableInputDevices) {
2821 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002822 continue;
2823 }
2824 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002825 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002826 }
2827 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002828 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002829 }
2830 }
2831 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2832 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2833 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2834 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2835 }
2836 *num_ports += mInputs.size();
2837 }
2838 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002839 size_t numOutputs = 0;
2840 for (size_t i = 0; i < mOutputs.size(); i++) {
2841 if (!mOutputs[i]->isDuplicated()) {
2842 numOutputs++;
2843 if (portsWritten < portsMax) {
2844 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2845 }
2846 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002847 }
Eric Laurent84c70242014-06-23 08:46:27 -07002848 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002849 }
2850 }
2851 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002852 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002853 return NO_ERROR;
2854}
2855
Eric Laurent99fcae42018-05-17 16:59:18 -07002856status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07002857{
Eric Laurent99fcae42018-05-17 16:59:18 -07002858 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
2859 return BAD_VALUE;
2860 }
2861 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
2862 if (dev != 0) {
2863 dev->toAudioPort(port);
2864 return NO_ERROR;
2865 }
2866 dev = mAvailableInputDevices.getDeviceFromId(port->id);
2867 if (dev != 0) {
2868 dev->toAudioPort(port);
2869 return NO_ERROR;
2870 }
2871 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
2872 if (out != 0) {
2873 out->toAudioPort(port);
2874 return NO_ERROR;
2875 }
2876 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
2877 if (in != 0) {
2878 in->toAudioPort(port);
2879 return NO_ERROR;
2880 }
2881 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002882}
2883
Eric Laurent6a94d692014-05-20 11:18:06 -07002884status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2885 audio_patch_handle_t *handle,
2886 uid_t uid)
2887{
2888 ALOGV("createAudioPatch()");
2889
2890 if (handle == NULL || patch == NULL) {
2891 return BAD_VALUE;
2892 }
2893 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2894
Mikhail Naganovac9858b2018-06-15 13:12:37 -07002895 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07002896 return BAD_VALUE;
2897 }
2898 // only one source per audio patch supported for now
2899 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002900 return INVALID_OPERATION;
2901 }
Eric Laurent874c42872014-08-08 15:13:39 -07002902
2903 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002904 return INVALID_OPERATION;
2905 }
Eric Laurent874c42872014-08-08 15:13:39 -07002906 for (size_t i = 0; i < patch->num_sinks; i++) {
2907 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2908 return INVALID_OPERATION;
2909 }
2910 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002911
2912 sp<AudioPatch> patchDesc;
2913 ssize_t index = mAudioPatches.indexOfKey(*handle);
2914
Eric Laurent6a94d692014-05-20 11:18:06 -07002915 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2916 patch->sources[0].role,
2917 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002918#if LOG_NDEBUG == 0
2919 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002920 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002921 patch->sinks[i].role,
2922 patch->sinks[i].type);
2923 }
2924#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002925
2926 if (index >= 0) {
2927 patchDesc = mAudioPatches.valueAt(index);
2928 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2929 mUidCached, patchDesc->mUid, uid);
2930 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2931 return INVALID_OPERATION;
2932 }
2933 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002934 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002935 }
2936
2937 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002938 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002939 if (outputDesc == NULL) {
2940 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2941 return BAD_VALUE;
2942 }
Eric Laurent84c70242014-06-23 08:46:27 -07002943 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2944 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002945 if (patchDesc != 0) {
2946 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2947 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2948 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2949 return BAD_VALUE;
2950 }
2951 }
Eric Laurent874c42872014-08-08 15:13:39 -07002952 DeviceVector devices;
2953 for (size_t i = 0; i < patch->num_sinks; i++) {
2954 // Only support mix to devices connection
2955 // TODO add support for mix to mix connection
2956 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2957 ALOGV("createAudioPatch() source mix but sink is not a device");
2958 return INVALID_OPERATION;
2959 }
2960 sp<DeviceDescriptor> devDesc =
2961 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2962 if (devDesc == 0) {
2963 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2964 return BAD_VALUE;
2965 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002966
François Gaffie53615e22015-03-19 09:24:12 +01002967 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002968 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002969 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002970 NULL, // updatedSamplingRate
2971 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002972 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002973 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002974 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002975 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002976 ALOGV("createAudioPatch() profile not supported for device %08x",
2977 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002978 return INVALID_OPERATION;
2979 }
2980 devices.add(devDesc);
2981 }
2982 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002983 return INVALID_OPERATION;
2984 }
Eric Laurent874c42872014-08-08 15:13:39 -07002985
Eric Laurent6a94d692014-05-20 11:18:06 -07002986 // TODO: reconfigure output format and channels here
2987 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002988 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002989 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002990 index = mAudioPatches.indexOfKey(*handle);
2991 if (index >= 0) {
2992 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2993 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2994 }
2995 patchDesc = mAudioPatches.valueAt(index);
2996 patchDesc->mUid = uid;
2997 ALOGV("createAudioPatch() success");
2998 } else {
2999 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
3000 return INVALID_OPERATION;
3001 }
3002 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3003 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3004 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003005 // only one sink supported when connecting an input device to a mix
3006 if (patch->num_sinks > 1) {
3007 return INVALID_OPERATION;
3008 }
François Gaffie53615e22015-03-19 09:24:12 +01003009 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003010 if (inputDesc == NULL) {
3011 return BAD_VALUE;
3012 }
3013 if (patchDesc != 0) {
3014 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3015 return BAD_VALUE;
3016 }
3017 }
3018 sp<DeviceDescriptor> devDesc =
3019 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
3020 if (devDesc == 0) {
3021 return BAD_VALUE;
3022 }
3023
François Gaffie53615e22015-03-19 09:24:12 +01003024 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08003025 devDesc->mAddress,
3026 patch->sinks[0].sample_rate,
3027 NULL, /*updatedSampleRate*/
3028 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003029 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003030 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003031 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003032 // FIXME for the parameter type,
3033 // and the NONE
3034 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003035 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003036 return INVALID_OPERATION;
3037 }
3038 // TODO: reconfigure output format and channels here
3039 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01003040 devDesc->type(), inputDesc->mIoHandle);
3041 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003042 index = mAudioPatches.indexOfKey(*handle);
3043 if (index >= 0) {
3044 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3045 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
3046 }
3047 patchDesc = mAudioPatches.valueAt(index);
3048 patchDesc->mUid = uid;
3049 ALOGV("createAudioPatch() success");
3050 } else {
3051 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
3052 return INVALID_OPERATION;
3053 }
3054 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3055 // device to device connection
3056 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003057 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003058 return BAD_VALUE;
3059 }
3060 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003061 sp<DeviceDescriptor> srcDeviceDesc =
3062 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07003063 if (srcDeviceDesc == 0) {
3064 return BAD_VALUE;
3065 }
Eric Laurent874c42872014-08-08 15:13:39 -07003066
Eric Laurent6a94d692014-05-20 11:18:06 -07003067 //update source and sink with our own data as the data passed in the patch may
3068 // be incomplete.
3069 struct audio_patch newPatch = *patch;
3070 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003071
Eric Laurent874c42872014-08-08 15:13:39 -07003072 for (size_t i = 0; i < patch->num_sinks; i++) {
3073 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3074 ALOGV("createAudioPatch() source device but one sink is not a device");
3075 return INVALID_OPERATION;
3076 }
3077
3078 sp<DeviceDescriptor> sinkDeviceDesc =
3079 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3080 if (sinkDeviceDesc == 0) {
3081 return BAD_VALUE;
3082 }
3083 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
3084
Eric Laurent3bcf8592015-04-03 12:13:24 -07003085 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003086 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003087 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08003088 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003089 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003090 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003091 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003092 return INVALID_OPERATION;
3093 }
Eric Laurent874c42872014-08-08 15:13:39 -07003094 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01003095 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003096 // if the sink device is reachable via an opened output stream, request to go via
3097 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07003098 audio_io_handle_t output = selectOutput(outputs,
3099 AUDIO_OUTPUT_FLAG_NONE,
3100 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07003101 if (output != AUDIO_IO_HANDLE_NONE) {
3102 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3103 if (outputDesc->isDuplicated()) {
3104 return INVALID_OPERATION;
3105 }
3106 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003107 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003108 newPatch.num_sources = 2;
3109 }
Eric Laurent83b88082014-06-20 18:31:16 -07003110 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003111 }
3112 // TODO: check from routing capabilities in config file and other conflicting patches
3113
Mikhail Naganovdc769682018-05-04 15:34:08 -07003114 status_t status = installPatch(__func__, index, handle, &newPatch, 0, uid, &patchDesc);
3115 if (status != NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003116 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3117 status);
3118 return INVALID_OPERATION;
3119 }
3120 } else {
3121 return BAD_VALUE;
3122 }
3123 } else {
3124 return BAD_VALUE;
3125 }
3126 return NO_ERROR;
3127}
3128
3129status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3130 uid_t uid)
3131{
3132 ALOGV("releaseAudioPatch() patch %d", handle);
3133
3134 ssize_t index = mAudioPatches.indexOfKey(handle);
3135
3136 if (index < 0) {
3137 return BAD_VALUE;
3138 }
3139 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3140 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3141 mUidCached, patchDesc->mUid, uid);
3142 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3143 return INVALID_OPERATION;
3144 }
3145
3146 struct audio_patch *patch = &patchDesc->mPatch;
3147 patchDesc->mUid = mUidCached;
3148 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003149 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003150 if (outputDesc == NULL) {
3151 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3152 return BAD_VALUE;
3153 }
3154
Eric Laurentc75307b2015-03-17 15:29:32 -07003155 setOutputDevice(outputDesc,
3156 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07003157 true,
3158 0,
3159 NULL);
3160 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3161 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003162 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003163 if (inputDesc == NULL) {
3164 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3165 return BAD_VALUE;
3166 }
3167 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003168 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003169 true,
3170 NULL);
3171 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003172 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3173 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3174 status, patchDesc->mAfPatchHandle);
3175 removeAudioPatch(patchDesc->mHandle);
3176 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003177 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003178 } else {
3179 return BAD_VALUE;
3180 }
3181 } else {
3182 return BAD_VALUE;
3183 }
3184 return NO_ERROR;
3185}
3186
3187status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3188 struct audio_patch *patches,
3189 unsigned int *generation)
3190{
François Gaffie53615e22015-03-19 09:24:12 +01003191 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003192 return BAD_VALUE;
3193 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003194 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003195 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003196}
3197
Eric Laurente1715a42014-05-20 11:30:42 -07003198status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003199{
Eric Laurente1715a42014-05-20 11:30:42 -07003200 ALOGV("setAudioPortConfig()");
3201
3202 if (config == NULL) {
3203 return BAD_VALUE;
3204 }
3205 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3206 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003207 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3208 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003209 }
3210
Eric Laurenta121f902014-06-03 13:32:54 -07003211 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003212 if (config->type == AUDIO_PORT_TYPE_MIX) {
3213 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003214 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003215 if (outputDesc == NULL) {
3216 return BAD_VALUE;
3217 }
Eric Laurent84c70242014-06-23 08:46:27 -07003218 ALOG_ASSERT(!outputDesc->isDuplicated(),
3219 "setAudioPortConfig() called on duplicated output %d",
3220 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003221 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003222 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003223 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003224 if (inputDesc == NULL) {
3225 return BAD_VALUE;
3226 }
Eric Laurenta121f902014-06-03 13:32:54 -07003227 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003228 } else {
3229 return BAD_VALUE;
3230 }
3231 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3232 sp<DeviceDescriptor> deviceDesc;
3233 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3234 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3235 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3236 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3237 } else {
3238 return BAD_VALUE;
3239 }
3240 if (deviceDesc == NULL) {
3241 return BAD_VALUE;
3242 }
Eric Laurenta121f902014-06-03 13:32:54 -07003243 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003244 } else {
3245 return BAD_VALUE;
3246 }
3247
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003248 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003249 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3250 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003251 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003252 audioPortConfig->toAudioPortConfig(&newConfig, config);
3253 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003254 }
Eric Laurenta121f902014-06-03 13:32:54 -07003255 if (status != NO_ERROR) {
3256 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003257 }
Eric Laurente1715a42014-05-20 11:30:42 -07003258
3259 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003260}
3261
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003262void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3263{
Eric Laurentd60560a2015-04-10 11:31:20 -07003264 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003265 clearAudioPatches(uid);
3266 clearSessionRoutes(uid);
3267}
3268
Eric Laurent6a94d692014-05-20 11:18:06 -07003269void AudioPolicyManager::clearAudioPatches(uid_t uid)
3270{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003271 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003272 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3273 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003274 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003275 }
3276 }
3277}
3278
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003279void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3280 audio_io_handle_t ouptutToSkip)
3281{
3282 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3283 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3284 for (size_t j = 0; j < mOutputs.size(); j++) {
3285 if (mOutputs.keyAt(j) == ouptutToSkip) {
3286 continue;
3287 }
3288 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3289 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3290 continue;
3291 }
3292 // If the default device for this strategy is on another output mix,
3293 // invalidate all tracks in this strategy to force re connection.
3294 // Otherwise select new device on the output mix.
3295 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003296 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003297 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3298 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3299 }
3300 }
3301 } else {
3302 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3303 setOutputDevice(outputDesc, newDevice, false);
3304 }
3305 }
3306}
3307
3308void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3309{
3310 // remove output routes associated with this uid
3311 SortedVector<routing_strategy> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07003312 for (size_t i = 0; i < mOutputs.size(); i++) {
3313 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3314 TrackClientMap clients = outputDesc->clientsMap();
3315 for (const auto& client : clients) {
3316 if (client.second->hasPreferredDevice() && client.second->uid() == uid) {
3317 client.second->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3318 affectedStrategies.add(getStrategy(client.second->stream()));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003319 }
3320 }
3321 }
3322 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003323 for (const auto& strategy : affectedStrategies) {
3324 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003325 }
3326
3327 // remove input routes associated with this uid
3328 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07003329 for (size_t i = 0; i < mInputs.size(); i++) {
3330 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
3331 RecordClientMap clients = inputDesc->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 affectedSources.add(client.second->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003336 }
3337 }
3338 }
3339 // reroute inputs if necessary
3340 SortedVector<audio_io_handle_t> inputsToClose;
3341 for (size_t i = 0; i < mInputs.size(); i++) {
3342 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003343 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003344 inputsToClose.add(inputDesc->mIoHandle);
3345 }
3346 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003347 for (const auto& input : inputsToClose) {
3348 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003349 }
3350}
3351
Eric Laurentd60560a2015-04-10 11:31:20 -07003352void AudioPolicyManager::clearAudioSources(uid_t uid)
3353{
3354 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003355 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3356 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07003357 stopAudioSource(mAudioSources.keyAt(i));
3358 }
3359 }
3360}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003361
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003362status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3363 audio_io_handle_t *ioHandle,
3364 audio_devices_t *device)
3365{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003366 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3367 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003368 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003369
François Gaffiedf372692015-03-19 10:43:27 +01003370 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003371}
3372
Eric Laurentd60560a2015-04-10 11:31:20 -07003373status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003374 const audio_attributes_t *attributes,
3375 audio_port_handle_t *portId,
3376 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003377{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003378 ALOGV("%s", __FUNCTION__);
3379 *portId = AUDIO_PORT_HANDLE_NONE;
3380
3381 if (source == NULL || attributes == NULL || portId == NULL) {
3382 ALOGW("%s invalid argument: source %p attributes %p handle %p",
3383 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003384 return BAD_VALUE;
3385 }
3386
Eric Laurentd60560a2015-04-10 11:31:20 -07003387 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3388 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003389 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
3390 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003391 return INVALID_OPERATION;
3392 }
3393
3394 sp<DeviceDescriptor> srcDeviceDesc =
3395 mAvailableInputDevices.getDevice(source->ext.device.type,
3396 String8(source->ext.device.address));
3397 if (srcDeviceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003398 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003399 return BAD_VALUE;
3400 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003401
3402 *portId = AudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07003403
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003404 struct audio_patch dummyPatch = {};
Eric Laurentd60560a2015-04-10 11:31:20 -07003405 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003406
3407 sp<SourceClientDescriptor> sourceDesc =
3408 new SourceClientDescriptor(*portId, uid, *attributes, patchDesc, srcDeviceDesc,
Eric Laurent97ac8712018-07-27 18:59:02 -07003409 streamTypefromAttributesInt(attributes),
3410 getStrategyForAttr(attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07003411
3412 status_t status = connectAudioSource(sourceDesc);
3413 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003414 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003415 }
3416 return status;
3417}
3418
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003419status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003420{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003421 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003422
3423 // make sure we only have one patch per source.
3424 disconnectAudioSource(sourceDesc);
3425
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003426 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003427 routing_strategy strategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003428 audio_stream_type_t stream = sourceDesc->stream();
3429 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->srcDevice();
Eric Laurentd60560a2015-04-10 11:31:20 -07003430
3431 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3432 sp<DeviceDescriptor> sinkDeviceDesc =
3433 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3434
3435 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003436
3437 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3438 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003439 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003440 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3441 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3442 // create patch between src device and output device
3443 // create Hwoutput and add to mHwOutputs
3444 } else {
3445 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3446 audio_io_handle_t output =
3447 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3448 if (output == AUDIO_IO_HANDLE_NONE) {
3449 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3450 return INVALID_OPERATION;
3451 }
3452 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3453 if (outputDesc->isDuplicated()) {
3454 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3455 return INVALID_OPERATION;
3456 }
Eric Laurent733ce942017-12-07 12:18:25 -08003457 status_t status = outputDesc->start();
3458 if (status != NO_ERROR) {
3459 return status;
3460 }
3461
Eric Laurentd60560a2015-04-10 11:31:20 -07003462 // create a special patch with no sink and two sources:
3463 // - the second source indicates to PatchPanel through which output mix this patch should
3464 // be connected as well as the stream type for volume control
3465 // - the sink is defined by whatever output device is currently selected for the output
3466 // though which this patch is routed.
Mikhail Naganovdc769682018-05-04 15:34:08 -07003467 PatchBuilder patchBuilder;
3468 patchBuilder.addSource(srcDeviceDesc).addSource(outputDesc, { .stream = stream });
3469 status = mpClientInterface->createAudioPatch(patchBuilder.patch(),
Eric Laurentd60560a2015-04-10 11:31:20 -07003470 &afPatchHandle,
3471 0);
3472 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3473 status, afPatchHandle);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003474 sourceDesc->patchDesc()->mPatch = *patchBuilder.patch();
Eric Laurentd60560a2015-04-10 11:31:20 -07003475 if (status != NO_ERROR) {
3476 ALOGW("%s patch panel could not connect device patch, error %d",
3477 __FUNCTION__, status);
3478 return INVALID_OPERATION;
3479 }
3480 uint32_t delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07003481 status = startSource(outputDesc, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003482
3483 if (status != NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003484 mpClientInterface->releaseAudioPatch(sourceDesc->patchDesc()->mAfPatchHandle, 0);
Eric Laurentd60560a2015-04-10 11:31:20 -07003485 return status;
3486 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003487 sourceDesc->setSwOutput(outputDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003488 if (delayMs != 0) {
3489 usleep(delayMs * 1000);
3490 }
3491 }
3492
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003493 sourceDesc->patchDesc()->mAfPatchHandle = afPatchHandle;
3494 addAudioPatch(sourceDesc->patchDesc()->mHandle, sourceDesc->patchDesc());
Eric Laurentd60560a2015-04-10 11:31:20 -07003495
3496 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003497}
3498
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003499status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07003500{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003501 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
3502 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003503 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003504 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003505 return BAD_VALUE;
3506 }
3507 status_t status = disconnectAudioSource(sourceDesc);
3508
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003509 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003510 return status;
3511}
3512
Andy Hung2ddee192015-12-18 17:34:44 -08003513status_t AudioPolicyManager::setMasterMono(bool mono)
3514{
3515 if (mMasterMono == mono) {
3516 return NO_ERROR;
3517 }
3518 mMasterMono = mono;
3519 // if enabling mono we close all offloaded devices, which will invalidate the
3520 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3521 // for recreating the new AudioTrack as non-offloaded PCM.
3522 //
3523 // If disabling mono, we leave all tracks as is: we don't know which clients
3524 // and tracks are able to be recreated as offloaded. The next "song" should
3525 // play back offloaded.
3526 if (mMasterMono) {
3527 Vector<audio_io_handle_t> offloaded;
3528 for (size_t i = 0; i < mOutputs.size(); ++i) {
3529 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3530 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3531 offloaded.push(desc->mIoHandle);
3532 }
3533 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003534 for (const auto& handle : offloaded) {
3535 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003536 }
3537 }
3538 // update master mono for all remaining outputs
3539 for (size_t i = 0; i < mOutputs.size(); ++i) {
3540 updateMono(mOutputs.keyAt(i));
3541 }
3542 return NO_ERROR;
3543}
3544
3545status_t AudioPolicyManager::getMasterMono(bool *mono)
3546{
3547 *mono = mMasterMono;
3548 return NO_ERROR;
3549}
3550
Eric Laurentac9cef52017-06-09 15:46:26 -07003551float AudioPolicyManager::getStreamVolumeDB(
3552 audio_stream_type_t stream, int index, audio_devices_t device)
3553{
3554 return computeVolume(stream, index, device);
3555}
3556
jiabin81772902018-04-02 17:52:27 -07003557status_t AudioPolicyManager::getSupportedFormats(audio_io_handle_t ioHandle,
3558 FormatVector& formats) {
3559 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
3560 return BAD_VALUE;
3561 }
3562 String8 reply;
3563 reply = mpClientInterface->getParameters(
3564 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
3565 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
3566 AudioParameter repliedParameters(reply);
3567 if (repliedParameters.get(
3568 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
3569 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
3570 return BAD_VALUE;
3571 }
3572 for (auto format : formatsFromString(reply.string())) {
3573 // Only AUDIO_FORMAT_AAC_LC will be used in Settings UI for all AAC formats.
3574 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3575 if (format == AAC_FORMATS[i]) {
3576 format = AUDIO_FORMAT_AAC_LC;
3577 break;
3578 }
3579 }
3580 bool exist = false;
3581 for (size_t i = 0; i < formats.size(); i++) {
3582 if (format == formats[i]) {
3583 exist = true;
3584 break;
3585 }
3586 }
3587 bool isSurroundFormat = false;
3588 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3589 if (SURROUND_FORMATS[i] == format) {
3590 isSurroundFormat = true;
3591 break;
3592 }
3593 }
3594 if (!exist && isSurroundFormat) {
3595 formats.add(format);
3596 }
3597 }
3598 return NO_ERROR;
3599}
3600
3601status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3602 audio_format_t *surroundFormats,
3603 bool *surroundFormatsEnabled,
3604 bool reported)
3605{
3606 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3607 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3608 return BAD_VALUE;
3609 }
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003610 ALOGV("getSurroundFormats() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p"
3611 " reported %d", *numSurroundFormats, surroundFormats, surroundFormatsEnabled, reported);
jiabin81772902018-04-02 17:52:27 -07003612
3613 // Only return value if there is HDMI output.
3614 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3615 return INVALID_OPERATION;
3616 }
3617
3618 size_t formatsWritten = 0;
3619 size_t formatsMax = *numSurroundFormats;
3620 *numSurroundFormats = 0;
3621 FormatVector formats;
3622 if (reported) {
3623 // Only get surround formats which are reported by device.
3624 // First list already open outputs that can be routed to this device
3625 audio_devices_t device = AUDIO_DEVICE_OUT_HDMI;
3626 SortedVector<audio_io_handle_t> outputs;
3627 bool reportedFormatFound = false;
3628 status_t status;
3629 sp<SwAudioOutputDescriptor> desc;
3630 for (size_t i = 0; i < mOutputs.size(); i++) {
3631 desc = mOutputs.valueAt(i);
3632 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
3633 outputs.add(mOutputs.keyAt(i));
3634 }
3635 }
3636 // Open an output to query dynamic parameters.
Mikhail Naganov708e0382018-05-30 09:53:04 -07003637 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003638 AUDIO_DEVICE_OUT_HDMI);
3639 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3640 String8 address = hdmiOutputDevices[i]->mAddress;
3641 for (const auto& hwModule : mHwModules) {
3642 for (size_t i = 0; i < hwModule->getOutputProfiles().size(); i++) {
3643 sp<IOProfile> profile = hwModule->getOutputProfiles()[i];
3644 if (profile->supportDevice(AUDIO_DEVICE_OUT_HDMI) &&
3645 profile->supportDeviceAddress(address)) {
3646 size_t j;
3647 for (j = 0; j < outputs.size(); j++) {
3648 desc = mOutputs.valueFor(outputs.itemAt(j));
3649 if (!desc->isDuplicated() && desc->mProfile == profile) {
3650 break;
3651 }
3652 }
3653 if (j != outputs.size()) {
3654 status = getSupportedFormats(outputs.itemAt(j), formats);
3655 reportedFormatFound |= (status == NO_ERROR);
3656 continue;
3657 }
3658
3659 if (!profile->canOpenNewIo()) {
3660 ALOGW("Max Output number %u already opened for this profile %s",
3661 profile->maxOpenCount, profile->getTagName().c_str());
3662 continue;
3663 }
3664
3665 ALOGV("opening output for device %08x with params %s profile %p name %s",
3666 device, address.string(), profile.get(), profile->getName().string());
3667 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
3668 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3669 status_t status = desc->open(nullptr, device, address,
3670 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE,
3671 &output);
3672
3673 if (status == NO_ERROR) {
3674 status = getSupportedFormats(output, formats);
3675 reportedFormatFound |= (status == NO_ERROR);
3676 desc->close();
3677 output = AUDIO_IO_HANDLE_NONE;
3678 }
3679 }
3680 }
3681 }
3682 }
3683
3684 if (!reportedFormatFound) {
3685 return UNKNOWN_ERROR;
3686 }
3687 } else {
3688 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3689 formats.add(SURROUND_FORMATS[i]);
3690 }
3691 }
3692 for (size_t i = 0; i < formats.size(); i++) {
3693 if (formatsWritten < formatsMax) {
3694 surroundFormats[formatsWritten] = formats[i];
3695 bool formatEnabled = false;
3696 if (formats[i] == AUDIO_FORMAT_AAC_LC) {
3697 for (size_t j = 0; j < ARRAY_SIZE(AAC_FORMATS); j++) {
3698 formatEnabled =
3699 mSurroundFormats.find(AAC_FORMATS[i]) != mSurroundFormats.end();
3700 break;
3701 }
3702 } else {
3703 formatEnabled = mSurroundFormats.find(formats[i]) != mSurroundFormats.end();
3704 }
3705 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3706 }
3707 (*numSurroundFormats)++;
3708 }
3709 return NO_ERROR;
3710}
3711
3712status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3713{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003714 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
jiabin81772902018-04-02 17:52:27 -07003715 // Check if audio format is a surround formats.
3716 bool isSurroundFormat = false;
3717 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3718 if (audioFormat == SURROUND_FORMATS[i]) {
3719 isSurroundFormat = true;
3720 break;
3721 }
3722 }
3723 if (!isSurroundFormat) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003724 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07003725 return BAD_VALUE;
3726 }
3727
3728 // Should only be called when MANUAL.
3729 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3730 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
3731 if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003732 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07003733 return INVALID_OPERATION;
3734 }
3735
3736 if ((mSurroundFormats.find(audioFormat) != mSurroundFormats.end() && enabled)
3737 || (mSurroundFormats.find(audioFormat) == mSurroundFormats.end() && !enabled)) {
3738 return NO_ERROR;
3739 }
3740
3741 // The operation is valid only when there is HDMI output available.
3742 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003743 ALOGW("%s() no HDMI out devices found", __func__);
jiabin81772902018-04-02 17:52:27 -07003744 return INVALID_OPERATION;
3745 }
3746
3747 if (enabled) {
3748 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3749 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3750 mSurroundFormats.insert(AAC_FORMATS[i]);
3751 }
3752 } else {
3753 mSurroundFormats.insert(audioFormat);
3754 }
3755 } else {
3756 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3757 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3758 mSurroundFormats.erase(AAC_FORMATS[i]);
3759 }
3760 } else {
3761 mSurroundFormats.erase(audioFormat);
3762 }
3763 }
3764
3765 sp<SwAudioOutputDescriptor> outputDesc;
3766 bool profileUpdated = false;
Mikhail Naganov708e0382018-05-30 09:53:04 -07003767 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003768 AUDIO_DEVICE_OUT_HDMI);
3769 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3770 // Simulate reconnection to update enabled surround sound formats.
3771 String8 address = hdmiOutputDevices[i]->mAddress;
3772 String8 name = hdmiOutputDevices[i]->getName();
3773 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3774 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3775 address.c_str(),
3776 name.c_str());
3777 if (status != NO_ERROR) {
3778 continue;
3779 }
3780 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3781 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3782 address.c_str(),
3783 name.c_str());
3784 profileUpdated |= (status == NO_ERROR);
3785 }
Mikhail Naganov708e0382018-05-30 09:53:04 -07003786 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003787 AUDIO_DEVICE_IN_HDMI);
3788 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3789 // Simulate reconnection to update enabled surround sound formats.
3790 String8 address = hdmiInputDevices[i]->mAddress;
3791 String8 name = hdmiInputDevices[i]->getName();
3792 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3793 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3794 address.c_str(),
3795 name.c_str());
3796 if (status != NO_ERROR) {
3797 continue;
3798 }
3799 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3800 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3801 address.c_str(),
3802 name.c_str());
3803 profileUpdated |= (status == NO_ERROR);
3804 }
3805
3806 // Undo the surround formats change due to no audio profiles updated.
3807 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003808 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
jiabin81772902018-04-02 17:52:27 -07003809 if (enabled) {
3810 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3811 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3812 mSurroundFormats.erase(AAC_FORMATS[i]);
3813 }
3814 } else {
3815 mSurroundFormats.erase(audioFormat);
3816 }
3817 } else {
3818 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3819 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3820 mSurroundFormats.insert(AAC_FORMATS[i]);
3821 }
3822 } else {
3823 mSurroundFormats.insert(audioFormat);
3824 }
3825 }
3826 }
3827
3828 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3829}
3830
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003831void AudioPolicyManager::setRecordSilenced(uid_t uid, bool silenced)
3832{
3833 ALOGV("AudioPolicyManager:setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
3834
3835 Vector<sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
3836 for (size_t i = 0; i < activeInputs.size(); i++) {
3837 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
Eric Laurent8f42ea12018-08-08 09:08:25 -07003838 RecordClientVector clients = activeDesc->clientsList(true /*activeOnly*/);
3839 for (const auto& client : clients) {
3840 if (uid == client->uid()) {
3841 client->setSilenced(silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003842 }
3843 }
3844 }
3845}
3846
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003847status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003848{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003849 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003850
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003851 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003852 if (patchDesc == 0) {
3853 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003854 sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003855 return BAD_VALUE;
3856 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003857 removeAudioPatch(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003858
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003859 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003860 if (swOutputDesc != 0) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003861 status_t status = stopSource(swOutputDesc, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08003862 if (status == NO_ERROR) {
3863 swOutputDesc->stop();
3864 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003865 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3866 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003867 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003868 if (hwOutputDesc != 0) {
3869 // release patch between src device and output device
3870 // close Hwoutput and remove from mHwOutputs
3871 } else {
3872 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3873 }
3874 }
3875 return NO_ERROR;
3876}
3877
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003878sp<SourceClientDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
Eric Laurentd60560a2015-04-10 11:31:20 -07003879 audio_io_handle_t output, routing_strategy strategy)
3880{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003881 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07003882 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003883 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3884 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003885 routing_strategy sourceStrategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003886 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003887 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3888 source = sourceDesc;
3889 break;
3890 }
3891 }
3892 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003893}
3894
Eric Laurente552edb2014-03-10 17:42:56 -07003895// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003896// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003897// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003898uint32_t AudioPolicyManager::nextAudioPortGeneration()
3899{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003900 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003901}
3902
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003903#ifdef USE_XML_AUDIO_POLICY_CONF
3904// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3905static const char *kConfigLocationList[] =
3906 {"/odm/etc", "/vendor/etc", "/system/etc"};
3907static const int kConfigLocationListSize =
3908 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3909
3910static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3911 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07003912 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003913 status_t ret;
3914
Petri Gyntherf497f292018-04-17 18:46:10 -07003915 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
3916 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
3917 // A2DP offload supported but disabled: try to use special XML file
3918 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
3919 }
3920 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3921
3922 for (const char* fileName : fileNames) {
3923 for (int i = 0; i < kConfigLocationListSize; i++) {
Petri Gyntherf497f292018-04-17 18:46:10 -07003924 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
3925 "%s/%s", kConfigLocationList[i], fileName);
Mikhail Naganova289aea2018-09-17 15:26:23 -07003926 ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile, &config);
Petri Gyntherf497f292018-04-17 18:46:10 -07003927 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003928 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07003929 return ret;
3930 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003931 }
3932 }
3933 return ret;
3934}
3935#endif
3936
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003937AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
3938 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07003939 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07003940 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003941 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07003942 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003943 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003944#ifdef USE_XML_AUDIO_POLICY_CONF
3945 mVolumeCurves(new VolumeCurvesCollection()),
3946 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08003947 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003948#else
3949 mVolumeCurves(new StreamDescriptorCollection()),
3950 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
3951 mDefaultOutputDevice),
3952#endif
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003953 mAudioPortGeneration(1),
3954 mBeaconMuteRefCount(0),
3955 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003956 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003957 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003958 mMasterMono(false),
Chris Thornton2b864642017-06-27 21:26:07 -07003959 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE),
3960 mHasComputedSoundTriggerSupportsConcurrentCapture(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003961{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003962}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003963
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003964AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
3965 : AudioPolicyManager(clientInterface, false /*forTesting*/)
3966{
3967 loadConfig();
3968 initialize();
3969}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003970
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003971void AudioPolicyManager::loadConfig() {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003972#ifdef USE_XML_AUDIO_POLICY_CONF
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003973 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003974#else
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003975 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, getConfig()) != NO_ERROR)
3976 && (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, getConfig()) != NO_ERROR)) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003977#endif
3978 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003979 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01003980 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003981}
3982
3983status_t AudioPolicyManager::initialize() {
3984 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01003985
3986 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003987 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3988 if (!engineInstance) {
3989 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003990 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003991 }
3992 // Retrieve the Policy Manager Interface
3993 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3994 if (mEngine == NULL) {
3995 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003996 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003997 }
3998 mEngine->setObserver(this);
3999 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004000 if (status != NO_ERROR) {
4001 LOG_FATAL("Policy engine not initialized(err=%d)", status);
4002 return status;
4003 }
François Gaffie2110e042015-03-24 08:41:51 +01004004
Eric Laurent3a4311c2014-03-17 12:00:47 -07004005 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07004006 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07004007 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
4008 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Mikhail Naganovd4120142017-12-06 15:49:22 -08004009 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004010 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08004011 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
4012 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07004013 continue;
4014 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08004015 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07004016 // open all output streams needed to access attached devices
4017 // except for direct output streams that are only opened when they are actually
4018 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07004019 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004020 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004021 if (!outProfile->canOpenNewIo()) {
4022 ALOGE("Invalid Output profile max open count %u for profile %s",
4023 outProfile->maxOpenCount, outProfile->getTagName().c_str());
4024 continue;
4025 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004026 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004027 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004028 continue;
4029 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004030 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004031 mTtsOutputAvailable = true;
4032 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004033
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004034 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07004035 continue;
4036 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004037 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01004038 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
4039 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07004040 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004041 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07004042 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004043 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07004044 }
Eric Laurentd78f1532014-09-16 16:38:20 -07004045 if ((profileType & outputDeviceTypes) == 0) {
4046 continue;
4047 }
Eric Laurentc75307b2015-03-17 15:29:32 -07004048 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
4049 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07004050 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov708e0382018-05-30 09:53:04 -07004051 const DeviceVector &devicesForType = supportedDevices.getDevicesFromTypeMask(
4052 profileType);
Eric Laurentc40d9692016-04-13 19:14:13 -07004053 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
4054 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07004055 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004056 status_t status = outputDesc->open(nullptr, profileType, address,
4057 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07004058
4059 if (status != NO_ERROR) {
4060 ALOGW("Cannot open output stream for device %08x on hw module %s",
4061 outputDesc->mDevice,
Mikhail Naganovd4120142017-12-06 15:49:22 -08004062 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07004063 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004064 for (const auto& dev : supportedDevices) {
4065 ssize_t index = mAvailableOutputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07004066 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08004067 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004068 mAvailableOutputDevices[index]->attach(hwModule);
Eric Laurentd78f1532014-09-16 16:38:20 -07004069 }
4070 }
4071 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004072 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004073 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07004074 }
4075 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07004076 setOutputDevice(outputDesc,
Eric Laurentfe231122017-11-17 17:48:06 -08004077 profileType,
Eric Laurentc40d9692016-04-13 19:14:13 -07004078 true,
4079 0,
4080 NULL,
Eric Laurentfe231122017-11-17 17:48:06 -08004081 address);
Eric Laurentd78f1532014-09-16 16:38:20 -07004082 }
Eric Laurente552edb2014-03-10 17:42:56 -07004083 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004084 // open input streams needed to access attached devices to validate
4085 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004086 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004087 if (!inProfile->canOpenNewIo()) {
4088 ALOGE("Invalid Input profile max open count %u for profile %s",
4089 inProfile->maxOpenCount, inProfile->getTagName().c_str());
4090 continue;
4091 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004092 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004093 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004094 continue;
4095 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004096 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07004097 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004098 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
4099
Eric Laurentd78f1532014-09-16 16:38:20 -07004100 if ((profileType & inputDeviceTypes) == 0) {
4101 continue;
4102 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08004103 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08004104 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004105
Mikhail Naganov708e0382018-05-30 09:53:04 -07004106 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(profileType);
Eric Laurent53b810e2017-12-10 17:25:10 -08004107 // the inputs vector must be of size >= 1, but we don't want to crash here
4108 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
4109 : String8("");
4110 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
4111 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
4112
Eric Laurentd78f1532014-09-16 16:38:20 -07004113 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004114 status_t status = inputDesc->open(nullptr,
4115 profileType,
Eric Laurent53b810e2017-12-10 17:25:10 -08004116 address,
Eric Laurentfe231122017-11-17 17:48:06 -08004117 AUDIO_SOURCE_MIC,
4118 AUDIO_INPUT_FLAG_NONE,
4119 &input);
Eric Laurentd78f1532014-09-16 16:38:20 -07004120
4121 if (status == NO_ERROR) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004122 for (const auto& dev : inProfile->getSupportedDevices()) {
4123 ssize_t index = mAvailableInputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07004124 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07004125 if (index >= 0) {
4126 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
4127 if (!devDesc->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004128 devDesc->attach(hwModule);
Eric Laurent83efe1c2017-07-09 16:51:08 -07004129 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07004130 }
Eric Laurentd78f1532014-09-16 16:38:20 -07004131 }
4132 }
Eric Laurentfe231122017-11-17 17:48:06 -08004133 inputDesc->close();
Eric Laurentd78f1532014-09-16 16:38:20 -07004134 } else {
4135 ALOGW("Cannot open input stream for device %08x on hw module %s",
Eric Laurentfe231122017-11-17 17:48:06 -08004136 profileType,
Mikhail Naganovd4120142017-12-06 15:49:22 -08004137 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07004138 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004139 }
4140 }
4141 // make sure all attached devices have been allocated a unique ID
4142 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004143 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004144 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004145 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
4146 continue;
4147 }
François Gaffie2110e042015-03-24 08:41:51 +01004148 // The device is now validated and can be appended to the available devices of the engine
4149 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
4150 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004151 i++;
4152 }
4153 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004154 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01004155 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004156 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
4157 continue;
4158 }
François Gaffie2110e042015-03-24 08:41:51 +01004159 // The device is now validated and can be appended to the available devices of the engine
4160 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
4161 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004162 i++;
4163 }
4164 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004165 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01004166 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004167 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004168 }
jiabin9ff780e2018-03-19 18:19:52 -07004169 // If microphones address is empty, set it according to device type
4170 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
4171 if (mAvailableInputDevices[i]->mAddress.isEmpty()) {
4172 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
4173 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
4174 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
4175 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BACK_MICROPHONE_ADDRESS);
4176 }
4177 }
4178 }
Eric Laurente552edb2014-03-10 17:42:56 -07004179
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004180 if (mPrimaryOutput == 0) {
4181 ALOGE("Failed to open primary output");
4182 status = NO_INIT;
4183 }
Eric Laurente552edb2014-03-10 17:42:56 -07004184
4185 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004186 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004187}
4188
Eric Laurente0720872014-03-11 09:30:41 -07004189AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004190{
Eric Laurente552edb2014-03-10 17:42:56 -07004191 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004192 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004193 }
4194 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004195 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004196 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004197 mAvailableOutputDevices.clear();
4198 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004199 mOutputs.clear();
4200 mInputs.clear();
4201 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004202 mHwModulesAll.clear();
jiabin81772902018-04-02 17:52:27 -07004203 mSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004204}
4205
Eric Laurente0720872014-03-11 09:30:41 -07004206status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004207{
Eric Laurent87ffa392015-05-22 10:32:38 -07004208 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004209}
4210
Eric Laurente552edb2014-03-10 17:42:56 -07004211// ---
4212
Eric Laurent98e38192018-02-15 18:31:53 -08004213void AudioPolicyManager::addOutput(audio_io_handle_t output,
4214 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004215{
Eric Laurent1c333e22014-05-20 10:48:17 -07004216 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08004217 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004218 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004219 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004220 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004221}
4222
François Gaffie53615e22015-03-19 09:24:12 +01004223void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4224{
4225 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004226 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004227}
4228
Eric Laurent98e38192018-02-15 18:31:53 -08004229void AudioPolicyManager::addInput(audio_io_handle_t input,
4230 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004231{
Eric Laurent1c333e22014-05-20 10:48:17 -07004232 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004233 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004234}
Eric Laurente552edb2014-03-10 17:42:56 -07004235
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004236void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08004237 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004238 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004239 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08004240 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004241 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08004242 if (devDesc != 0) {
4243 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
4244 desc->mIoHandle, address.string());
4245 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004246 }
4247}
4248
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004249status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004250 audio_policy_dev_state_t state,
4251 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004252 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07004253{
François Gaffie53615e22015-03-19 09:24:12 +01004254 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07004255 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004256
4257 if (audio_device_is_digital(device)) {
4258 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004259 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004260 }
Eric Laurente552edb2014-03-10 17:42:56 -07004261
Eric Laurent3b73df72014-03-11 09:06:29 -07004262 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004263 // first list already open outputs that can be routed to this device
4264 for (size_t i = 0; i < mOutputs.size(); i++) {
4265 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07004266 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004267 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004268 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
4269 outputs.add(mOutputs.keyAt(i));
4270 } else {
4271 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08004272 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004273 }
Eric Laurente552edb2014-03-10 17:42:56 -07004274 }
4275 }
4276 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004277 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004278 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004279 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4280 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004281 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004282 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004283 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004284 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004285 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4286 j, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004287 }
Eric Laurente552edb2014-03-10 17:42:56 -07004288 }
4289 }
4290 }
4291
Eric Laurent7b279bb2015-12-14 10:18:23 -08004292 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004293
Eric Laurente552edb2014-03-10 17:42:56 -07004294 if (profiles.isEmpty() && outputs.isEmpty()) {
4295 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4296 return BAD_VALUE;
4297 }
4298
4299 // open outputs for matching profiles if needed. Direct outputs are also opened to
4300 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4301 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004302 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004303
4304 // nothing to do if one output is already opened for this profile
4305 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004306 for (j = 0; j < outputs.size(); j++) {
4307 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004308 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004309 // matching profile: save the sample rates, format and channel masks supported
4310 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07004311 if (audio_device_is_digital(device)) {
4312 devDesc->importAudioPort(profile);
4313 }
Eric Laurente552edb2014-03-10 17:42:56 -07004314 break;
4315 }
4316 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004317 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004318 continue;
4319 }
4320
Eric Laurent3974e3b2017-12-07 17:58:43 -08004321 if (!profile->canOpenNewIo()) {
4322 ALOGW("Max Output number %u already opened for this profile %s",
4323 profile->maxOpenCount, profile->getTagName().c_str());
4324 continue;
4325 }
4326
Eric Laurent83efe1c2017-07-09 16:51:08 -07004327 ALOGV("opening output for device %08x with params %s profile %p name %s",
4328 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004329 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004330 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004331 status_t status = desc->open(nullptr, device, address,
4332 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004333
Eric Laurentfe231122017-11-17 17:48:06 -08004334 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004335 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004336 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004337 char *param = audio_device_address_to_parameter(device, address);
4338 mpClientInterface->setParameters(output, String8(param));
4339 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004340 }
Phil Burk00eeb322016-03-31 12:41:00 -07004341 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004342 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004343 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004344 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004345 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004346 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004347 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004348 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004349 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4350 profile->pickAudioProfile(
4351 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004352 config.offload_info.sample_rate = config.sample_rate;
4353 config.offload_info.channel_mask = config.channel_mask;
4354 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004355
4356 status_t status = desc->open(&config, device, address, AUDIO_STREAM_DEFAULT,
4357 AUDIO_OUTPUT_FLAG_NONE, &output);
4358 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004359 output = AUDIO_IO_HANDLE_NONE;
4360 }
Eric Laurentd4692962014-05-05 18:13:44 -07004361 }
4362
Eric Laurentcf2c0212014-07-25 16:20:43 -07004363 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004364 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01004365 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004366 sp<AudioPolicyMix> policyMix;
4367 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004368 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
4369 address.string());
4370 }
François Gaffie036e1e92015-03-19 10:16:24 +01004371 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07004372 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01004373
Eric Laurent87ffa392015-05-22 10:32:38 -07004374 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4375 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004376 // no duplicated output for direct outputs and
4377 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004378 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004379
Eric Laurentd4692962014-05-05 18:13:44 -07004380 //TODO: configure audio effect output stage here
4381
4382 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004383 sp<SwAudioOutputDescriptor> dupOutputDesc =
4384 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4385 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4386 &duplicatedOutput);
4387 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004388 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004389 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004390 } else {
4391 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004392 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004393 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004394 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004395 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004396 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004397 }
Eric Laurente552edb2014-03-10 17:42:56 -07004398 }
4399 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004400 } else {
4401 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004402 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004403 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004404 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004405 profiles.removeAt(profile_index);
4406 profile_index--;
4407 } else {
4408 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004409 // Load digital format info only for digital devices
4410 if (audio_device_is_digital(device)) {
4411 devDesc->importAudioPort(profile);
4412 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004413
François Gaffie53615e22015-03-19 09:24:12 +01004414 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004415 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4416 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004417 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004418 NULL/*patch handle*/, address.string());
4419 }
Eric Laurente552edb2014-03-10 17:42:56 -07004420 ALOGV("checkOutputsForDevice(): adding output %d", output);
4421 }
4422 }
4423
4424 if (profiles.isEmpty()) {
4425 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4426 return BAD_VALUE;
4427 }
Eric Laurentd4692962014-05-05 18:13:44 -07004428 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004429 // check if one opened output is not needed any more after disconnecting one device
4430 for (size_t i = 0; i < mOutputs.size(); i++) {
4431 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004432 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004433 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004434 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004435 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004436 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004437 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004438 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4439 mOutputs.keyAt(i));
4440 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004441 }
Eric Laurente552edb2014-03-10 17:42:56 -07004442 }
4443 }
Eric Laurentd4692962014-05-05 18:13:44 -07004444 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004445 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004446 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4447 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004448 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004449 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004450 "clearing direct output profile %zu on module %s",
4451 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004452 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004453 }
4454 }
4455 }
4456 }
4457 return NO_ERROR;
4458}
4459
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004460status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004461 audio_policy_dev_state_t state,
4462 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004463 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004464{
Paul McLean9080a4c2015-06-18 08:24:02 -07004465 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004466 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004467
4468 if (audio_device_is_digital(device)) {
4469 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004470 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004471 }
4472
Eric Laurentd4692962014-05-05 18:13:44 -07004473 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4474 // first list already open inputs that can be routed to this device
4475 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4476 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004477 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004478 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4479 inputs.add(mInputs.keyAt(input_index));
4480 }
4481 }
4482
4483 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004484 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004485 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004486 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004487 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004488 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004489 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004490
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004491 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004492 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004493 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004494 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004495 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4496 profile_index, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004497 }
Eric Laurentd4692962014-05-05 18:13:44 -07004498 }
4499 }
4500 }
4501
4502 if (profiles.isEmpty() && inputs.isEmpty()) {
4503 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4504 return BAD_VALUE;
4505 }
4506
4507 // open inputs for matching profiles if needed. Direct inputs are also opened to
4508 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4509 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4510
Eric Laurent1c333e22014-05-20 10:48:17 -07004511 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004512
Eric Laurentd4692962014-05-05 18:13:44 -07004513 // nothing to do if one input is already opened for this profile
4514 size_t input_index;
4515 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4516 desc = mInputs.valueAt(input_index);
4517 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004518 if (audio_device_is_digital(device)) {
4519 devDesc->importAudioPort(profile);
4520 }
Eric Laurentd4692962014-05-05 18:13:44 -07004521 break;
4522 }
4523 }
4524 if (input_index != mInputs.size()) {
4525 continue;
4526 }
4527
Eric Laurent3974e3b2017-12-07 17:58:43 -08004528 if (!profile->canOpenNewIo()) {
4529 ALOGW("Max Input number %u already opened for this profile %s",
4530 profile->maxOpenCount, profile->getTagName().c_str());
4531 continue;
4532 }
4533
Eric Laurentfe231122017-11-17 17:48:06 -08004534 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004535 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004536 status_t status = desc->open(nullptr,
4537 device,
4538 address,
4539 AUDIO_SOURCE_MIC,
4540 AUDIO_INPUT_FLAG_NONE,
4541 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004542
Eric Laurentcf2c0212014-07-25 16:20:43 -07004543 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004544 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004545 char *param = audio_device_address_to_parameter(device, address);
4546 mpClientInterface->setParameters(input, String8(param));
4547 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004548 }
Phil Burk00eeb322016-03-31 12:41:00 -07004549 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004550 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004551 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004552 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004553 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004554 }
4555
4556 if (input != 0) {
4557 addInput(input, desc);
4558 }
4559 } // endif input != 0
4560
Eric Laurentcf2c0212014-07-25 16:20:43 -07004561 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004562 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004563 profiles.removeAt(profile_index);
4564 profile_index--;
4565 } else {
4566 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004567 if (audio_device_is_digital(device)) {
4568 devDesc->importAudioPort(profile);
4569 }
Eric Laurentd4692962014-05-05 18:13:44 -07004570 ALOGV("checkInputsForDevice(): adding input %d", input);
4571 }
4572 } // end scan profiles
4573
4574 if (profiles.isEmpty()) {
4575 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4576 return BAD_VALUE;
4577 }
4578 } else {
4579 // Disconnect
4580 // check if one opened input is not needed any more after disconnecting one device
4581 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4582 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004583 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004584 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4585 mInputs.keyAt(input_index));
4586 inputs.add(mInputs.keyAt(input_index));
4587 }
4588 }
4589 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004590 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004591 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004592 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004593 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004594 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004595 if (profile->supportDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004596 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4597 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004598 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004599 }
4600 }
4601 }
4602 } // end disconnect
4603
4604 return NO_ERROR;
4605}
4606
4607
Eric Laurente0720872014-03-11 09:30:41 -07004608void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004609{
4610 ALOGV("closeOutput(%d)", output);
4611
Eric Laurentc75307b2015-03-17 15:29:32 -07004612 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004613 if (outputDesc == NULL) {
4614 ALOGW("closeOutput() unknown output %d", output);
4615 return;
4616 }
François Gaffie036e1e92015-03-19 10:16:24 +01004617 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004618
Eric Laurente552edb2014-03-10 17:42:56 -07004619 // look for duplicated outputs connected to the output being removed.
4620 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004621 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004622 if (dupOutputDesc->isDuplicated() &&
4623 (dupOutputDesc->mOutput1 == outputDesc ||
4624 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004625 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004626 if (dupOutputDesc->mOutput1 == outputDesc) {
4627 outputDesc2 = dupOutputDesc->mOutput2;
4628 } else {
4629 outputDesc2 = dupOutputDesc->mOutput1;
4630 }
4631 // As all active tracks on duplicated output will be deleted,
4632 // and as they were also referenced on the other output, the reference
4633 // count for their stream type must be adjusted accordingly on
4634 // the other output.
Eric Laurent733ce942017-12-07 12:18:25 -08004635 bool wasActive = outputDesc2->isActive();
Eric Laurent3b73df72014-03-11 09:06:29 -07004636 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurent592dd7b2018-08-05 18:58:48 -07004637 int activeCount = dupOutputDesc->streamActiveCount((audio_stream_type_t)j);
4638 outputDesc2->changeStreamActiveCount((audio_stream_type_t)j,-activeCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004639 }
Eric Laurent733ce942017-12-07 12:18:25 -08004640 // stop() will be a no op if the output is still active but is needed in case all
4641 // active streams refcounts where cleared above
4642 if (wasActive) {
4643 outputDesc2->stop();
4644 }
Eric Laurente552edb2014-03-10 17:42:56 -07004645 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4646 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4647
4648 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004649 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004650 }
4651 }
4652
Eric Laurent05b90f82014-08-27 15:32:29 -07004653 nextAudioPortGeneration();
4654
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004655 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004656 if (index >= 0) {
4657 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004658 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004659 mAudioPatches.removeItemsAt(index);
4660 mpClientInterface->onAudioPatchListUpdate();
4661 }
4662
Eric Laurentfe231122017-11-17 17:48:06 -08004663 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004664
François Gaffie53615e22015-03-19 09:24:12 +01004665 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004666 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004667}
4668
4669void AudioPolicyManager::closeInput(audio_io_handle_t input)
4670{
4671 ALOGV("closeInput(%d)", input);
4672
4673 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4674 if (inputDesc == NULL) {
4675 ALOGW("closeInput() unknown input %d", input);
4676 return;
4677 }
4678
Eric Laurent6a94d692014-05-20 11:18:06 -07004679 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004680
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004681 audio_devices_t device = inputDesc->mDevice;
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004682 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004683 if (index >= 0) {
4684 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004685 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004686 mAudioPatches.removeItemsAt(index);
4687 mpClientInterface->onAudioPatchListUpdate();
4688 }
4689
Eric Laurentfe231122017-11-17 17:48:06 -08004690 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004691 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004692
4693 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
4694 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
4695 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
4696 SoundTrigger::setCaptureState(false);
4697 }
Eric Laurente552edb2014-03-10 17:42:56 -07004698}
4699
Eric Laurentc75307b2015-03-17 15:29:32 -07004700SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4701 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004702 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004703{
4704 SortedVector<audio_io_handle_t> outputs;
4705
4706 ALOGVV("getOutputsForDevice() device %04x", device);
4707 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004708 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004709 i, openOutputs.valueAt(i)->isDuplicated(),
4710 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004711 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4712 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4713 outputs.add(openOutputs.keyAt(i));
4714 }
4715 }
4716 return outputs;
4717}
4718
Mikhail Naganov37977152018-07-11 15:54:44 -07004719void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
4720{
4721 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
4722 // output is suspended before any tracks are moved to it
4723 checkA2dpSuspend();
4724 checkOutputForAllStrategies();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004725 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07004726 updateDevicesAndOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004727 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
4728 setMsdPatch();
4729 }
Mikhail Naganov37977152018-07-11 15:54:44 -07004730}
4731
Eric Laurente0720872014-03-11 09:30:41 -07004732void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004733{
4734 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4735 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4736 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4737 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4738
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004739 // also take into account external policy-related changes: add all outputs which are
4740 // associated with policies in the "before" and "after" output vectors
4741 ALOGVV("checkOutputForStrategy(): policy related outputs");
4742 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004743 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004744 if (desc != 0 && desc->mPolicyMix != NULL) {
4745 srcOutputs.add(desc->mIoHandle);
4746 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4747 }
4748 }
4749 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004750 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004751 if (desc != 0 && desc->mPolicyMix != NULL) {
4752 dstOutputs.add(desc->mIoHandle);
4753 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4754 }
4755 }
4756
Mikhail Naganov9de8bd12018-07-23 16:41:31 -07004757 if (srcOutputs != dstOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004758 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4759 // audio from invalidated tracks will be rendered when unmuting
4760 uint32_t maxLatency = 0;
4761 for (audio_io_handle_t srcOut : srcOutputs) {
4762 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4763 if (desc != 0 && maxLatency < desc->latency()) {
4764 maxLatency = desc->latency();
4765 }
4766 }
Eric Laurente552edb2014-03-10 17:42:56 -07004767 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4768 strategy, srcOutputs[0], dstOutputs[0]);
4769 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004770 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004771 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4772 if (desc != 0 && isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004773 setStrategyMute(strategy, true, desc);
Eric Laurentac3a6902018-05-11 16:39:10 -07004774 setStrategyMute(strategy, false, desc, maxLatency * LATENCY_MUTE_FACTOR, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004775 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004776 sp<SourceClientDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004777 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004778 if (source != 0){
4779 connectAudioSource(source);
4780 }
Eric Laurente552edb2014-03-10 17:42:56 -07004781 }
4782
4783 // Move effects associated to this strategy from previous output to new output
4784 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004785 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004786 }
4787 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004788 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004789 if (getStrategy((audio_stream_type_t)i) == strategy) {
4790 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004791 }
4792 }
4793 }
4794}
4795
Eric Laurente0720872014-03-11 09:30:41 -07004796void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004797{
François Gaffie2110e042015-03-24 08:41:51 +01004798 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004799 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004800 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004801 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004802 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004803 checkOutputForStrategy(STRATEGY_SONIFICATION);
4804 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004805 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004806 checkOutputForStrategy(STRATEGY_MEDIA);
4807 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004808 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004809}
4810
Eric Laurente0720872014-03-11 09:30:41 -07004811void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004812{
François Gaffie53615e22015-03-19 09:24:12 +01004813 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004814 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004815 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004816 return;
4817 }
4818
Eric Laurent3a4311c2014-03-17 12:00:47 -07004819 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004820 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4821 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4822 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004823
4824 // if suspended, restore A2DP output if:
4825 // ((SCO device is NOT connected) ||
4826 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4827 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004828 //
Eric Laurentf732e072016-08-03 19:30:28 -07004829 // if not suspended, suspend A2DP output if:
4830 // (SCO device is connected) &&
4831 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4832 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004833 //
4834 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004835 if (!isScoConnected ||
4836 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4837 AUDIO_POLICY_FORCE_BT_SCO) &&
4838 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4839 AUDIO_POLICY_FORCE_BT_SCO) &&
4840 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004841 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004842
4843 mpClientInterface->restoreOutput(a2dpOutput);
4844 mA2dpSuspended = false;
4845 }
4846 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004847 if (isScoConnected &&
4848 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4849 AUDIO_POLICY_FORCE_BT_SCO) ||
4850 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4851 AUDIO_POLICY_FORCE_BT_SCO) ||
4852 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004853 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004854
4855 mpClientInterface->suspendOutput(a2dpOutput);
4856 mA2dpSuspended = true;
4857 }
4858 }
4859}
4860
Eric Laurent97ac8712018-07-27 18:59:02 -07004861template <class IoDescriptor, class Filter>
4862sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4863 IoDescriptor& desc, Filter filter, bool& active, const DeviceVector& devices)
4864{
4865 auto activeClients = desc->clientsList(true /*activeOnly*/);
4866 auto activeClientsWithRoute =
4867 desc->clientsList(true /*activeOnly*/, filter, true /*preferredDevice*/);
4868 active = activeClients.size() > 0;
4869 if (active && activeClients.size() == activeClientsWithRoute.size()) {
4870 return devices.getDeviceFromId(activeClientsWithRoute[0]->preferredDeviceId());
4871 }
4872 return nullptr;
4873}
4874
4875template <class IoCollection, class Filter>
4876sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4877 IoCollection& ioCollection, Filter filter, const DeviceVector& devices)
4878{
4879 sp<DeviceDescriptor> device;
4880 for (size_t i = 0; i < ioCollection.size(); i++) {
4881 auto desc = ioCollection.valueAt(i);
4882 bool active;
4883 sp<DeviceDescriptor> curDevice = findPreferredDevice(desc, filter, active, devices);
4884 if (active && curDevice == nullptr) {
4885 return nullptr;
4886 } else if (curDevice != nullptr) {
4887 device = curDevice;
4888 }
4889 }
4890 return device;
4891}
4892
Eric Laurentc75307b2015-03-17 15:29:32 -07004893audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4894 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004895{
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004896 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004897 if (index >= 0) {
4898 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4899 if (patchDesc->mUid != mUidCached) {
4900 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004901 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004902 return outputDesc->device();
4903 }
4904 }
4905
Eric Laurent97ac8712018-07-27 18:59:02 -07004906 // Honor explicit routing requests only if no client using default routing is active on this
4907 // input: a specific app can not force routing for other apps by setting a preferred device.
4908 bool active; // unused
4909 sp<DeviceDescriptor> deviceDesc =
4910 findPreferredDevice(outputDesc, STRATEGY_NONE, active, mAvailableOutputDevices);
4911 if (deviceDesc != nullptr) {
4912 return deviceDesc->type();
Eric Laurentf3a5a602018-05-22 18:42:55 -07004913 }
4914
Eric Laurente552edb2014-03-10 17:42:56 -07004915 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004916 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004917 // use device for strategy enforced audible
4918 // 2: we are in call or the strategy phone is active on the output:
4919 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004920 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004921 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004922 // 4: the strategy for enforced audible is active but not enforced on the output:
4923 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004924 // 5: the strategy accessibility is active on the output:
4925 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004926 // 6: the strategy "respectful" sonification is active on the output:
4927 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004928 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004929 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004930 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004931 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004932 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004933 // use device for strategy t-t-s
Eric Laurent484e9272018-06-07 17:29:23 -07004934
4935 // FIXME: extend use of isStrategyActiveOnSameModule() to all strategies
4936 // with a refined rule considering mutually exclusive devices (using same backend)
4937 // as opposed to all streams on the same audio HAL module.
Eric Laurent97ac8712018-07-27 18:59:02 -07004938 audio_devices_t device = AUDIO_DEVICE_NONE;
François Gaffiead3183e2015-03-18 16:55:35 +01004939 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004940 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004941 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4942 } else if (isInCall() ||
Eric Laurent484e9272018-06-07 17:29:23 -07004943 isStrategyActiveOnSameModule(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004944 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
Yung Ti Su3e7eb5e2018-06-13 11:48:42 +08004945 } else if (isStrategyActiveOnSameModule(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004946 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004947 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
4948 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004949 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4950 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004951 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004952 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004953 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004954 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004955 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004956 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004957 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004958 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004959 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004960 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004961 }
4962
Eric Laurent1c333e22014-05-20 10:48:17 -07004963 ALOGV("getNewOutputDevice() selected device %x", device);
4964 return device;
4965}
4966
Eric Laurentfb66dd92016-01-28 18:32:03 -08004967audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004968{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004969 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004970
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004971 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004972 if (index >= 0) {
4973 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4974 if (patchDesc->mUid != mUidCached) {
4975 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004976 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004977 return inputDesc->mDevice;
4978 }
4979 }
4980
Eric Laurent97ac8712018-07-27 18:59:02 -07004981 // Honor explicit routing requests only if no client using default routing is active on this
4982 // input: a specific app can not force routing for other apps by setting a preferred device.
4983 bool active;
4984 sp<DeviceDescriptor> deviceDesc =
4985 findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
4986 if (deviceDesc != nullptr) {
4987 return deviceDesc->type();
4988 }
4989
Eric Laurentdc95a252018-04-12 12:46:56 -07004990 // If we are not in call and no client is active on this input, this methods returns
4991 // AUDIO_DEVICE_NONE, causing the patch on the input stream to be released.
Eric Laurentfb66dd92016-01-28 18:32:03 -08004992 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
Eric Laurentdc95a252018-04-12 12:46:56 -07004993 if (source == AUDIO_SOURCE_DEFAULT && isInCall()) {
4994 source = AUDIO_SOURCE_VOICE_COMMUNICATION;
4995 }
4996 if (source != AUDIO_SOURCE_DEFAULT) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08004997 device = getDeviceAndMixForInputSource(source);
4998 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004999
Eric Laurente552edb2014-03-10 17:42:56 -07005000 return device;
5001}
5002
Eric Laurent794fde22016-03-11 09:50:45 -08005003bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
5004 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08005005 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08005006}
5007
Eric Laurente0720872014-03-11 09:30:41 -07005008uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005009 return (uint32_t)getStrategy(stream);
5010}
5011
Eric Laurente0720872014-03-11 09:30:41 -07005012audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005013 // By checking the range of stream before calling getStrategy, we avoid
5014 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
5015 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08005016 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005017 return AUDIO_DEVICE_NONE;
5018 }
Eric Laurentb0688d62018-08-14 15:49:18 -07005019 audio_devices_t activeDevices = AUDIO_DEVICE_NONE;
Eric Laurent28d09f02016-03-08 10:43:05 -08005020 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08005021 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
5022 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08005023 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07005024 }
Eric Laurent794fde22016-03-11 09:50:45 -08005025 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08005026 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07005027 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Eric Laurentb0688d62018-08-14 15:49:18 -07005028 devices |= curDevices;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005029 for (audio_io_handle_t output : getOutputsForDevice(curDevices, mOutputs)) {
5030 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08005031 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurentb0688d62018-08-14 15:49:18 -07005032 activeDevices |= outputDesc->device();
Eric Laurent28d09f02016-03-08 10:43:05 -08005033 }
5034 }
Eric Laurente552edb2014-03-10 17:42:56 -07005035 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005036
Eric Laurentb0688d62018-08-14 15:49:18 -07005037 // Favor devices selected on active streams if any to report correct device in case of
5038 // explicit device selection
5039 if (activeDevices != AUDIO_DEVICE_NONE) {
5040 devices = activeDevices;
5041 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005042 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
5043 and doesn't really need to.*/
5044 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
5045 devices |= AUDIO_DEVICE_OUT_SPEAKER;
5046 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
5047 }
Eric Laurente552edb2014-03-10 17:42:56 -07005048 return devices;
5049}
5050
François Gaffie2110e042015-03-24 08:41:51 +01005051routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
5052{
Eric Laurent223fd5c2014-11-11 13:43:36 -08005053 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01005054 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005055}
5056
Eric Laurent97ac8712018-07-27 18:59:02 -07005057routing_strategy AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005058 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005059 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
Eric Laurent97ac8712018-07-27 18:59:02 -07005060 return STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005061 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005062 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
Eric Laurent97ac8712018-07-27 18:59:02 -07005063 return STRATEGY_ENFORCED_AUDIBLE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005064 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005065 // usage to strategy mapping
Eric Laurent97ac8712018-07-27 18:59:02 -07005066 return mEngine->getStrategyForUsage(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005067}
5068
Eric Laurente0720872014-03-11 09:30:41 -07005069void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005070 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005071 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07005072 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
5073 updateDevicesAndOutputs();
5074 break;
5075 default:
5076 break;
5077 }
5078}
5079
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005080uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07005081
5082 // skip beacon mute management if a dedicated TTS output is available
5083 if (mTtsOutputAvailable) {
5084 return 0;
5085 }
5086
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005087 switch(event) {
5088 case STARTING_OUTPUT:
5089 mBeaconMuteRefCount++;
5090 break;
5091 case STOPPING_OUTPUT:
5092 if (mBeaconMuteRefCount > 0) {
5093 mBeaconMuteRefCount--;
5094 }
5095 break;
5096 case STARTING_BEACON:
5097 mBeaconPlayingRefCount++;
5098 break;
5099 case STOPPING_BEACON:
5100 if (mBeaconPlayingRefCount > 0) {
5101 mBeaconPlayingRefCount--;
5102 }
5103 break;
5104 }
5105
5106 if (mBeaconMuteRefCount > 0) {
5107 // any playback causes beacon to be muted
5108 return setBeaconMute(true);
5109 } else {
5110 // no other playback: unmute when beacon starts playing, mute when it stops
5111 return setBeaconMute(mBeaconPlayingRefCount == 0);
5112 }
5113}
5114
5115uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5116 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5117 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5118 // keep track of muted state to avoid repeating mute/unmute operations
5119 if (mBeaconMuted != mute) {
5120 // mute/unmute AUDIO_STREAM_TTS on all outputs
5121 ALOGV("\t muting %d", mute);
5122 uint32_t maxLatency = 0;
5123 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005124 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005125 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07005126 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005127 0 /*delay*/, AUDIO_DEVICE_NONE);
5128 const uint32_t latency = desc->latency() * 2;
5129 if (latency > maxLatency) {
5130 maxLatency = latency;
5131 }
5132 }
5133 mBeaconMuted = mute;
5134 return maxLatency;
5135 }
5136 return 0;
5137}
5138
Eric Laurente0720872014-03-11 09:30:41 -07005139audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01005140 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005141{
Eric Laurent97ac8712018-07-27 18:59:02 -07005142 // Honor explicit routing requests only if all active clients have a preferred route in which
5143 // case the last active client route is used
5144 sp<DeviceDescriptor> deviceDesc = findPreferredDevice(mOutputs, strategy, mAvailableOutputDevices);
5145 if (deviceDesc != nullptr) {
5146 return deviceDesc->type();
Paul McLeanaa981192015-03-21 09:55:15 -07005147 }
5148
Eric Laurente552edb2014-03-10 17:42:56 -07005149 if (fromCache) {
5150 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
5151 strategy, mDeviceForStrategy[strategy]);
5152 return mDeviceForStrategy[strategy];
5153 }
François Gaffie2110e042015-03-24 08:41:51 +01005154 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07005155}
5156
Eric Laurente0720872014-03-11 09:30:41 -07005157void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005158{
5159 for (int i = 0; i < NUM_STRATEGIES; i++) {
5160 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
5161 }
5162 mPreviousOutputs = mOutputs;
5163}
5164
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005165uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005166 audio_devices_t prevDevice,
5167 uint32_t delayMs)
5168{
5169 // mute/unmute strategies using an incompatible device combination
5170 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5171 // if unmuting, unmute only after the specified delay
5172 if (outputDesc->isDuplicated()) {
5173 return 0;
5174 }
5175
5176 uint32_t muteWaitMs = 0;
5177 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07005178 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005179
5180 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
5181 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07005182 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07005183 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
5184 bool doMute = false;
5185
5186 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
5187 doMute = true;
5188 outputDesc->mStrategyMutedByDevice[i] = true;
5189 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
5190 doMute = true;
5191 outputDesc->mStrategyMutedByDevice[i] = false;
5192 }
Eric Laurent99401132014-05-07 19:48:15 -07005193 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005194 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005195 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005196 // skip output if it does not share any device with current output
5197 if ((desc->supportedDevices() & outputDesc->supportedDevices())
5198 == AUDIO_DEVICE_NONE) {
5199 continue;
5200 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005201 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07005202 mute ? "muting" : "unmuting", i, curDevice);
5203 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005204 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005205 if (mute) {
5206 // FIXME: should not need to double latency if volume could be applied
5207 // immediately by the audioflinger mixer. We must account for the delay
5208 // between now and the next time the audioflinger thread for this output
5209 // will process a buffer (which corresponds to one buffer size,
5210 // usually 1/2 or 1/4 of the latency).
5211 if (muteWaitMs < desc->latency() * 2) {
5212 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005213 }
5214 }
5215 }
5216 }
5217 }
5218 }
5219
Eric Laurent99401132014-05-07 19:48:15 -07005220 // temporary mute output if device selection changes to avoid volume bursts due to
5221 // different per device volumes
5222 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005223 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5224 // temporary mute duration is conservatively set to 4 times the reported latency
5225 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5226 if (muteWaitMs < tempMuteWaitMs) {
5227 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005228 }
Eric Laurentdc462862016-07-19 12:29:53 -07005229
Eric Laurent99401132014-05-07 19:48:15 -07005230 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005231 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005232 // make sure that we do not start the temporary mute period too early in case of
5233 // delayed device change
5234 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005235 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07005236 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07005237 }
5238 }
5239 }
5240
Eric Laurente552edb2014-03-10 17:42:56 -07005241 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5242 if (muteWaitMs > delayMs) {
5243 muteWaitMs -= delayMs;
5244 usleep(muteWaitMs * 1000);
5245 return muteWaitMs;
5246 }
5247 return 0;
5248}
5249
Eric Laurentc75307b2015-03-17 15:29:32 -07005250uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005251 audio_devices_t device,
5252 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07005253 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005254 audio_patch_handle_t *patchHandle,
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005255 const char *address,
5256 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005257{
Eric Laurentc75307b2015-03-17 15:29:32 -07005258 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005259 AudioParameter param;
5260 uint32_t muteWaitMs;
5261
5262 if (outputDesc->isDuplicated()) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005263 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs,
5264 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
5265 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs,
5266 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005267 return muteWaitMs;
5268 }
5269 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5270 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07005271 if ((device != AUDIO_DEVICE_NONE) &&
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005272 ((device & outputDesc->supportedDevices()) == AUDIO_DEVICE_NONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005273 return 0;
5274 }
5275
5276 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07005277 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07005278
5279 audio_devices_t prevDevice = outputDesc->mDevice;
5280
Paul McLeanaa981192015-03-21 09:55:15 -07005281 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005282
5283 if (device != AUDIO_DEVICE_NONE) {
5284 outputDesc->mDevice = device;
5285 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005286
5287 // if the outputs are not materially active, there is no need to mute.
5288 if (requiresMuteCheck) {
5289 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
5290 } else {
5291 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5292 muteWaitMs = 0;
5293 }
Eric Laurente552edb2014-03-10 17:42:56 -07005294
5295 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005296 // the requested device is AUDIO_DEVICE_NONE
5297 // OR the requested device is the same as current device
5298 // AND force is not specified
5299 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07005300 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07005301 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
5302 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005303 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005304 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005305 return muteWaitMs;
5306 }
5307
5308 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07005309
Eric Laurente552edb2014-03-10 17:42:56 -07005310 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07005311 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005312 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005313 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07005314 DeviceVector deviceList;
5315 if ((address == NULL) || (strlen(address) == 0)) {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005316 deviceList = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurentc40d9692016-04-13 19:14:13 -07005317 } else {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005318 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
5319 device, String8(address));
5320 if (deviceDesc) deviceList.add(deviceDesc);
Eric Laurentc40d9692016-04-13 19:14:13 -07005321 }
5322
Eric Laurent1c333e22014-05-20 10:48:17 -07005323 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005324 PatchBuilder patchBuilder;
5325 patchBuilder.addSource(outputDesc);
Eric Laurent1c333e22014-05-20 10:48:17 -07005326 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005327 patchBuilder.addSink(deviceList.itemAt(i));
Eric Laurent1c333e22014-05-20 10:48:17 -07005328 }
Mikhail Naganovdc769682018-05-04 15:34:08 -07005329 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005330 }
bryant_liuf5e7e792014-08-19 20:07:05 +08005331
5332 // inform all input as well
5333 for (size_t i = 0; i < mInputs.size(); i++) {
5334 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01005335 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08005336 AudioParameter inputCmd = AudioParameter();
5337 ALOGV("%s: inform input %d of device:%d", __func__,
5338 inputDescriptor->mIoHandle, device);
5339 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
5340 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
5341 inputCmd.toString(),
5342 delayMs);
5343 }
5344 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005345 }
Eric Laurente552edb2014-03-10 17:42:56 -07005346
5347 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07005348 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005349
5350 return muteWaitMs;
5351}
5352
Eric Laurentc75307b2015-03-17 15:29:32 -07005353status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005354 int delayMs,
5355 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005356{
Eric Laurent6a94d692014-05-20 11:18:06 -07005357 ssize_t index;
5358 if (patchHandle) {
5359 index = mAudioPatches.indexOfKey(*patchHandle);
5360 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005361 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005362 }
5363 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005364 return INVALID_OPERATION;
5365 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005366 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5367 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005368 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005369 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005370 removeAudioPatch(patchDesc->mHandle);
5371 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005372 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005373 return status;
5374}
5375
5376status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5377 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005378 bool force,
5379 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005380{
5381 status_t status = NO_ERROR;
5382
Eric Laurent1f2f2232014-06-02 12:01:23 -07005383 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005384 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5385 inputDesc->mDevice = device;
5386
Mikhail Naganov708e0382018-05-30 09:53:04 -07005387 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005388 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005389 PatchBuilder patchBuilder;
5390 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005391 // AUDIO_SOURCE_HOTWORD is for internal use only:
5392 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07005393 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5394 auto result = usecase;
5395 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5396 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5397 }
5398 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07005399 //only one input device for now
Mikhail Naganovdc769682018-05-04 15:34:08 -07005400 addSource(deviceList.itemAt(0));
5401 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005402 }
5403 }
5404 return status;
5405}
5406
Eric Laurent6a94d692014-05-20 11:18:06 -07005407status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5408 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005409{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005410 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005411 ssize_t index;
5412 if (patchHandle) {
5413 index = mAudioPatches.indexOfKey(*patchHandle);
5414 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005415 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005416 }
5417 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005418 return INVALID_OPERATION;
5419 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005420 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5421 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005422 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005423 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005424 removeAudioPatch(patchDesc->mHandle);
5425 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005426 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005427 return status;
5428}
5429
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005430sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005431 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005432 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005433 audio_format_t& format,
5434 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005435 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005436{
5437 // Choose an input profile based on the requested capture parameters: select the first available
5438 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005439 //
5440 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5441 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005442
Glenn Kasten730b9262018-03-29 15:01:26 -07005443 sp<IOProfile> firstInexact;
5444 uint32_t updatedSamplingRate = 0;
5445 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5446 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005447 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005448 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005449 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005450 //updatedFormat = format;
Eric Laurent275e8e92014-11-30 15:14:47 -08005451 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005452 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005453 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005454 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005455 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005456 &channelMask /*updatedChannelMask*/,
5457 // FIXME ugly cast
5458 (audio_output_flags_t) flags,
5459 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005460 return profile;
5461 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005462 if (firstInexact == nullptr && profile->isCompatibleProfile(device, address,
5463 samplingRate,
5464 &updatedSamplingRate,
5465 format,
5466 &updatedFormat,
5467 channelMask,
5468 &updatedChannelMask,
5469 // FIXME ugly cast
5470 (audio_output_flags_t) flags,
5471 false /*exactMatchRequiredForInputFlags*/)) {
5472 firstInexact = profile;
5473 }
5474
Eric Laurente552edb2014-03-10 17:42:56 -07005475 }
5476 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005477 if (firstInexact != nullptr) {
5478 samplingRate = updatedSamplingRate;
5479 format = updatedFormat;
5480 channelMask = updatedChannelMask;
5481 return firstInexact;
5482 }
Eric Laurente552edb2014-03-10 17:42:56 -07005483 return NULL;
5484}
5485
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005486
5487audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005488 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005489{
Eric Laurent97ac8712018-07-27 18:59:02 -07005490 // Honor explicit routing requests only if all active clients have a preferred route in which
5491 // case the last active client route is used
5492 sp<DeviceDescriptor> deviceDesc =
5493 findPreferredDevice(mInputs, inputSource, mAvailableInputDevices);
5494 if (deviceDesc != nullptr) {
5495 return deviceDesc->type();
5496 }
5497
5498
François Gaffie036e1e92015-03-19 10:16:24 +01005499 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5500 audio_devices_t selectedDeviceFromMix =
5501 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005502
François Gaffie036e1e92015-03-19 10:16:24 +01005503 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5504 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005505 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005506 return getDeviceForInputSource(inputSource);
5507}
5508
5509audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5510{
Eric Laurent97ac8712018-07-27 18:59:02 -07005511 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005512}
5513
Eric Laurente0720872014-03-11 09:30:41 -07005514float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005515 int index,
5516 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005517{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005518 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005519
5520 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5521 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5522 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5523 // the ringtone volume
5524 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5525 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5526 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5527 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5528 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5529 }
5530
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005531 // in-call: always cap volume by voice volume + some low headroom
5532 if ((stream != AUDIO_STREAM_VOICE_CALL) &&
Eric Laurent7731b5a2018-04-06 15:47:22 -07005533 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005534 switch (stream) {
5535 case AUDIO_STREAM_SYSTEM:
5536 case AUDIO_STREAM_RING:
5537 case AUDIO_STREAM_MUSIC:
5538 case AUDIO_STREAM_ALARM:
5539 case AUDIO_STREAM_NOTIFICATION:
5540 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5541 case AUDIO_STREAM_DTMF:
5542 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005543 int voiceVolumeIndex =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005544 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, device);
Eric Laurent7731b5a2018-04-06 15:47:22 -07005545 const float maxVoiceVolDb =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005546 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, device)
Eric Laurent7731b5a2018-04-06 15:47:22 -07005547 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005548 if (volumeDB > maxVoiceVolDb) {
5549 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5550 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5551 volumeDB = maxVoiceVolDb;
5552 }
5553 } break;
5554 default:
5555 break;
5556 }
5557 }
5558
Eric Laurente552edb2014-03-10 17:42:56 -07005559 // if a headset is connected, apply the following rules to ring tones and notifications
5560 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005561 // - always attenuate notifications volume by 6dB
5562 // - attenuate ring tones volume by 6dB unless music is not playing and
5563 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005564 // - if music is playing, always limit the volume to current music volume,
5565 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005566 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005567 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5568 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5569 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005570 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005571 AUDIO_DEVICE_OUT_USB_HEADSET |
5572 AUDIO_DEVICE_OUT_HEARING_AID)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005573 ((stream_strategy == STRATEGY_SONIFICATION)
5574 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005575 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005576 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005577 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005578 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005579 // when the phone is ringing we must consider that music could have been paused just before
5580 // by the music application and behave as if music was active if the last music track was
5581 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005582 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005583 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005584 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005585 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005586 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005587 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5588 musicDevice),
5589 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005590 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5591 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005592 if (volumeDB > minVolDB) {
5593 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005594 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005595 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005596 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5597 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5598 // on A2DP, also ensure notification volume is not too low compared to media when
5599 // intended to be played
5600 if ((volumeDB > -96.0f) &&
5601 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5602 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5603 stream, device,
5604 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5605 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5606 }
5607 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005608 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5609 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005610 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005611 }
5612 }
5613
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005614 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005615}
5616
Eric Laurent3839bc02018-07-10 18:33:34 -07005617int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
5618 audio_stream_type_t srcStream,
5619 audio_stream_type_t dstStream)
5620{
5621 if (srcStream == dstStream) {
5622 return srcIndex;
5623 }
5624 float minSrc = (float)mVolumeCurves->getVolumeIndexMin(srcStream);
5625 float maxSrc = (float)mVolumeCurves->getVolumeIndexMax(srcStream);
5626 float minDst = (float)mVolumeCurves->getVolumeIndexMin(dstStream);
5627 float maxDst = (float)mVolumeCurves->getVolumeIndexMax(dstStream);
5628
5629 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
5630}
5631
Eric Laurente0720872014-03-11 09:30:41 -07005632status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005633 int index,
5634 const sp<AudioOutputDescriptor>& outputDesc,
5635 audio_devices_t device,
5636 int delayMs,
5637 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005638{
Eric Laurente552edb2014-03-10 17:42:56 -07005639 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005640 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005641 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005642 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005643 return NO_ERROR;
5644 }
François Gaffie2110e042015-03-24 08:41:51 +01005645 audio_policy_forced_cfg_t forceUseForComm =
5646 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005647 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005648 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5649 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005650 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005651 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005652 return INVALID_OPERATION;
5653 }
5654
Eric Laurentc75307b2015-03-17 15:29:32 -07005655 if (device == AUDIO_DEVICE_NONE) {
5656 device = outputDesc->device();
5657 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005658
Eric Laurentffbc80f2015-03-18 18:30:19 -07005659 float volumeDb = computeVolume(stream, index, device);
HW Leeda7581e2018-05-22 18:31:34 +08005660 if (outputDesc->isFixedVolume(device) ||
5661 // Force VoIP volume to max for bluetooth SCO
5662 ((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
5663 (device & AUDIO_DEVICE_OUT_ALL_SCO) != 0)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005664 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005665 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005666
Eric Laurentffbc80f2015-03-18 18:30:19 -07005667 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005668
Eric Laurent3b73df72014-03-11 09:06:29 -07005669 if (stream == AUDIO_STREAM_VOICE_CALL ||
5670 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005671 float voiceVolume;
5672 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005673 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurent3839bc02018-07-10 18:33:34 -07005674 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005675 } else {
5676 voiceVolume = 1.0;
5677 }
5678
Eric Laurent18fba842016-03-31 14:41:26 -07005679 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005680 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5681 mLastVoiceVolume = voiceVolume;
5682 }
5683 }
5684
5685 return NO_ERROR;
5686}
5687
Eric Laurentc75307b2015-03-17 15:29:32 -07005688void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5689 audio_devices_t device,
5690 int delayMs,
5691 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005692{
Eric Laurentc75307b2015-03-17 15:29:32 -07005693 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005694
Eric Laurent794fde22016-03-11 09:50:45 -08005695 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005696 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005697 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005698 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005699 device,
5700 delayMs,
5701 force);
5702 }
5703}
5704
Eric Laurente0720872014-03-11 09:30:41 -07005705void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005706 bool on,
5707 const sp<AudioOutputDescriptor>& outputDesc,
5708 int delayMs,
5709 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005710{
Eric Laurent72249d52015-06-08 11:12:15 -07005711 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5712 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005713 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005714 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005715 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005716 }
5717 }
5718}
5719
Eric Laurente0720872014-03-11 09:30:41 -07005720void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005721 bool on,
5722 const sp<AudioOutputDescriptor>& outputDesc,
5723 int delayMs,
5724 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005725{
Eric Laurente552edb2014-03-10 17:42:56 -07005726 if (device == AUDIO_DEVICE_NONE) {
5727 device = outputDesc->device();
5728 }
5729
Eric Laurentc75307b2015-03-17 15:29:32 -07005730 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5731 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005732
5733 if (on) {
5734 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005735 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005736 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005737 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005738 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005739 }
5740 }
5741 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5742 outputDesc->mMuteCount[stream]++;
5743 } else {
5744 if (outputDesc->mMuteCount[stream] == 0) {
5745 ALOGV("setStreamMute() unmuting non muted stream!");
5746 return;
5747 }
5748 if (--outputDesc->mMuteCount[stream] == 0) {
5749 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005750 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005751 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005752 device,
5753 delayMs);
5754 }
5755 }
5756}
5757
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005758audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5759{
5760 // flags to stream type mapping
5761 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5762 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5763 }
5764 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5765 return AUDIO_STREAM_BLUETOOTH_SCO;
5766 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005767 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5768 return AUDIO_STREAM_TTS;
5769 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005770
Ari Hausman-Cohen5c00d012018-06-26 17:09:11 -07005771 return audio_usage_to_stream_type(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005772}
Eric Laurente83b55d2014-11-14 10:06:21 -08005773
François Gaffie53615e22015-03-19 09:24:12 +01005774bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5775{
Eric Laurente83b55d2014-11-14 10:06:21 -08005776 // has flags that map to a strategy?
5777 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5778 return true;
5779 }
5780
5781 // has known usage?
5782 switch (paa->usage) {
5783 case AUDIO_USAGE_UNKNOWN:
5784 case AUDIO_USAGE_MEDIA:
5785 case AUDIO_USAGE_VOICE_COMMUNICATION:
5786 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5787 case AUDIO_USAGE_ALARM:
5788 case AUDIO_USAGE_NOTIFICATION:
5789 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5790 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5791 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5792 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5793 case AUDIO_USAGE_NOTIFICATION_EVENT:
5794 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5795 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5796 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5797 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005798 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005799 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005800 break;
5801 default:
5802 return false;
5803 }
5804 return true;
5805}
5806
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005807bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005808 routing_strategy strategy, uint32_t inPastMs,
5809 nsecs_t sysTime) const
5810{
5811 if ((sysTime == 0) && (inPastMs != 0)) {
5812 sysTime = systemTime();
5813 }
Eric Laurent794fde22016-03-11 09:50:45 -08005814 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005815 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurent97ac8712018-07-27 18:59:02 -07005816 (STRATEGY_NONE == strategy)) &&
François Gaffiead3183e2015-03-18 16:55:35 +01005817 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5818 return true;
5819 }
5820 }
5821 return false;
5822}
5823
Eric Laurent484e9272018-06-07 17:29:23 -07005824bool AudioPolicyManager::isStrategyActiveOnSameModule(const sp<AudioOutputDescriptor>& outputDesc,
5825 routing_strategy strategy, uint32_t inPastMs,
5826 nsecs_t sysTime) const
5827{
5828 for (size_t i = 0; i < mOutputs.size(); i++) {
5829 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5830 if (outputDesc->sharesHwModuleWith(desc)
5831 && isStrategyActive(desc, strategy, inPastMs, sysTime)) {
5832 return true;
5833 }
5834 }
5835 return false;
5836}
5837
François Gaffie2110e042015-03-24 08:41:51 +01005838audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5839{
5840 return mEngine->getForceUse(usage);
5841}
5842
5843bool AudioPolicyManager::isInCall()
5844{
5845 return isStateInCall(mEngine->getPhoneState());
5846}
5847
5848bool AudioPolicyManager::isStateInCall(int state)
5849{
5850 return is_state_in_call(state);
5851}
5852
Eric Laurentd60560a2015-04-10 11:31:20 -07005853void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5854{
5855 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005856 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5857 if (sourceDesc->srcDevice()->equals(deviceDesc)) {
5858 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->portId());
5859 stopAudioSource(sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005860 }
5861 }
5862
5863 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5864 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5865 bool release = false;
5866 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5867 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5868 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5869 source->ext.device.type == deviceDesc->type()) {
5870 release = true;
5871 }
5872 }
5873 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5874 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5875 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5876 sink->ext.device.type == deviceDesc->type()) {
5877 release = true;
5878 }
5879 }
5880 if (release) {
5881 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5882 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5883 }
5884 }
5885}
5886
Phil Burk09bc4612016-02-24 15:58:15 -08005887// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005888void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5889 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005890 // TODO Set this based on Config properties.
5891 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005892
5893 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5894 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005895 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005896
jiabin81772902018-04-02 17:52:27 -07005897 // If MANUAL, keep the supported surround sound formats as current enabled ones.
5898 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
5899 formats.clear();
5900 for (auto it = mSurroundFormats.begin(); it != mSurroundFormats.end(); it++) {
5901 formats.add(*it);
Phil Burk09bc4612016-02-24 15:58:15 -08005902 }
jiabin81772902018-04-02 17:52:27 -07005903 // Always enable IEC61937 when in MANUAL mode.
5904 formats.add(AUDIO_FORMAT_IEC61937);
5905 } else { // NEVER, AUTO or ALWAYS
5906 // Analyze original support for various formats.
5907 bool supportsAC3 = false;
5908 bool supportsOtherSurround = false;
5909 bool supportsIEC61937 = false;
5910 mSurroundFormats.clear();
5911 for (ssize_t formatIndex = 0; formatIndex < (ssize_t)formats.size(); formatIndex++) {
5912 audio_format_t format = formats[formatIndex];
5913 switch (format) {
5914 case AUDIO_FORMAT_AC3:
5915 supportsAC3 = true;
5916 break;
5917 case AUDIO_FORMAT_E_AC3:
5918 case AUDIO_FORMAT_DTS:
5919 case AUDIO_FORMAT_DTS_HD:
5920 // If ALWAYS, remove all other surround formats here
5921 // since we will add them later.
5922 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5923 formats.removeAt(formatIndex);
5924 formatIndex--;
5925 }
5926 supportsOtherSurround = true;
5927 break;
5928 case AUDIO_FORMAT_IEC61937:
5929 supportsIEC61937 = true;
5930 break;
5931 default:
5932 break;
5933 }
5934 }
Phil Burk09bc4612016-02-24 15:58:15 -08005935
jiabin81772902018-04-02 17:52:27 -07005936 // Modify formats based on surround preferences.
5937 // If NEVER, remove support for surround formats.
5938 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5939 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5940 // Remove surround sound related formats.
5941 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5942 audio_format_t format = formats[formatIndex];
5943 switch(format) {
5944 case AUDIO_FORMAT_AC3:
5945 case AUDIO_FORMAT_E_AC3:
5946 case AUDIO_FORMAT_DTS:
5947 case AUDIO_FORMAT_DTS_HD:
5948 case AUDIO_FORMAT_IEC61937:
5949 formats.removeAt(formatIndex);
5950 break;
5951 default:
5952 formatIndex++; // keep it
5953 break;
5954 }
5955 }
5956 supportsAC3 = false;
5957 supportsOtherSurround = false;
5958 supportsIEC61937 = false;
5959 }
5960 } else { // AUTO or ALWAYS
5961 // Most TVs support AC3 even if they do not report it in the EDID.
5962 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
5963 && !supportsAC3) {
5964 formats.add(AUDIO_FORMAT_AC3);
5965 supportsAC3 = true;
5966 }
5967
5968 // If ALWAYS, add support for raw surround formats if all are missing.
5969 // This assumes that if any of these formats are reported by the HAL
5970 // then the report is valid and should not be modified.
5971 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5972 formats.add(AUDIO_FORMAT_E_AC3);
5973 formats.add(AUDIO_FORMAT_DTS);
5974 formats.add(AUDIO_FORMAT_DTS_HD);
5975 supportsOtherSurround = true;
5976 }
5977
5978 // Add support for IEC61937 if any raw surround supported.
5979 // The HAL could do this but add it here, just in case.
5980 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
5981 formats.add(AUDIO_FORMAT_IEC61937);
5982 supportsIEC61937 = true;
5983 }
5984
5985 // Add reported surround sound formats to enabled surround formats.
5986 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
Phil Burk07ac1142016-03-25 13:39:29 -07005987 audio_format_t format = formats[formatIndex];
5988 switch(format) {
5989 case AUDIO_FORMAT_AC3:
5990 case AUDIO_FORMAT_E_AC3:
5991 case AUDIO_FORMAT_DTS:
5992 case AUDIO_FORMAT_DTS_HD:
jiabin81772902018-04-02 17:52:27 -07005993 case AUDIO_FORMAT_AAC_LC:
5994 case AUDIO_FORMAT_DOLBY_TRUEHD:
5995 case AUDIO_FORMAT_E_AC3_JOC:
5996 mSurroundFormats.insert(format);
Phil Burk07ac1142016-03-25 13:39:29 -07005997 default:
Phil Burk07ac1142016-03-25 13:39:29 -07005998 break;
5999 }
Phil Burk09bc4612016-02-24 15:58:15 -08006000 }
Phil Burk07ac1142016-03-25 13:39:29 -07006001 }
Phil Burk09bc4612016-02-24 15:58:15 -08006002 }
Phil Burk0709b0a2016-03-31 12:54:57 -07006003}
6004
6005// Modify the list of channel masks supported.
6006void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
6007 ChannelsVector &channelMasks = *channelMasksPtr;
6008 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6009 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
6010
6011 // If NEVER, then remove support for channelMasks > stereo.
6012 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
6013 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
6014 audio_channel_mask_t channelMask = channelMasks[maskIndex];
6015 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
6016 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
6017 channelMasks.removeAt(maskIndex);
6018 } else {
6019 maskIndex++;
6020 }
6021 }
jiabin81772902018-04-02 17:52:27 -07006022 // If ALWAYS or MANUAL, then make sure we at least support 5.1
6023 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
6024 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006025 bool supports5dot1 = false;
6026 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006027 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006028 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
6029 supports5dot1 = true;
6030 break;
6031 }
6032 }
6033 // If not then add 5.1 support.
6034 if (!supports5dot1) {
6035 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
6036 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
6037 }
Phil Burk09bc4612016-02-24 15:58:15 -08006038 }
6039}
6040
Phil Burk00eeb322016-03-31 12:41:00 -07006041void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
6042 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01006043 AudioProfileVector &profiles)
6044{
6045 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07006046
François Gaffie112b0af2015-11-19 16:13:25 +01006047 // Format MUST be checked first to update the list of AudioProfile
6048 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006049 reply = mpClientInterface->getParameters(
6050 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07006051 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006052 AudioParameter repliedParameters(reply);
6053 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006054 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01006055 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
6056 return;
6057 }
Phil Burk09bc4612016-02-24 15:58:15 -08006058 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07006059 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006060 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07006061 }
Phil Burk09bc4612016-02-24 15:58:15 -08006062 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01006063 }
François Gaffie112b0af2015-11-19 16:13:25 +01006064
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006065 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08006066 ChannelsVector channelMasks;
6067 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01006068 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07006069 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01006070
6071 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006072 reply = mpClientInterface->getParameters(
6073 ioHandle,
6074 requestedParameters.toString() + ";" +
6075 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01006076 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006077 AudioParameter repliedParameters(reply);
6078 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006079 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006080 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01006081 }
6082 }
6083 if (profiles.hasDynamicChannelsFor(format)) {
6084 reply = mpClientInterface->getParameters(ioHandle,
6085 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07006086 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01006087 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006088 AudioParameter repliedParameters(reply);
6089 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006090 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006091 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07006092 if (device == AUDIO_DEVICE_OUT_HDMI) {
6093 filterSurroundChannelMasks(&channelMasks);
6094 }
François Gaffie112b0af2015-11-19 16:13:25 +01006095 }
6096 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08006097 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006098 }
6099}
Eric Laurentd60560a2015-04-10 11:31:20 -07006100
Mikhail Naganovdc769682018-05-04 15:34:08 -07006101status_t AudioPolicyManager::installPatch(const char *caller,
6102 audio_patch_handle_t *patchHandle,
6103 AudioIODescriptorInterface *ioDescriptor,
6104 const struct audio_patch *patch,
6105 int delayMs)
6106{
6107 ssize_t index = mAudioPatches.indexOfKey(
6108 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6109 *patchHandle : ioDescriptor->getPatchHandle());
6110 sp<AudioPatch> patchDesc;
6111 status_t status = installPatch(
6112 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6113 if (status == NO_ERROR) {
6114 ioDescriptor->setPatchHandle(patchDesc->mHandle);
6115 }
6116 return status;
6117}
6118
6119status_t AudioPolicyManager::installPatch(const char *caller,
6120 ssize_t index,
6121 audio_patch_handle_t *patchHandle,
6122 const struct audio_patch *patch,
6123 int delayMs,
6124 uid_t uid,
6125 sp<AudioPatch> *patchDescPtr)
6126{
6127 sp<AudioPatch> patchDesc;
6128 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6129 if (index >= 0) {
6130 patchDesc = mAudioPatches.valueAt(index);
6131 afPatchHandle = patchDesc->mAfPatchHandle;
6132 }
6133
6134 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6135 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6136 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6137 if (status == NO_ERROR) {
6138 if (index < 0) {
6139 patchDesc = new AudioPatch(patch, uid);
6140 addAudioPatch(patchDesc->mHandle, patchDesc);
6141 } else {
6142 patchDesc->mPatch = *patch;
6143 }
6144 patchDesc->mAfPatchHandle = afPatchHandle;
6145 if (patchHandle) {
6146 *patchHandle = patchDesc->mHandle;
6147 }
6148 nextAudioPortGeneration();
6149 mpClientInterface->onAudioPatchListUpdate();
6150 }
6151 if (patchDescPtr) *patchDescPtr = patchDesc;
6152 return status;
6153}
6154
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006155} // namespace android