blob: 92f6c7970104b3316678fb0fb5a5d4b321981c76 [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 Laurent8fc147b2018-07-22 19:13:55 -0700520 closeSessions(activeDesc, true /*activeOnly*/);
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;
791 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 Laurente83b55d2014-11-14 10:06:21 -0800794 if (attr != NULL) {
795 if (!isValidAttributes(attr)) {
796 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
797 attr->usage, attr->content_type, attr->flags,
798 attr->tags);
799 return BAD_VALUE;
800 }
801 attributes = *attr;
802 } else {
803 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
804 ALOGE("getOutputForAttr(): invalid stream type");
805 return BAD_VALUE;
806 }
807 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700808 }
Eric Laurent20b9ef02016-12-05 11:03:16 -0800809
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700810 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
811 " session %d selectedDeviceId %d",
812 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700813 session, *selectedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700814
Scott Randolph7b1fd232018-06-18 15:33:03 -0700815 // TODO: check for existing client for this port ID
816 if (*portId == AUDIO_PORT_HANDLE_NONE) {
817 *portId = AudioPort::getNextUniqueId();
818 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700819
Scott Randolph7b1fd232018-06-18 15:33:03 -0700820 // First check for explicit routing (eg. setPreferredDevice)
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700821 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -0700822 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800823 deviceDesc = mAvailableOutputDevices.getDeviceFromId(*selectedDeviceId);
Scott Randolph7b1fd232018-06-18 15:33:03 -0700824 } else {
825 // If no explict route, is there a matching dynamic policy that applies?
826 sp<SwAudioOutputDescriptor> desc;
827 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
828 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
829 if (!audio_has_proportional_frames(config->format)) {
830 return BAD_VALUE;
831 }
832 *stream = streamTypefromAttributesInt(&attributes);
833 *output = desc->mIoHandle;
834 ALOGV("getOutputForAttr() returns output %d", *output);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700835 goto exit;
Scott Randolph7b1fd232018-06-18 15:33:03 -0700836 }
837
838 // Virtual sources must always be dynamicaly or explicitly routed
839 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
840 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
841 return BAD_VALUE;
842 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700843 }
Scott Randolph7b1fd232018-06-18 15:33:03 -0700844
845 // Virtual sources must always be dynamicaly or explicitly routed
846 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
847 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
848 return BAD_VALUE;
849 }
850
851 *stream = streamTypefromAttributesInt(&attributes);
852
853 // TODO: Should this happen only if an explicit route is active?
854 // the previous code structure meant that this would always happen which
855 // would appear to result in adding a null deviceDesc when not using an
856 // explicit route. Is that the intended and necessary behavior?
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700857 mOutputRoutes.addRoute(session, *stream, SessionRoute::SOURCE_TYPE_NA, deviceDesc, uid);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700858
Eric Laurent8fc147b2018-07-22 19:13:55 -0700859 strategy = (routing_strategy) getStrategyForAttr(&attributes);
860 device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700861
Eric Laurente83b55d2014-11-14 10:06:21 -0800862 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200863 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -0700864 }
865
Nadav Barb2f18162018-07-18 13:01:53 +0300866 // Set incall music only if device was explicitly set, and fallback to the device which is
867 // chosen by the engine if not.
868 // FIXME: provide a more generic approach which is not device specific and move this back
869 // to getOutputForDevice.
870 if (device == AUDIO_DEVICE_OUT_TELEPHONY_TX &&
871 *stream == AUDIO_STREAM_MUSIC &&
872 audio_is_linear_pcm(config->format) &&
873 isInCall()) {
874 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
875 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
876 } else {
877 device = mEngine->getDeviceForStrategy(strategy);
878 }
879 }
880
Glenn Kasten49f36ba2017-12-06 13:02:02 -0800881 ALOGV("getOutputForAttr() device 0x%x, sampling rate %d, format %#x, channel mask %#x, "
882 "flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +0200883 device, config->sample_rate, config->format, config->channel_mask, *flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700884
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100885 *output = AUDIO_IO_HANDLE_NONE;
886 if (msdDevice != AUDIO_DEVICE_NONE) {
887 *output = getOutputForDevice(msdDevice, session, *stream, config, flags);
888 if (*output != AUDIO_IO_HANDLE_NONE && setMsdPatch(device) == NO_ERROR) {
889 ALOGV("%s() Using MSD device 0x%x instead of device 0x%x",
890 __func__, msdDevice, device);
891 device = msdDevice;
892 } else {
893 *output = AUDIO_IO_HANDLE_NONE;
894 }
895 }
896 if (*output == AUDIO_IO_HANDLE_NONE) {
897 *output = getOutputForDevice(device, session, *stream, config, flags);
898 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800899 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700900 mOutputRoutes.removeRoute(session);
Eric Laurente83b55d2014-11-14 10:06:21 -0800901 return INVALID_OPERATION;
902 }
Paul McLeanaa981192015-03-21 09:55:15 -0700903
Eric Laurent8fc147b2018-07-22 19:13:55 -0700904 outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -0700905 *selectedDeviceId = outputDevices.size() > 0 ? outputDevices.itemAt(0)->getId()
906 : AUDIO_PORT_HANDLE_NONE;
907
Eric Laurent8fc147b2018-07-22 19:13:55 -0700908exit:
909 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
910 .format = config->format,
911 .channel_mask = config->channel_mask };
912 sp<TrackClientDescriptor> clientDesc =
913 new TrackClientDescriptor(*portId, uid, session,
914 attributes, clientConfig, requestedDeviceId, *stream, *flags);
915 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
916 outputDesc->clients().emplace(*portId, clientDesc);
917
918 ALOGV(" getOutputForAttr() returns output %d selectedDeviceId %d for port ID %d",
919 *output, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -0700920
Eric Laurente83b55d2014-11-14 10:06:21 -0800921 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700922}
923
924audio_io_handle_t AudioPolicyManager::getOutputForDevice(
925 audio_devices_t device,
Kevin Rocard169753c2017-03-06 14:18:23 -0800926 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700927 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -0800928 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200929 audio_output_flags_t *flags)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700930{
Andy Hungc88b0642018-04-27 15:42:35 -0700931 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700932 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700933
Eric Laurente552edb2014-03-10 17:42:56 -0700934 // open a direct output if required by specified parameters
935 //force direct flag if offload flag is set: offloading implies a direct output stream
936 // and all common behaviors are driven by checking only the direct flag
937 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +0200938 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
939 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700940 }
Nadav Bar766fb022018-01-07 12:18:03 +0200941 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
942 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -0700943 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800944 // only allow deep buffering for music stream type
945 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +0200946 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700947 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +0200948 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700949 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
950 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +0200951 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800952 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700953 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +0200954 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700955 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Eric Laurentfe231122017-11-17 17:48:06 -0800956 audio_is_linear_pcm(config->format)) {
Nadav Bar766fb022018-01-07 12:18:03 +0200957 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700958 AUDIO_OUTPUT_FLAG_DIRECT);
959 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700960 }
Eric Laurente552edb2014-03-10 17:42:56 -0700961
Nadav Bar766fb022018-01-07 12:18:03 +0200962
Eric Laurentb732cf52014-09-24 19:08:21 -0700963 sp<IOProfile> profile;
964
965 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700966 // and not explicitly requested
Nadav Bar766fb022018-01-07 12:18:03 +0200967 if (((*flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Eric Laurentfe231122017-11-17 17:48:06 -0800968 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
969 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
Eric Laurentb732cf52014-09-24 19:08:21 -0700970 goto non_direct_output;
971 }
972
Andy Hung2ddee192015-12-18 17:34:44 -0800973 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
974 // This prevents creating an offloaded track and tearing it down immediately after start
975 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700976 // FIXME: We should check the audio session here but we do not have it in this context.
977 // This may prevent offloading in rare situations where effects are left active by apps
978 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700979
Nadav Bar766fb022018-01-07 12:18:03 +0200980 if (((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800981 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700982 profile = getProfileForDirectOutput(device,
Eric Laurentfe231122017-11-17 17:48:06 -0800983 config->sample_rate,
984 config->format,
985 config->channel_mask,
Nadav Bar766fb022018-01-07 12:18:03 +0200986 (audio_output_flags_t)*flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700987 }
988
Eric Laurent1c333e22014-05-20 10:48:17 -0700989 if (profile != 0) {
Andy Hungc88b0642018-04-27 15:42:35 -0700990 // exclusive outputs for MMAP and Offload are enforced by different session ids.
991 for (size_t i = 0; i < mOutputs.size(); i++) {
992 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
993 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
994 // reuse direct output if currently open by the same client
995 // and configured with same parameters
996 if ((config->sample_rate == desc->mSamplingRate) &&
Andy Hung5659ed52018-04-30 10:31:26 -0700997 (config->format == desc->mFormat) &&
Andy Hungc88b0642018-04-27 15:42:35 -0700998 (config->channel_mask == desc->mChannelMask) &&
999 (session == desc->mDirectClientSession)) {
1000 desc->mDirectOpenCount++;
1001 ALOGI("getOutputForDevice() reusing direct output %d for session %d",
1002 mOutputs.keyAt(i), session);
1003 return mOutputs.keyAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001004 }
1005 }
1006 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08001007
1008 if (!profile->canOpenNewIo()) {
1009 goto non_direct_output;
Eric Laurente552edb2014-03-10 17:42:56 -07001010 }
Eric Laurent861a6282015-05-18 15:40:16 -07001011
Eric Laurent3974e3b2017-12-07 17:58:43 -08001012 sp<SwAudioOutputDescriptor> outputDesc =
1013 new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurent53b810e2017-12-10 17:25:10 -08001014
Mikhail Naganov708e0382018-05-30 09:53:04 -07001015 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -08001016 String8 address = outputDevices.size() > 0 ? outputDevices.itemAt(0)->mAddress
1017 : String8("");
1018
Nadav Bar766fb022018-01-07 12:18:03 +02001019 status = outputDesc->open(config, device, address, stream, *flags, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07001020
1021 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001022 if (status != NO_ERROR ||
Eric Laurentfe231122017-11-17 17:48:06 -08001023 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
Andy Hung5659ed52018-04-30 10:31:26 -07001024 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->mFormat) ||
Eric Laurentfe231122017-11-17 17:48:06 -08001025 (config->channel_mask != 0 && config->channel_mask != outputDesc->mChannelMask)) {
1026 ALOGV("getOutputForDevice() failed opening direct output: output %d sample rate %d %d,"
1027 "format %d %d, channel mask %04x %04x", output, config->sample_rate,
1028 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
1029 config->channel_mask, outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001030 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001031 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07001032 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001033 // fall back to mixer output if possible when the direct output could not be open
Eric Laurentfe231122017-11-17 17:48:06 -08001034 if (audio_is_linear_pcm(config->format) &&
1035 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -08001036 goto non_direct_output;
1037 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001038 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001039 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001040 outputDesc->mRefCount[stream] = 0;
1041 outputDesc->mStopTime[stream] = 0;
1042 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -08001043 outputDesc->mDirectClientSession = session;
1044
Eric Laurente552edb2014-03-10 17:42:56 -07001045 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001046 mPreviousOutputs = mOutputs;
Eric Laurentf4e63452017-11-06 19:31:46 +00001047 ALOGV("getOutputForDevice() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001048 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001049 return output;
1050 }
1051
Eric Laurentb732cf52014-09-24 19:08:21 -07001052non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001053
1054 // A request for HW A/V sync cannot fallback to a mixed output because time
1055 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001056 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001057 return AUDIO_IO_HANDLE_NONE;
1058 }
1059
Eric Laurente552edb2014-03-10 17:42:56 -07001060 // ignoring channel mask due to downmix capability in mixer
1061
1062 // open a non direct output
1063
1064 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001065 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001066 // get which output is suitable for the specified stream. The actual
1067 // routing change will happen when startOutput() will be called
1068 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1069
Eric Laurent8838a382014-09-08 16:44:28 -07001070 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001071 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1072 output = selectOutput(outputs, *flags, config->format);
Eric Laurente552edb2014-03-10 17:42:56 -07001073 }
Eric Laurentf4e63452017-11-06 19:31:46 +00001074 ALOGW_IF((output == 0), "getOutputForDevice() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001075 "sampling rate %d, format %#x, channels %#x, flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +02001076 stream, config->sample_rate, config->format, config->channel_mask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001077
Eric Laurente552edb2014-03-10 17:42:56 -07001078 return output;
1079}
1080
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001081sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
1082 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1083 if (msdModule != 0) {
1084 DeviceVector msdInputDevices = mAvailableInputDevices.getDevicesFromHwModule(
1085 msdModule->getHandle());
1086 if (!msdInputDevices.isEmpty()) return msdInputDevices.itemAt(0);
1087 }
1088 return 0;
1089}
1090
1091audio_devices_t AudioPolicyManager::getMsdAudioOutDeviceTypes() const {
1092 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1093 if (msdModule != 0) {
1094 return mAvailableOutputDevices.getDeviceTypesFromHwModule(msdModule->getHandle());
1095 }
1096 return AUDIO_DEVICE_NONE;
1097}
1098
1099const AudioPatchCollection AudioPolicyManager::getMsdPatches() const {
1100 AudioPatchCollection msdPatches;
1101 audio_module_handle_t msdModuleHandle = mHwModules.getModuleFromName(
1102 AUDIO_HARDWARE_MODULE_ID_MSD)->getHandle();
1103 if (msdModuleHandle == AUDIO_MODULE_HANDLE_NONE) return msdPatches;
1104 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1105 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1106 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1107 const struct audio_port_config *source = &patch->mPatch.sources[j];
1108 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1109 source->ext.device.hw_module == msdModuleHandle) {
1110 msdPatches.addAudioPatch(patch->mHandle, patch);
1111 }
1112 }
1113 }
1114 return msdPatches;
1115}
1116
1117status_t AudioPolicyManager::getBestMsdAudioProfileFor(audio_devices_t outputDevice,
1118 bool hwAvSync, audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1119{
1120 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1121 if (msdModule == nullptr) {
1122 ALOGE("%s() unable to get MSD module", __func__);
1123 return NO_INIT;
1124 }
1125 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(outputDevice);
1126 if (deviceModule == nullptr) {
1127 ALOGE("%s() unable to get module for %#x", __func__, outputDevice);
1128 return NO_INIT;
1129 }
1130 const InputProfileCollection &inputProfiles = msdModule->getInputProfiles();
1131 if (inputProfiles.isEmpty()) {
1132 ALOGE("%s() no input profiles for MSD module", __func__);
1133 return NO_INIT;
1134 }
1135 const OutputProfileCollection &outputProfiles = deviceModule->getOutputProfiles();
1136 if (outputProfiles.isEmpty()) {
1137 ALOGE("%s() no output profiles for device %#x", __func__, outputDevice);
1138 return NO_INIT;
1139 }
1140 AudioProfileVector msdProfiles;
1141 // Each IOProfile represents a MixPort from audio_policy_configuration.xml
1142 for (const auto &inProfile : inputProfiles) {
1143 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0)) {
1144 msdProfiles.appendVector(inProfile->getAudioProfiles());
1145 }
1146 }
1147 AudioProfileVector deviceProfiles;
1148 for (const auto &outProfile : outputProfiles) {
1149 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0)) {
1150 deviceProfiles.appendVector(outProfile->getAudioProfiles());
1151 }
1152 }
1153 struct audio_config_base bestSinkConfig;
1154 status_t result = msdProfiles.findBestMatchingOutputConfig(deviceProfiles,
1155 compressedFormatsOrder, surroundChannelMasksOrder, true /*preferHigherSamplingRates*/,
1156 &bestSinkConfig);
1157 if (result != NO_ERROR) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001158 ALOGD("%s() no matching profiles found for device: %#x, hwAvSync: %d",
1159 __func__, outputDevice, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001160 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001161 }
1162 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1163 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1164 sinkConfig->format = bestSinkConfig.format;
1165 // For encoded streams force direct flag to prevent downstream mixing.
1166 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1167 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
1168 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1169 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1170 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1171 sourceConfig->format = bestSinkConfig.format;
1172 // Copy input stream directly without any processing (e.g. resampling).
1173 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1174 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1175 if (hwAvSync) {
1176 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1177 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1178 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1179 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1180 }
1181 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1182 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1183 sinkConfig->config_mask |= config_mask;
1184 sourceConfig->config_mask |= config_mask;
1185 return NO_ERROR;
1186}
1187
1188PatchBuilder AudioPolicyManager::buildMsdPatch(audio_devices_t outputDevice) const
1189{
1190 PatchBuilder patchBuilder;
1191 patchBuilder.addSource(getMsdAudioInDevice()).
1192 addSink(findDevice(mAvailableOutputDevices, outputDevice));
1193 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1194 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
1195 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1196 // For now, we just forcefully try with HwAvSync first.
1197 status_t res = getBestMsdAudioProfileFor(outputDevice, true /*hwAvSync*/,
1198 &sourceConfig, &sinkConfig) == NO_ERROR ? NO_ERROR :
1199 getBestMsdAudioProfileFor(
1200 outputDevice, false /*hwAvSync*/, &sourceConfig, &sinkConfig);
1201 if (res == NO_ERROR) {
1202 // Found a matching profile for encoded audio. Re-create PatchBuilder with this config.
1203 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1204 }
1205 ALOGV("%s() no matching profile found. Fall through to default PCM patch"
1206 " supporting PCM format conversion.", __func__);
1207 return patchBuilder;
1208}
1209
1210status_t AudioPolicyManager::setMsdPatch(audio_devices_t outputDevice) {
1211 ALOGV("%s() for outputDevice %#x", __func__, outputDevice);
1212 if (outputDevice == AUDIO_DEVICE_NONE) {
1213 // Use media strategy for unspecified output device. This should only
1214 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1215 // therefore invalidate explicit routing requests.
1216 outputDevice = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
1217 }
1218 PatchBuilder patchBuilder = buildMsdPatch(outputDevice);
1219 const struct audio_patch* patch = patchBuilder.patch();
1220 const AudioPatchCollection msdPatches = getMsdPatches();
1221 if (!msdPatches.isEmpty()) {
1222 LOG_ALWAYS_FATAL_IF(msdPatches.size() > 1,
1223 "The current MSD prototype only supports one output patch");
1224 sp<AudioPatch> currentPatch = msdPatches.valueAt(0);
1225 if (audio_patches_are_equal(&currentPatch->mPatch, patch)) {
1226 return NO_ERROR;
1227 }
1228 releaseAudioPatch(currentPatch->mHandle, mUidCached);
1229 }
1230 status_t status = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1231 patch, 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1232 ALOGE_IF(status != NO_ERROR, "%s() error %d creating MSD audio patch", __func__, status);
1233 ALOGI_IF(status == NO_ERROR, "%s() Patch created from MSD_IN to "
1234 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__, outputDevice,
1235 patch->sources[0].format, patch->sources[0].channel_mask, patch->sources[0].sample_rate);
1236 return status;
1237}
1238
Eric Laurente0720872014-03-11 09:30:41 -07001239audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001240 audio_output_flags_t flags,
1241 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001242{
1243 // select one output among several that provide a path to a particular device or set of
1244 // devices (the list was previously build by getOutputsForDevice()).
1245 // The priority is as follows:
1246 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001247 // 2: the output with the bit depth the closest to the requested one
1248 // 3: the primary output
1249 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001250
1251 if (outputs.size() == 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001252 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001253 }
1254 if (outputs.size() == 1) {
1255 return outputs[0];
1256 }
1257
1258 int maxCommonFlags = 0;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001259 audio_io_handle_t outputForFlags = AUDIO_IO_HANDLE_NONE;
1260 audio_io_handle_t outputForPrimary = AUDIO_IO_HANDLE_NONE;
1261 audio_io_handle_t outputForFormat = AUDIO_IO_HANDLE_NONE;
Eric Laurente6930022016-02-11 10:20:40 -08001262 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1263 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001264
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001265 for (audio_io_handle_t output : outputs) {
1266 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001267 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001268 // if a valid format is specified, skip output if not compatible
1269 if (format != AUDIO_FORMAT_INVALID) {
1270 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Andy Hung5659ed52018-04-30 10:31:26 -07001271 if (format != outputDesc->mFormat) {
Eric Laurent8838a382014-09-08 16:44:28 -07001272 continue;
1273 }
1274 } else if (!audio_is_linear_pcm(format)) {
1275 continue;
1276 }
Eric Laurente6930022016-02-11 10:20:40 -08001277 if (AudioPort::isBetterFormatMatch(
1278 outputDesc->mFormat, bestFormat, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001279 outputForFormat = output;
Eric Laurente6930022016-02-11 10:20:40 -08001280 bestFormat = outputDesc->mFormat;
1281 }
Eric Laurent8838a382014-09-08 16:44:28 -07001282 }
1283
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001284 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001285 if (commonFlags >= maxCommonFlags) {
1286 if (commonFlags == maxCommonFlags) {
Andy Hungc9901522017-11-10 20:07:54 -08001287 if (format != AUDIO_FORMAT_INVALID
1288 && AudioPort::isBetterFormatMatch(
1289 outputDesc->mFormat, bestFormatForFlags, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001290 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001291 bestFormatForFlags = outputDesc->mFormat;
1292 }
1293 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001294 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001295 maxCommonFlags = commonFlags;
1296 bestFormatForFlags = outputDesc->mFormat;
1297 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001298 ALOGV("selectOutput() commonFlags for output %d, %04x", output, commonFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001299 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001300 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001301 outputForPrimary = output;
Eric Laurente552edb2014-03-10 17:42:56 -07001302 }
1303 }
1304 }
1305
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001306 if (outputForFlags != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001307 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001308 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001309 if (outputForFormat != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001310 return outputForFormat;
1311 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001312 if (outputForPrimary != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001313 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001314 }
1315
1316 return outputs[0];
1317}
1318
Eric Laurent8fc147b2018-07-22 19:13:55 -07001319status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001320{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001321 ALOGV("%s portId %d", __FUNCTION__, portId);
1322
1323 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1324 if (outputDesc == 0) {
1325 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001326 return BAD_VALUE;
1327 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001328 sp<TrackClientDescriptor> client = outputDesc->clients()[portId];
1329 audio_stream_type_t stream = client->stream();
1330 audio_session_t session = client->session();
Eric Laurente552edb2014-03-10 17:42:56 -07001331
Eric Laurent8fc147b2018-07-22 19:13:55 -07001332 ALOGV("startOutput() output %d, stream %d, session %d",
1333 outputDesc->mIoHandle, stream, session);
Eric Laurentc75307b2015-03-17 15:29:32 -07001334
Eric Laurent733ce942017-12-07 12:18:25 -08001335 status_t status = outputDesc->start();
1336 if (status != NO_ERROR) {
1337 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001338 }
1339
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001340 // Routing?
1341 mOutputRoutes.incRouteActivity(session);
1342
Eric Laurentc75307b2015-03-17 15:29:32 -07001343 audio_devices_t newDevice;
Eric Laurentc40d9692016-04-13 19:14:13 -07001344 AudioMix *policyMix = NULL;
1345 const char *address = NULL;
Eric Laurentc75307b2015-03-17 15:29:32 -07001346 if (outputDesc->mPolicyMix != NULL) {
Eric Laurentc40d9692016-04-13 19:14:13 -07001347 policyMix = outputDesc->mPolicyMix;
1348 address = policyMix->mDeviceAddress.string();
1349 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1350 newDevice = policyMix->mDeviceType;
1351 } else {
1352 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1353 }
Eric Laurent2157f5b2018-04-25 18:33:02 -07001354 } else if (mOutputRoutes.getAndClearRouteChanged(session)) {
Eric Laurent493404d2015-04-21 15:07:36 -07001355 newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurentf3a5a602018-05-22 18:42:55 -07001356 if (newDevice != outputDesc->device()) {
Eric Laurent8fc147b2018-07-22 19:13:55 -07001357 checkStrategyRoute(getStrategy(stream), outputDesc->mIoHandle);
Eric Laurentf3a5a602018-05-22 18:42:55 -07001358 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001359 } else {
1360 newDevice = AUDIO_DEVICE_NONE;
1361 }
1362
1363 uint32_t delayMs = 0;
1364
Eric Laurent733ce942017-12-07 12:18:25 -08001365 status = startSource(outputDesc, stream, newDevice, address, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001366
1367 if (status != NO_ERROR) {
1368 mOutputRoutes.decRouteActivity(session);
Eric Laurent733ce942017-12-07 12:18:25 -08001369 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001370 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001371 }
1372 // Automatically enable the remote submix input when output is started on a re routing mix
1373 // of type MIX_TYPE_RECORDERS
Eric Laurentc40d9692016-04-13 19:14:13 -07001374 if (audio_is_remote_submix_device(newDevice) && policyMix != NULL &&
1375 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001376 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1377 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Eric Laurentc40d9692016-04-13 19:14:13 -07001378 address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001379 "remote-submix");
1380 }
1381
1382 if (delayMs != 0) {
1383 usleep(delayMs * 1000);
1384 }
1385
1386 return status;
1387}
1388
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001389status_t AudioPolicyManager::startSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurentc75307b2015-03-17 15:29:32 -07001390 audio_stream_type_t stream,
1391 audio_devices_t device,
Eric Laurentc40d9692016-04-13 19:14:13 -07001392 const char *address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001393 uint32_t *delayMs)
1394{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001395 // cannot start playback of STREAM_TTS if any other output is being used
1396 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001397
1398 *delayMs = 0;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001399 if (stream == AUDIO_STREAM_TTS) {
1400 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001401 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001402 return INVALID_OPERATION;
1403 } else {
1404 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1405 }
1406 } else {
1407 // some playback other than beacon starts
1408 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1409 }
1410
Eric Laurent77305a62016-07-25 16:39:22 -07001411 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001412 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001413 bool force = !outputDesc->isActive() &&
1414 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001415
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001416 // requiresMuteCheck is false when we can bypass mute strategy.
1417 // It covers a common case when there is no materially active audio
1418 // and muting would result in unnecessary delay and dropped audio.
1419 const uint32_t outputLatencyMs = outputDesc->latency();
1420 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1421
Eric Laurente552edb2014-03-10 17:42:56 -07001422 // increment usage count for this stream on the requested output:
1423 // NOTE that the usage count is the same for duplicated output and hardware output which is
1424 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1425 outputDesc->changeRefCount(stream, 1);
1426
Eric Laurent36829f92017-04-07 19:04:42 -07001427 if (stream == AUDIO_STREAM_MUSIC) {
1428 selectOutputForMusicEffects();
1429 }
1430
Eric Laurent493404d2015-04-21 15:07:36 -07001431 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001432 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001433 if (device == AUDIO_DEVICE_NONE) {
1434 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001435 }
Eric Laurent36829f92017-04-07 19:04:42 -07001436
Eric Laurente552edb2014-03-10 17:42:56 -07001437 routing_strategy strategy = getStrategy(stream);
1438 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001439 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1440 (beaconMuteLatency > 0);
1441 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001442 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001443 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001444 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001445 // An output has a shared device if
1446 // - managed by the same hw module
1447 // - supports the currently selected device
1448 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
1449 && (desc->supportedDevices() & device) != AUDIO_DEVICE_NONE;
1450
Eric Laurent77305a62016-07-25 16:39:22 -07001451 // force a device change if any other output is:
1452 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001453 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001454 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001455 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001456 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001457 // change the device currently selected by the other output.
1458 if (sharedDevice &&
Eric Laurent77305a62016-07-25 16:39:22 -07001459 desc->device() != device &&
Eric Laurent77305a62016-07-25 16:39:22 -07001460 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001461 force = true;
1462 }
1463 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001464 // a notification so that audio focus effect can propagate, or that a mute/unmute
1465 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001466 const uint32_t latencyMs = desc->latency();
1467 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1468
1469 if (shouldWait && isActive && (waitMs < latencyMs)) {
1470 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001471 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001472
1473 // Require mute check if another output is on a shared device
1474 // and currently active to have proper drain and avoid pops.
1475 // Note restoring AudioTracks onto this output needs to invoke
1476 // a volume ramp if there is no mute.
1477 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001478 }
1479 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001480
1481 const uint32_t muteWaitMs =
1482 setOutputDevice(outputDesc, device, force, 0, NULL, address, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001483
Eric Laurente552edb2014-03-10 17:42:56 -07001484 // apply volume rules for current stream and device if necessary
1485 checkAndSetVolume(stream,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001486 mVolumeCurves->getVolumeIndex(stream, outputDesc->device()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001487 outputDesc,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001488 outputDesc->device());
Eric Laurente552edb2014-03-10 17:42:56 -07001489
1490 // update the outputs if starting an output with a stream that can affect notification
1491 // routing
1492 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001493
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001494 // force reevaluating accessibility routing when ringtone or alarm starts
1495 if (strategy == STRATEGY_SONIFICATION) {
1496 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1497 }
Eric Laurentdc462862016-07-19 12:29:53 -07001498
1499 if (waitMs > muteWaitMs) {
1500 *delayMs = waitMs - muteWaitMs;
1501 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001502
1503 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1504 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1505 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1506 // change occurs after the MixerThread starts and causes a stream volume
1507 // glitch.
1508 //
1509 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001510 }
Eric Laurentdc462862016-07-19 12:29:53 -07001511
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001512 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1513 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1514 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1515 }
1516
Tomoharu Kasaharaa81f0982018-01-18 20:55:02 +09001517 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1518 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1519 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1520 }
1521
Eric Laurente552edb2014-03-10 17:42:56 -07001522 return NO_ERROR;
1523}
1524
Eric Laurent8fc147b2018-07-22 19:13:55 -07001525status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001526{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001527 ALOGV("%s portId %d", __FUNCTION__, portId);
1528
1529 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1530 if (outputDesc == 0) {
1531 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001532 return BAD_VALUE;
1533 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001534 sp<TrackClientDescriptor> client = outputDesc->clients()[portId];
1535 audio_stream_type_t stream = client->stream();
1536 audio_session_t session = client->session();
Eric Laurente552edb2014-03-10 17:42:56 -07001537
Eric Laurent8fc147b2018-07-22 19:13:55 -07001538 ALOGV("stopOutput() output %d, stream %d, session %d", outputDesc->mIoHandle, stream, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001539
Eric Laurentc75307b2015-03-17 15:29:32 -07001540 if (outputDesc->mRefCount[stream] == 1) {
1541 // Automatically disable the remote submix input when output is stopped on a
1542 // re routing mix of type MIX_TYPE_RECORDERS
1543 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1544 outputDesc->mPolicyMix != NULL &&
1545 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1546 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1547 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001548 outputDesc->mPolicyMix->mDeviceAddress,
Eric Laurentc75307b2015-03-17 15:29:32 -07001549 "remote-submix");
1550 }
1551 }
1552
1553 // Routing?
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001554 bool forceDeviceUpdate = false;
Eric Laurentc75307b2015-03-17 15:29:32 -07001555 if (outputDesc->mRefCount[stream] > 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001556 int activityCount = mOutputRoutes.decRouteActivity(session);
1557 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1558
1559 if (forceDeviceUpdate) {
1560 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1561 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001562 }
1563
Eric Laurent3974e3b2017-12-07 17:58:43 -08001564 status_t status = stopSource(outputDesc, stream, forceDeviceUpdate);
1565
Eric Laurent733ce942017-12-07 12:18:25 -08001566 if (status == NO_ERROR ) {
1567 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001568 }
1569 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001570}
1571
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001572status_t AudioPolicyManager::stopSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001573 audio_stream_type_t stream,
1574 bool forceDeviceUpdate)
Eric Laurentc75307b2015-03-17 15:29:32 -07001575{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001576 // always handle stream stop, check which stream type is stopping
1577 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1578
Eric Laurente552edb2014-03-10 17:42:56 -07001579 if (outputDesc->mRefCount[stream] > 0) {
1580 // decrement usage count of this stream on the output
1581 outputDesc->changeRefCount(stream, -1);
Paul McLeanaa981192015-03-21 09:55:15 -07001582
Eric Laurente552edb2014-03-10 17:42:56 -07001583 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001584 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001585 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001586 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001587 // delay the device switch by twice the latency because stopOutput() is executed when
1588 // the track stop() command is received and at that time the audio track buffer can
1589 // still contain data that needs to be drained. The latency only covers the audio HAL
1590 // and kernel buffers. Also the latency does not always include additional delay in the
1591 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001592 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001593
1594 // force restoring the device selection on other active outputs if it differs from the
1595 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001596 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001597 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001598 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001599 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001600 desc->isActive() &&
1601 outputDesc->sharesHwModuleWith(desc) &&
1602 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001603 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1604 bool force = desc->device() != newDevice2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001605
Eric Laurentc75307b2015-03-17 15:29:32 -07001606 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001607 newDevice2,
1608 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001609 delayMs);
1610 // re-apply device specific volume if not done by setOutputDevice()
1611 if (!force) {
1612 applyStreamVolumes(desc, newDevice2, delayMs);
1613 }
Eric Laurente552edb2014-03-10 17:42:56 -07001614 }
1615 }
1616 // update the outputs if stopping one with a stream that can affect notification routing
1617 handleNotificationRoutingForStream(stream);
1618 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001619
1620 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1621 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1622 setStrategyMute(STRATEGY_SONIFICATION, false, outputDesc);
1623 }
1624
Eric Laurent36829f92017-04-07 19:04:42 -07001625 if (stream == AUDIO_STREAM_MUSIC) {
1626 selectOutputForMusicEffects();
1627 }
Eric Laurente552edb2014-03-10 17:42:56 -07001628 return NO_ERROR;
1629 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001630 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001631 return INVALID_OPERATION;
1632 }
1633}
1634
Eric Laurent8fc147b2018-07-22 19:13:55 -07001635void AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001636{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001637 ALOGV("%s portId %d", __FUNCTION__, portId);
1638
1639 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1640 if (outputDesc == 0) {
1641 ALOGW("releaseOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001642 return;
1643 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001644 sp<TrackClientDescriptor> client = outputDesc->clients()[portId];
1645 audio_session_t session = client->session();
1646
1647 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001648
Paul McLeanaa981192015-03-21 09:55:15 -07001649 // Routing
1650 mOutputRoutes.removeRoute(session);
1651
Eric Laurent8fc147b2018-07-22 19:13:55 -07001652 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1653 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001654 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07001655 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001656 return;
1657 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001658 if (--outputDesc->mDirectOpenCount == 0) {
1659 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07001660 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001661 }
1662 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001663 outputDesc->clients().erase(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001664}
1665
1666
Eric Laurentcaf7f482014-11-25 17:50:47 -08001667status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1668 audio_io_handle_t *input,
1669 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001670 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001671 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001672 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001673 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001674 input_type_t *inputType,
1675 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001676{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001677 ALOGV("getInputForAttr() source %d, sampling rate %d, format %#x, channel mask %#x,"
Eric Laurentcaf7f482014-11-25 17:50:47 -08001678 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001679 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001680
Eric Laurentad2e7b92017-09-14 20:06:42 -07001681 status_t status = NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -08001682 // handle legacy remote submix case where the address was not always specified
1683 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001684 audio_source_t halInputSource;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001685 audio_source_t inputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001686 AudioMix *policyMix = NULL;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001687 DeviceVector inputDevices;
Eric Laurent8fc147b2018-07-22 19:13:55 -07001688 sp<AudioInputDescriptor> inputDesc;
1689 sp<RecordClientDescriptor> clientDesc;
1690 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Eric Laurent20b9ef02016-12-05 11:03:16 -08001691
Eric Laurentfe231122017-11-17 17:48:06 -08001692 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1693 inputSource = AUDIO_SOURCE_MIC;
1694 }
1695
Paul McLean466dc8e2015-04-17 13:15:36 -06001696 // Explicit routing?
1697 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -07001698 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
jiabinc0c831a2018-01-29 17:55:15 -08001699 deviceDesc = mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001700 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001701 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
Paul McLean466dc8e2015-04-17 13:15:36 -06001702
Eric Laurentad2e7b92017-09-14 20:06:42 -07001703 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1704 // possible
1705 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1706 *input != AUDIO_IO_HANDLE_NONE) {
1707 ssize_t index = mInputs.indexOfKey(*input);
1708 if (index < 0) {
1709 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1710 status = BAD_VALUE;
1711 goto error;
1712 }
1713 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1714 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1715 if (audioSession == 0) {
1716 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1717 status = BAD_VALUE;
1718 goto error;
1719 }
1720 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1721 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001722 // corresponds to a new client and is only permitted from the same UID.
1723 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurentad2e7b92017-09-14 20:06:42 -07001724 if (audioSession->openCount() == 1) {
1725 audioSession->setUid(uid);
1726 } else if (audioSession->uid() != uid) {
Eric Laurent331679c2018-04-16 17:03:16 -07001727 if (!audioSession->isSilenced()) {
1728 ALOGW("getInputForAttr() bad uid %d for session %d uid %d",
1729 uid, session, audioSession->uid());
1730 status = INVALID_OPERATION;
1731 goto error;
1732 }
1733 audioSession->setUid(uid);
1734 audioSession->setSilenced(false);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001735 }
1736 audioSession->changeOpenCount(1);
1737 *inputType = API_INPUT_LEGACY;
1738 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1739 *portId = AudioPort::getNextUniqueId();
1740 }
Mikhail Naganov708e0382018-05-30 09:53:04 -07001741 inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(inputDesc->mDevice);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001742 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1743 : AUDIO_PORT_HANDLE_NONE;
1744 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
1745
Eric Laurent8fc147b2018-07-22 19:13:55 -07001746 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001747 }
1748
1749 *input = AUDIO_IO_HANDLE_NONE;
1750 *inputType = API_INPUT_INVALID;
1751
Eric Laurentad2e7b92017-09-14 20:06:42 -07001752 halInputSource = inputSource;
1753
1754 // TODO: check for existing client for this port ID
1755 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1756 *portId = AudioPort::getNextUniqueId();
1757 }
1758
1759 audio_devices_t device;
1760
Eric Laurentc447ded2015-01-06 08:47:05 -08001761 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001762 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001763 status = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
1764 if (status != NO_ERROR) {
1765 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001766 }
1767 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001768 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1769 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001770 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001771 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001772 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001773 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001774 status = BAD_VALUE;
1775 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001776 }
Eric Laurentc722f302014-12-10 11:21:49 -08001777 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001778 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001779 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1780 // there is an external policy, but this input is attached to a mix of recorders,
1781 // meaning it receives audio injected into the framework, so the recorder doesn't
1782 // know about it and is therefore considered "legacy"
1783 *inputType = API_INPUT_LEGACY;
1784 } else {
1785 // recording a mix of players defined by an external policy, we're rerouting for
1786 // an external policy
1787 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1788 }
Eric Laurentc722f302014-12-10 11:21:49 -08001789 } else if (audio_is_remote_submix_device(device)) {
1790 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001791 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001792 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1793 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001794 } else {
1795 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001796 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001797
Eric Laurent599c7582015-12-07 18:05:55 -08001798 }
1799
1800 *input = getInputForDevice(device, address, session, uid, inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001801 config, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001802 policyMix);
1803 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001804 status = INVALID_OPERATION;
1805 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001806 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001807
Mikhail Naganov708e0382018-05-30 09:53:04 -07001808 inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -07001809 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1810 : AUDIO_PORT_HANDLE_NONE;
1811
Eric Laurent8fc147b2018-07-22 19:13:55 -07001812exit:
1813 clientDesc = new RecordClientDescriptor(*portId, uid, session,
1814 *attr, *config, requestedDeviceId, inputSource, flags);
1815 inputDesc = mInputs.valueFor(*input);
1816 inputDesc->clients().emplace(*portId, clientDesc);
1817
1818 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
1819 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001820
Eric Laurent599c7582015-12-07 18:05:55 -08001821 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001822
1823error:
1824 mInputRoutes.removeRoute(session);
1825 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001826}
1827
1828
1829audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1830 String8 address,
1831 audio_session_t session,
1832 uid_t uid,
1833 audio_source_t inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001834 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08001835 audio_input_flags_t flags,
1836 AudioMix *policyMix)
1837{
1838 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1839 audio_source_t halInputSource = inputSource;
1840 bool isSoundTrigger = false;
1841
1842 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1843 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1844 if (index >= 0) {
1845 input = mSoundTriggerSessions.valueFor(session);
1846 isSoundTrigger = true;
1847 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1848 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1849 } else {
1850 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001851 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001852 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08001853 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001854 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001855 }
1856
Andy Hungf129b032015-04-07 13:45:50 -07001857 // find a compatible input profile (not necessarily identical in parameters)
1858 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08001859 // sampling rate and flags may be updated by getInputProfile
1860 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
1861 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07001862 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08001863 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07001864 audio_input_flags_t profileFlags = flags;
1865 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07001866 profileFormat = config->format; // reset each time through loop, in case it is updated
Eric Laurent275e8e92014-11-30 15:14:47 -08001867 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001868 profileSamplingRate, profileFormat, profileChannelMask,
1869 profileFlags);
1870 if (profile != 0) {
1871 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001872 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1873 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001874 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1875 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1876 } else { // fail
Glenn Kastenfaa10a62017-05-25 15:52:05 -07001877 ALOGW("getInputForDevice() could not find profile for device 0x%X, "
Eric Laurentfe231122017-11-17 17:48:06 -08001878 "sampling rate %u, format %#x, channel mask 0x%X, flags %#x",
1879 device, config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001880 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001881 }
Eric Laurente552edb2014-03-10 17:42:56 -07001882 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001883 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08001884 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08001885 if (samplingRate == 0) {
1886 samplingRate = profileSamplingRate;
1887 }
Eric Laurente552edb2014-03-10 17:42:56 -07001888
Eric Laurent322b4d22015-04-03 15:57:54 -07001889 if (profile->getModuleHandle() == 0) {
1890 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001891 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001892 }
1893
Eric Laurent599c7582015-12-07 18:05:55 -08001894 sp<AudioSession> audioSession = new AudioSession(session,
Eric Laurentfe231122017-11-17 17:48:06 -08001895 inputSource,
1896 config->format,
1897 samplingRate,
1898 config->channel_mask,
1899 flags,
1900 uid,
Eric Laurenta18dced2018-07-20 15:14:54 -07001901 isSoundTrigger);
Eric Laurent599c7582015-12-07 18:05:55 -08001902
Eric Laurent3974e3b2017-12-07 17:58:43 -08001903 if (!profile->canOpenNewIo()) {
1904 return AUDIO_IO_HANDLE_NONE;
1905 }
1906
Eric Laurentfe231122017-11-17 17:48:06 -08001907 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001908
Eric Laurentfe231122017-11-17 17:48:06 -08001909 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
1910 lConfig.sample_rate = profileSamplingRate;
1911 lConfig.channel_mask = profileChannelMask;
1912 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07001913
Eric Laurent53b810e2017-12-10 17:25:10 -08001914 if (address == "") {
Mikhail Naganov708e0382018-05-30 09:53:04 -07001915 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -08001916 // the inputs vector must be of size >= 1, but we don't want to crash here
1917 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress : String8("");
1918 }
1919
Eric Laurentfe231122017-11-17 17:48:06 -08001920 status_t status = inputDesc->open(&lConfig, device, address,
1921 halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001922
1923 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001924 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08001925 (profileSamplingRate != lConfig.sample_rate) ||
1926 !audio_formats_match(profileFormat, lConfig.format) ||
1927 (profileChannelMask != lConfig.channel_mask)) {
1928 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001929 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08001930 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001931 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001932 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07001933 }
Eric Laurent599c7582015-12-07 18:05:55 -08001934 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001935 }
1936
Eric Laurentc722f302014-12-10 11:21:49 -08001937 inputDesc->mPolicyMix = policyMix;
Eric Laurent599c7582015-12-07 18:05:55 -08001938 inputDesc->addAudioSession(session, audioSession);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001939
Eric Laurent599c7582015-12-07 18:05:55 -08001940 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001941 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001942
Eric Laurent599c7582015-12-07 18:05:55 -08001943 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001944}
1945
Eric Laurentbb948092017-01-23 18:33:30 -08001946//static
1947bool AudioPolicyManager::isConcurrentSource(audio_source_t source)
1948{
1949 return (source == AUDIO_SOURCE_HOTWORD) ||
1950 (source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
1951 (source == AUDIO_SOURCE_FM_TUNER);
1952}
1953
Eric Laurentfb66dd92016-01-28 18:32:03 -08001954bool AudioPolicyManager::isConcurentCaptureAllowed(const sp<AudioInputDescriptor>& inputDesc,
1955 const sp<AudioSession>& audioSession)
1956{
1957 // Do not allow capture if an active voice call is using a software patch and
1958 // the call TX source device is on the same HW module.
1959 // FIXME: would be better to refine to only inputs whose profile connects to the
1960 // call TX device but this information is not in the audio patch
1961 if (mCallTxPatch != 0 &&
1962 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1963 return false;
1964 }
1965
1966 // starting concurrent capture is enabled if:
1967 // 1) capturing for re-routing
1968 // 2) capturing for HOTWORD source
1969 // 3) capturing for FM TUNER source
1970 // 3) All other active captures are either for re-routing or HOTWORD
1971
1972 if (is_virtual_input_device(inputDesc->mDevice) ||
Eric Laurentbb948092017-01-23 18:33:30 -08001973 isConcurrentSource(audioSession->inputSource())) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001974 return true;
1975 }
1976
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001977 for (const auto& activeInput : mInputs.getActiveInputs()) {
Eric Laurentbb948092017-01-23 18:33:30 -08001978 if (!isConcurrentSource(activeInput->inputSource(true)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001979 !is_virtual_input_device(activeInput->mDevice)) {
1980 return false;
1981 }
1982 }
1983
1984 return true;
1985}
1986
Chris Thornton2b864642017-06-27 21:26:07 -07001987// FIXME: remove when concurrent capture is ready. This is a hack to work around bug b/63083537.
1988bool AudioPolicyManager::soundTriggerSupportsConcurrentCapture() {
1989 if (!mHasComputedSoundTriggerSupportsConcurrentCapture) {
1990 bool soundTriggerSupportsConcurrentCapture = false;
1991 unsigned int numModules = 0;
1992 struct sound_trigger_module_descriptor* nModules = NULL;
1993
1994 status_t status = SoundTrigger::listModules(nModules, &numModules);
1995 if (status == NO_ERROR && numModules != 0) {
1996 nModules = (struct sound_trigger_module_descriptor*) calloc(
1997 numModules, sizeof(struct sound_trigger_module_descriptor));
1998 if (nModules == NULL) {
1999 // We failed to malloc the buffer, so just say no for now, and hope that we have more
2000 // ram the next time this function is called.
2001 ALOGE("Failed to allocate buffer for module descriptors");
2002 return false;
2003 }
2004
2005 status = SoundTrigger::listModules(nModules, &numModules);
2006 if (status == NO_ERROR) {
2007 soundTriggerSupportsConcurrentCapture = true;
2008 for (size_t i = 0; i < numModules; ++i) {
2009 soundTriggerSupportsConcurrentCapture &=
2010 nModules[i].properties.concurrent_capture;
2011 }
2012 }
2013 free(nModules);
2014 }
2015 mSoundTriggerSupportsConcurrentCapture = soundTriggerSupportsConcurrentCapture;
2016 mHasComputedSoundTriggerSupportsConcurrentCapture = true;
2017 }
2018 return mSoundTriggerSupportsConcurrentCapture;
2019}
2020
Eric Laurentfb66dd92016-01-28 18:32:03 -08002021
Eric Laurent8fc147b2018-07-22 19:13:55 -07002022status_t AudioPolicyManager::startInput(audio_port_handle_t portId,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002023 bool silenced,
Eric Laurentfb66dd92016-01-28 18:32:03 -08002024 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07002025{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002026 *concurrency = API_INPUT_CONCURRENCY_NONE;
2027
2028 ALOGV("%s portId %d", __FUNCTION__, portId);
2029
2030 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2031 if (inputDesc == 0) {
2032 ALOGW("startInput() no input for client %d", portId);
2033 return BAD_VALUE;
2034 }
2035 sp<RecordClientDescriptor> client = inputDesc->clients()[portId];
2036 audio_session_t session = client->session();
2037 audio_io_handle_t input = inputDesc->mIoHandle;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002038
2039 ALOGV("AudioPolicyManager::startInput(input:%d, session:%d, silenced:%d, concurrency:%d)",
2040 input, session, silenced, *concurrency);
2041
Eric Laurent599c7582015-12-07 18:05:55 -08002042 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
2043 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07002044 ALOGW("startInput() unknown session %d on input %d", session, input);
2045 return BAD_VALUE;
2046 }
2047
Eric Laurent74708e72017-04-07 17:13:42 -07002048 if (!is_virtual_input_device(inputDesc->mDevice)) {
2049 if (mCallTxPatch != 0 &&
2050 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
2051 ALOGW("startInput(%d) failed: call in progress", input);
Ray Essick84e84a52018-05-03 18:45:07 -07002052 *concurrency |= API_INPUT_CONCURRENCY_CALL;
Eric Laurent74708e72017-04-07 17:13:42 -07002053 return INVALID_OPERATION;
2054 }
2055
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002056 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002057
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002058 // If a UID is idle and records silence and another not silenced recording starts
2059 // from another UID (idle or active) we stop the current idle UID recording in
2060 // favor of the new one - "There can be only one" TM
2061 if (!silenced) {
2062 for (const auto& activeDesc : activeInputs) {
2063 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
2064 activeDesc->getId() == inputDesc->getId()) {
2065 continue;
2066 }
2067
2068 AudioSessionCollection activeSessions = activeDesc->getAudioSessions(
2069 true /*activeOnly*/);
2070 sp<AudioSession> activeSession = activeSessions.valueAt(0);
2071 if (activeSession->isSilenced()) {
Eric Laurent8fc147b2018-07-22 19:13:55 -07002072 closeSession(activeDesc, activeSession);
2073 ALOGV("startInput() session %d stopping silenced session %d", session, activeSession->session());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002074 activeInputs = mInputs.getActiveInputs();
2075 }
2076 }
2077 }
2078
2079 for (const auto& activeDesc : activeInputs) {
Eric Laurentcb4dae22017-07-01 19:39:32 -07002080 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
2081 activeDesc->getId() == inputDesc->getId()) {
2082 continue;
2083 }
2084
Eric Laurent74708e72017-04-07 17:13:42 -07002085 audio_source_t activeSource = activeDesc->inputSource(true);
2086 if (audioSession->inputSource() == AUDIO_SOURCE_HOTWORD) {
2087 if (activeSource == AUDIO_SOURCE_HOTWORD) {
2088 if (activeDesc->hasPreemptedSession(session)) {
2089 ALOGW("startInput(%d) failed for HOTWORD: "
2090 "other input %d already started for HOTWORD",
2091 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07002092 *concurrency |= API_INPUT_CONCURRENCY_HOTWORD;
Eric Laurent74708e72017-04-07 17:13:42 -07002093 return INVALID_OPERATION;
2094 }
2095 } else {
2096 ALOGV("startInput(%d) failed for HOTWORD: other input %d already started",
2097 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07002098 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07002099 return INVALID_OPERATION;
2100 }
2101 } else {
2102 if (activeSource != AUDIO_SOURCE_HOTWORD) {
2103 ALOGW("startInput(%d) failed: other input %d already started",
2104 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07002105 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07002106 return INVALID_OPERATION;
2107 }
2108 }
2109 }
2110
Chris Thornton2b864642017-06-27 21:26:07 -07002111 // We only need to check if the sound trigger session supports concurrent capture if the
2112 // input is also a sound trigger input. Otherwise, we should preempt any hotword stream
2113 // that's running.
2114 const bool allowConcurrentWithSoundTrigger =
2115 inputDesc->isSoundTrigger() ? soundTriggerSupportsConcurrentCapture() : false;
2116
Eric Laurent74708e72017-04-07 17:13:42 -07002117 // if capture is allowed, preempt currently active HOTWORD captures
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002118 for (const auto& activeDesc : activeInputs) {
Chris Thornton2b864642017-06-27 21:26:07 -07002119 if (allowConcurrentWithSoundTrigger && activeDesc->isSoundTrigger()) {
2120 continue;
2121 }
2122
Eric Laurent74708e72017-04-07 17:13:42 -07002123 audio_source_t activeSource = activeDesc->inputSource(true);
2124 if (activeSource == AUDIO_SOURCE_HOTWORD) {
2125 AudioSessionCollection activeSessions =
2126 activeDesc->getAudioSessions(true /*activeOnly*/);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002127 sp<AudioSession> activeSession = activeSessions[0];
Eric Laurent74708e72017-04-07 17:13:42 -07002128 SortedVector<audio_session_t> sessions = activeDesc->getPreemptedSessions();
Ray Essick84e84a52018-05-03 18:45:07 -07002129 *concurrency |= API_INPUT_CONCURRENCY_PREEMPT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002130 sessions.add(activeSession->session());
Eric Laurent74708e72017-04-07 17:13:42 -07002131 inputDesc->setPreemptedSessions(sessions);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002132 closeSession(inputDesc, activeSession);
Eric Laurent74708e72017-04-07 17:13:42 -07002133 ALOGV("startInput(%d) for HOTWORD preempting HOTWORD input %d",
2134 input, activeDesc->mIoHandle);
2135 }
2136 }
2137 }
Eric Laurente552edb2014-03-10 17:42:56 -07002138
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002139 // Make sure we start with the correct silence state
2140 audioSession->setSilenced(silenced);
2141
Eric Laurent313d1e72016-01-29 09:56:57 -08002142 // increment activity count before calling getNewInputDevice() below as only active sessions
2143 // are considered for device selection
Eric Laurenta18dced2018-07-20 15:14:54 -07002144 inputDesc->changeRefCount(session, 1);
Eric Laurent313d1e72016-01-29 09:56:57 -08002145
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002146 // Routing?
2147 mInputRoutes.incRouteActivity(session);
2148
Eric Laurent2157f5b2018-04-25 18:33:02 -07002149 if (audioSession->activeCount() == 1 || mInputRoutes.getAndClearRouteChanged(session)) {
Eric Laurent271a93e2016-09-29 14:47:06 -07002150 // indicate active capture to sound trigger service if starting capture from a mic on
2151 // primary HW module
Eric Laurentf7c50102016-09-30 15:19:43 -07002152 audio_devices_t device = getNewInputDevice(inputDesc);
Eric Laurent271a93e2016-09-29 14:47:06 -07002153 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002154
Eric Laurent733ce942017-12-07 12:18:25 -08002155 status_t status = inputDesc->start();
2156 if (status != NO_ERROR) {
2157 mInputRoutes.decRouteActivity(session);
Eric Laurenta18dced2018-07-20 15:14:54 -07002158 inputDesc->changeRefCount(session, -1);
Eric Laurent733ce942017-12-07 12:18:25 -08002159 return status;
2160 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002161
Eric Laurent733ce942017-12-07 12:18:25 -08002162 if (inputDesc->getAudioSessionCount(true/*activeOnly*/) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002163 // if input maps to a dynamic policy with an activity listener, notify of state change
2164 if ((inputDesc->mPolicyMix != NULL)
2165 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2166 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2167 MIX_STATE_MIXING);
Eric Laurentc722f302014-12-10 11:21:49 -08002168 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002169
Eric Laurentf7c50102016-09-30 15:19:43 -07002170 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2171 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Eric Laurent05b345e2016-11-18 12:36:27 -08002172 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002173 SoundTrigger::setCaptureState(true);
2174 }
2175
2176 // automatically enable the remote submix output when input is started if not
2177 // used by a policy mix of type MIX_TYPE_RECORDERS
2178 // For remote submix (a virtual device), we open only one input per capture request.
2179 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2180 String8 address = String8("");
2181 if (inputDesc->mPolicyMix == NULL) {
2182 address = String8("0");
2183 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2184 address = inputDesc->mPolicyMix->mDeviceAddress;
2185 }
2186 if (address != "") {
2187 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2188 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2189 address, "remote-submix");
2190 }
Eric Laurentc722f302014-12-10 11:21:49 -08002191 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002192 }
Eric Laurente552edb2014-03-10 17:42:56 -07002193 }
2194
Eric Laurent599c7582015-12-07 18:05:55 -08002195 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
Eric Laurente552edb2014-03-10 17:42:56 -07002196
Eric Laurente552edb2014-03-10 17:42:56 -07002197 return NO_ERROR;
2198}
2199
Eric Laurent8fc147b2018-07-22 19:13:55 -07002200status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002201{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002202 ALOGV("%s portId %d", __FUNCTION__, portId);
2203
2204 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2205 if (inputDesc == 0) {
2206 ALOGW("stopInput() no input for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002207 return BAD_VALUE;
2208 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002209 sp<RecordClientDescriptor> client = inputDesc->clients()[portId];
2210 audio_session_t session = client->session();
2211 audio_io_handle_t input = inputDesc->mIoHandle;
2212
2213 ALOGV("stopInput() input %d", input);
Eric Laurente552edb2014-03-10 17:42:56 -07002214
Eric Laurent599c7582015-12-07 18:05:55 -08002215 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07002216
Eric Laurent599c7582015-12-07 18:05:55 -08002217 if (audioSession->activeCount() == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002218 ALOGW("stopInput() input %d already stopped", input);
2219 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002220 }
2221
Eric Laurenta18dced2018-07-20 15:14:54 -07002222 inputDesc->changeRefCount(session, -1);
Paul McLean466dc8e2015-04-17 13:15:36 -06002223
2224 // Routing?
2225 mInputRoutes.decRouteActivity(session);
2226
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002227 if (audioSession->activeCount() == 0) {
Eric Laurent733ce942017-12-07 12:18:25 -08002228 inputDesc->stop();
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002229 if (inputDesc->isActive()) {
2230 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2231 } else {
2232 // if input maps to a dynamic policy with an activity listener, notify of state change
2233 if ((inputDesc->mPolicyMix != NULL)
2234 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2235 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2236 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002237 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002238
2239 // automatically disable the remote submix output when input is stopped if not
2240 // used by a policy mix of type MIX_TYPE_RECORDERS
2241 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2242 String8 address = String8("");
2243 if (inputDesc->mPolicyMix == NULL) {
2244 address = String8("0");
2245 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2246 address = inputDesc->mPolicyMix->mDeviceAddress;
2247 }
2248 if (address != "") {
2249 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2250 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2251 address, "remote-submix");
2252 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002253 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002254
Eric Laurentf7c50102016-09-30 15:19:43 -07002255 audio_devices_t device = inputDesc->mDevice;
Eric Laurentfb66dd92016-01-28 18:32:03 -08002256 resetInputDevice(input);
Eric Laurent84332aa2016-01-28 22:19:18 +00002257
Eric Laurentf7c50102016-09-30 15:19:43 -07002258 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2259 // primary HW module
2260 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2261 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2262 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08002263 SoundTrigger::setCaptureState(false);
2264 }
2265 inputDesc->clearPreemptedSessions();
Eric Laurent84332aa2016-01-28 22:19:18 +00002266 }
Eric Laurente552edb2014-03-10 17:42:56 -07002267 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002268 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002269}
2270
Eric Laurent8fc147b2018-07-22 19:13:55 -07002271void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002272{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002273 ALOGV("%s portId %d", __FUNCTION__, portId);
2274
2275 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2276 if (inputDesc == 0) {
2277 ALOGW("releaseInput() no input for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002278 return;
2279 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002280 sp<RecordClientDescriptor> client = inputDesc->clients()[portId];
2281 audio_session_t session = client->session();
2282 audio_io_handle_t input = inputDesc->mIoHandle;
2283
2284 ALOGV("releaseInput() %d", input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002285
2286 // Routing
2287 mInputRoutes.removeRoute(session);
2288
Eric Laurent599c7582015-12-07 18:05:55 -08002289 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
vivek mehta587b8df2017-01-31 14:58:44 -08002290 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07002291 ALOGW("releaseInput() unknown session %d on input %d", session, input);
2292 return;
2293 }
Eric Laurent599c7582015-12-07 18:05:55 -08002294
2295 if (audioSession->openCount() == 0) {
2296 ALOGW("releaseInput() invalid open count %d on session %d",
2297 audioSession->openCount(), session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002298 return;
2299 }
Eric Laurent599c7582015-12-07 18:05:55 -08002300
2301 if (audioSession->changeOpenCount(-1) == 0) {
2302 inputDesc->removeAudioSession(session);
2303 }
2304
Jean-Michel Trivi65bfe912015-12-04 15:56:47 -08002305 if (inputDesc->getOpenRefCount() > 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002306 ALOGV("releaseInput() exit > 0");
2307 return;
2308 }
2309
Eric Laurent05b90f82014-08-27 15:32:29 -07002310 closeInput(input);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002311 inputDesc->clients().erase(portId);
Eric Laurentb52c1522014-05-20 11:27:36 -07002312 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002313 ALOGV("releaseInput() exit");
2314}
2315
Eric Laurent8fc147b2018-07-22 19:13:55 -07002316void AudioPolicyManager::closeSessions(const sp<AudioInputDescriptor>& input, bool activeOnly)
2317{
2318 AudioSessionCollection sessions = input->getAudioSessions(activeOnly /*activeOnly*/);
2319 for (size_t i = 0; i < sessions.size(); i++) {
2320 closeSession(input, sessions[i]);
2321 }
2322}
2323
2324void AudioPolicyManager::closeSession(const sp<AudioInputDescriptor>& input,
2325 const sp<AudioSession>& session)
2326{
2327 RecordClientVector clients = input->getClientsForSession(session->session());
2328
2329 for (const auto& client : clients) {
2330 stopInput(client->portId());
2331 releaseInput(client->portId());
2332 }
2333}
2334
2335
Eric Laurentd4692962014-05-05 18:13:44 -07002336void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002337 bool patchRemoved = false;
2338
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002339 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002340 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002341 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002342 if (patch_index >= 0) {
2343 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002344 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002345 mAudioPatches.removeItemsAt(patch_index);
2346 patchRemoved = true;
2347 }
Eric Laurentfe231122017-11-17 17:48:06 -08002348 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002349 }
jiabin829a00b2018-04-04 16:28:32 -07002350 mInputRoutes.clear();
Eric Laurentd4692962014-05-05 18:13:44 -07002351 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002352 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002353 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002354
2355 if (patchRemoved) {
2356 mpClientInterface->onAudioPatchListUpdate();
2357 }
Eric Laurentd4692962014-05-05 18:13:44 -07002358}
2359
Eric Laurente0720872014-03-11 09:30:41 -07002360void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002361 int indexMin,
2362 int indexMax)
2363{
2364 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002365 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002366
2367 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002368 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2369 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002370 continue;
2371 }
2372 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002373 }
Eric Laurente552edb2014-03-10 17:42:56 -07002374}
2375
Eric Laurente0720872014-03-11 09:30:41 -07002376status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002377 int index,
2378 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002379{
2380
Nadav Bar7c605f62017-12-25 00:01:52 +02002381 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2382 // app that has MODIFY_PHONE_STATE permission.
2383 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
2384 !(stream == AUDIO_STREAM_VOICE_CALL && index == 0)) ||
François Gaffied1ab2bd2015-12-02 18:20:06 +01002385 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002386 return BAD_VALUE;
2387 }
2388 if (!audio_is_output_device(device)) {
2389 return BAD_VALUE;
2390 }
2391
2392 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002393 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002394
Eric Laurent1fd372e2016-04-06 14:23:53 -07002395 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002396 stream, device, index);
2397
Eric Laurent28d09f02016-03-08 10:43:05 -08002398 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002399 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2400 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002401 continue;
2402 }
2403 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2404 }
Eric Laurente552edb2014-03-10 17:42:56 -07002405
Eric Laurent1fd372e2016-04-06 14:23:53 -07002406 // update volume on all outputs and streams matching the following:
2407 // - The requested stream (or a stream matching for volume control) is active on the output
2408 // - The device (or devices) selected by the strategy corresponding to this stream includes
2409 // the requested device
2410 // - For non default requested device, currently selected device on the output is either the
2411 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002412 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2413 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002414 status_t status = NO_ERROR;
2415 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002416 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2417 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08002418 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
Eric Laurent3839bc02018-07-10 18:33:34 -07002419 if (!(streamsMatchForvolume(stream, (audio_stream_type_t)curStream))) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002420 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002421 }
Eric Laurentdcd4ab12018-06-29 17:45:13 -07002422 if (!(desc->isStreamActive((audio_stream_type_t)curStream) || isInCall())) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002423 continue;
2424 }
Eric Laurent794fde22016-03-11 09:50:45 -08002425 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002426 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2427 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002428 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2429 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002430 continue;
2431 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002432 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002433 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002434 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07002435 applyVolume = (curDevice & curStreamDevice) != 0;
2436 } else {
2437 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002438 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002439 }
Eric Laurent3839bc02018-07-10 18:33:34 -07002440 // rescale index before applying to curStream as ranges may be different for
2441 // stream and curStream
2442 int idx = rescaleVolumeIndex(index, stream, (audio_stream_type_t)curStream);
Eric Laurente76f29c2016-09-14 17:17:53 -07002443 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002444 //FIXME: workaround for truncated touch sounds
2445 // delayed volume change for system stream to be removed when the problem is
2446 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002447 status_t volStatus =
Eric Laurent3839bc02018-07-10 18:33:34 -07002448 checkAndSetVolume((audio_stream_type_t)curStream, idx, desc, curDevice,
Eric Laurentdc462862016-07-19 12:29:53 -07002449 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002450 if (volStatus != NO_ERROR) {
2451 status = volStatus;
2452 }
2453 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002454 }
Eric Laurente552edb2014-03-10 17:42:56 -07002455 }
2456 return status;
2457}
2458
Eric Laurente0720872014-03-11 09:30:41 -07002459status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002460 int *index,
2461 audio_devices_t device)
2462{
2463 if (index == NULL) {
2464 return BAD_VALUE;
2465 }
2466 if (!audio_is_output_device(device)) {
2467 return BAD_VALUE;
2468 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002469 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002470 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002471 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002472 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2473 }
François Gaffiedfd74092015-03-19 12:10:59 +01002474 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002475
François Gaffied1ab2bd2015-12-02 18:20:06 +01002476 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002477 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2478 return NO_ERROR;
2479}
2480
Eric Laurent36829f92017-04-07 19:04:42 -07002481audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002482{
2483 // select one output among several suitable for global effects.
2484 // The priority is as follows:
2485 // 1: An offloaded output. If the effect ends up not being offloadable,
2486 // AudioFlinger will invalidate the track and the offloaded output
2487 // will be closed causing the effect to be moved to a PCM output.
2488 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002489 // 3: The primary output
2490 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002491
Eric Laurent3b73df72014-03-11 09:06:29 -07002492 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002493 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent36829f92017-04-07 19:04:42 -07002494 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002495
Eric Laurent36829f92017-04-07 19:04:42 -07002496 if (outputs.size() == 0) {
2497 return AUDIO_IO_HANDLE_NONE;
2498 }
Eric Laurente552edb2014-03-10 17:42:56 -07002499
Eric Laurent36829f92017-04-07 19:04:42 -07002500 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2501 bool activeOnly = true;
2502
2503 while (output == AUDIO_IO_HANDLE_NONE) {
2504 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2505 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2506 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2507
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002508 for (audio_io_handle_t output : outputs) {
2509 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002510 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2511 continue;
2512 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002513 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2514 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002515 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002516 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002517 }
2518 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002519 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002520 }
2521 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002522 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002523 }
2524 }
2525 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2526 output = outputOffloaded;
2527 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2528 output = outputDeepBuffer;
2529 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2530 output = outputPrimary;
2531 } else {
2532 output = outputs[0];
2533 }
2534 activeOnly = false;
2535 }
2536
2537 if (output != mMusicEffectOutput) {
2538 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2539 mMusicEffectOutput = output;
2540 }
2541
2542 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002543 return output;
2544}
2545
Eric Laurent36829f92017-04-07 19:04:42 -07002546audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2547{
2548 return selectOutputForMusicEffects();
2549}
2550
Eric Laurente0720872014-03-11 09:30:41 -07002551status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002552 audio_io_handle_t io,
2553 uint32_t strategy,
2554 int session,
2555 int id)
2556{
2557 ssize_t index = mOutputs.indexOfKey(io);
2558 if (index < 0) {
2559 index = mInputs.indexOfKey(io);
2560 if (index < 0) {
2561 ALOGW("registerEffect() unknown io %d", io);
2562 return INVALID_OPERATION;
2563 }
2564 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002565 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002566}
2567
Eric Laurentc75307b2015-03-17 15:29:32 -07002568bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2569{
Eric Laurent28d09f02016-03-08 10:43:05 -08002570 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002571 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2572 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002573 continue;
2574 }
2575 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2576 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002577 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002578}
2579
2580bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2581{
2582 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2583}
2584
Eric Laurente0720872014-03-11 09:30:41 -07002585bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002586{
2587 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002588 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002589 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002590 return true;
2591 }
2592 }
2593 return false;
2594}
2595
Eric Laurent275e8e92014-11-30 15:14:47 -08002596// Register a list of custom mixes with their attributes and format.
2597// When a mix is registered, corresponding input and output profiles are
2598// added to the remote submix hw module. The profile contains only the
2599// parameters (sampling rate, format...) specified by the mix.
2600// The corresponding input remote submix device is also connected.
2601//
2602// When a remote submix device is connected, the address is checked to select the
2603// appropriate profile and the corresponding input or output stream is opened.
2604//
2605// When capture starts, getInputForAttr() will:
2606// - 1 look for a mix matching the address passed in attribtutes tags if any
2607// - 2 if none found, getDeviceForInputSource() will:
2608// - 2.1 look for a mix matching the attributes source
2609// - 2.2 if none found, default to device selection by policy rules
2610// At this time, the corresponding output remote submix device is also connected
2611// and active playback use cases can be transferred to this mix if needed when reconnecting
2612// after AudioTracks are invalidated
2613//
2614// When playback starts, getOutputForAttr() will:
2615// - 1 look for a mix matching the address passed in attribtutes tags if any
2616// - 2 if none found, look for a mix matching the attributes usage
2617// - 3 if none found, default to device and output selection by policy rules.
2618
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002619status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002620{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002621 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2622 status_t res = NO_ERROR;
2623
2624 sp<HwModule> rSubmixModule;
2625 // examine each mix's route type
2626 for (size_t i = 0; i < mixes.size(); i++) {
2627 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
2628 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
2629 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002630 break;
2631 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002632 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002633 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002634 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002635 rSubmixModule = mHwModules.getModuleFromName(
2636 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2637 if (rSubmixModule == 0) {
2638 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2639 i);
2640 res = INVALID_OPERATION;
2641 break;
2642 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002643 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002644
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002645 String8 address = mixes[i].mDeviceAddress;
François Gaffie036e1e92015-03-19 10:16:24 +01002646
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002647 if (mPolicyMixes.registerMix(address, mixes[i], 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002648 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002649 res = INVALID_OPERATION;
2650 break;
2651 }
2652 audio_config_t outputConfig = mixes[i].mFormat;
2653 audio_config_t inputConfig = mixes[i].mFormat;
2654 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2655 // stereo and let audio flinger do the channel conversion if needed.
2656 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2657 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2658 rSubmixModule->addOutputProfile(address, &outputConfig,
2659 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2660 rSubmixModule->addInputProfile(address, &inputConfig,
2661 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002662
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002663 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
2664 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2665 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2666 address.string(), "remote-submix");
2667 } else {
2668 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2669 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2670 address.string(), "remote-submix");
2671 }
2672 } else if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002673 String8 address = mixes[i].mDeviceAddress;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002674 audio_devices_t device = mixes[i].mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002675 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2676 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002677
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002678 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002679 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2680 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2681 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2682 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2683 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2684 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002685 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2686 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002687 if (mPolicyMixes.registerMix(address, mixes[i], desc) != NO_ERROR) {
2688 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002689 } else {
2690 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002691 }
2692 break;
2693 }
2694 }
2695
2696 if (res != NO_ERROR) {
2697 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002698 i, device, address.string());
2699 res = INVALID_OPERATION;
2700 break;
2701 } else if (!foundOutput) {
2702 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2703 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002704 res = INVALID_OPERATION;
2705 break;
2706 }
Eric Laurentc722f302014-12-10 11:21:49 -08002707 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002708 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002709 if (res != NO_ERROR) {
2710 unregisterPolicyMixes(mixes);
2711 }
2712 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002713}
2714
2715status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2716{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002717 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002718 status_t res = NO_ERROR;
2719 sp<HwModule> rSubmixModule;
2720 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002721 for (const auto& mix : mixes) {
2722 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002723
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002724 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002725 rSubmixModule = mHwModules.getModuleFromName(
2726 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2727 if (rSubmixModule == 0) {
2728 res = INVALID_OPERATION;
2729 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002730 }
2731 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002732
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002733 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002734
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002735 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2736 res = INVALID_OPERATION;
2737 continue;
2738 }
2739
2740 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2741 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2742 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2743 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2744 address.string(), "remote-submix");
2745 }
2746 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2747 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2748 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2749 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2750 address.string(), "remote-submix");
2751 }
2752 rSubmixModule->removeOutputProfile(address);
2753 rSubmixModule->removeInputProfile(address);
2754
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002755 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2756 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002757 res = INVALID_OPERATION;
2758 continue;
2759 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002760 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002761 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002762 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002763}
2764
Eric Laurente552edb2014-03-10 17:42:56 -07002765
Eric Laurente0720872014-03-11 09:30:41 -07002766status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002767{
Eric Laurente552edb2014-03-10 17:42:56 -07002768 String8 result;
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002769 result.appendFormat("\nAudioPolicyManager Dump: %p\n", this);
2770 result.appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07002771 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002772 std::string stateLiteral;
2773 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002774 result.appendFormat(" Phone state: %s\n", stateLiteral.c_str());
2775 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
2776 "communications", "media", "record", "dock", "system",
2777 "HDMI system audio", "encoded surround output", "vibrate ringing" };
2778 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
2779 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
2780 result.appendFormat(" Force use for %s: %d\n",
2781 forceUses[i], mEngine->getForceUse(i));
2782 }
2783 result.appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
2784 result.appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
2785 result.appendFormat(" Config source: %s\n", getConfig().getSource().c_str());
François Gaffie2110e042015-03-24 08:41:51 +01002786 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002787
François Gaffie112b0af2015-11-19 16:13:25 +01002788 mAvailableOutputDevices.dump(fd, String8("Available output"));
2789 mAvailableInputDevices.dump(fd, String8("Available input"));
Mikhail Naganovd4120142017-12-06 15:49:22 -08002790 mHwModulesAll.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002791 mOutputs.dump(fd);
2792 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002793 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002794 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002795 mAudioPatches.dump(fd);
Mikhail Naganov44344b02016-12-13 11:21:02 -08002796 mPolicyMixes.dump(fd);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07002797 mAudioSources.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002798
2799 return NO_ERROR;
2800}
2801
2802// This function checks for the parameters which can be offloaded.
2803// This can be enhanced depending on the capability of the DSP and policy
2804// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002805bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002806{
2807 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002808 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002809 offloadInfo.sample_rate, offloadInfo.channel_mask,
2810 offloadInfo.format,
2811 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2812 offloadInfo.has_video);
2813
Andy Hung2ddee192015-12-18 17:34:44 -08002814 if (mMasterMono) {
2815 return false; // no offloading if mono is set.
2816 }
2817
Eric Laurente552edb2014-03-10 17:42:56 -07002818 // Check if offload has been disabled
2819 char propValue[PROPERTY_VALUE_MAX];
2820 if (property_get("audio.offload.disable", propValue, "0")) {
2821 if (atoi(propValue) != 0) {
2822 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2823 return false;
2824 }
2825 }
2826
2827 // Check if stream type is music, then only allow offload as of now.
2828 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2829 {
2830 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2831 return false;
2832 }
2833
2834 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002835 const bool allowOffloadWithVideo =
2836 property_get_bool("audio.offload.video", false /* default_value */);
2837 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002838 ALOGV("isOffloadSupported: has_video == true, returning false");
2839 return false;
2840 }
2841
2842 //If duration is less than minimum value defined in property, return false
2843 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2844 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2845 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2846 return false;
2847 }
2848 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2849 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2850 return false;
2851 }
2852
2853 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2854 // creating an offloaded track and tearing it down immediately after start when audioflinger
2855 // detects there is an active non offloadable effect.
2856 // FIXME: We should check the audio session here but we do not have it in this context.
2857 // This may prevent offloading in rare situations where effects are left active by apps
2858 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002859 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002860 return false;
2861 }
2862
2863 // See if there is a profile to support this.
2864 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002865 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002866 offloadInfo.sample_rate,
2867 offloadInfo.format,
2868 offloadInfo.channel_mask,
2869 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002870 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2871 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002872}
2873
Eric Laurent6a94d692014-05-20 11:18:06 -07002874status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2875 audio_port_type_t type,
2876 unsigned int *num_ports,
2877 struct audio_port *ports,
2878 unsigned int *generation)
2879{
2880 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2881 generation == NULL) {
2882 return BAD_VALUE;
2883 }
2884 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2885 if (ports == NULL) {
2886 *num_ports = 0;
2887 }
2888
2889 size_t portsWritten = 0;
2890 size_t portsMax = *num_ports;
2891 *num_ports = 0;
2892 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002893 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2894 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002895 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002896 for (const auto& dev : mAvailableOutputDevices) {
2897 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002898 continue;
2899 }
2900 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002901 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002902 }
2903 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002904 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002905 }
2906 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002907 for (const auto& dev : mAvailableInputDevices) {
2908 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002909 continue;
2910 }
2911 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002912 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002913 }
2914 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002915 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002916 }
2917 }
2918 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2919 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2920 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2921 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2922 }
2923 *num_ports += mInputs.size();
2924 }
2925 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002926 size_t numOutputs = 0;
2927 for (size_t i = 0; i < mOutputs.size(); i++) {
2928 if (!mOutputs[i]->isDuplicated()) {
2929 numOutputs++;
2930 if (portsWritten < portsMax) {
2931 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2932 }
2933 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002934 }
Eric Laurent84c70242014-06-23 08:46:27 -07002935 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002936 }
2937 }
2938 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002939 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002940 return NO_ERROR;
2941}
2942
Eric Laurent99fcae42018-05-17 16:59:18 -07002943status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07002944{
Eric Laurent99fcae42018-05-17 16:59:18 -07002945 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
2946 return BAD_VALUE;
2947 }
2948 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
2949 if (dev != 0) {
2950 dev->toAudioPort(port);
2951 return NO_ERROR;
2952 }
2953 dev = mAvailableInputDevices.getDeviceFromId(port->id);
2954 if (dev != 0) {
2955 dev->toAudioPort(port);
2956 return NO_ERROR;
2957 }
2958 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
2959 if (out != 0) {
2960 out->toAudioPort(port);
2961 return NO_ERROR;
2962 }
2963 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
2964 if (in != 0) {
2965 in->toAudioPort(port);
2966 return NO_ERROR;
2967 }
2968 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002969}
2970
Eric Laurent6a94d692014-05-20 11:18:06 -07002971status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2972 audio_patch_handle_t *handle,
2973 uid_t uid)
2974{
2975 ALOGV("createAudioPatch()");
2976
2977 if (handle == NULL || patch == NULL) {
2978 return BAD_VALUE;
2979 }
2980 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2981
Mikhail Naganovac9858b2018-06-15 13:12:37 -07002982 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07002983 return BAD_VALUE;
2984 }
2985 // only one source per audio patch supported for now
2986 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002987 return INVALID_OPERATION;
2988 }
Eric Laurent874c42872014-08-08 15:13:39 -07002989
2990 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002991 return INVALID_OPERATION;
2992 }
Eric Laurent874c42872014-08-08 15:13:39 -07002993 for (size_t i = 0; i < patch->num_sinks; i++) {
2994 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2995 return INVALID_OPERATION;
2996 }
2997 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002998
2999 sp<AudioPatch> patchDesc;
3000 ssize_t index = mAudioPatches.indexOfKey(*handle);
3001
Eric Laurent6a94d692014-05-20 11:18:06 -07003002 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
3003 patch->sources[0].role,
3004 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003005#if LOG_NDEBUG == 0
3006 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08003007 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07003008 patch->sinks[i].role,
3009 patch->sinks[i].type);
3010 }
3011#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07003012
3013 if (index >= 0) {
3014 patchDesc = mAudioPatches.valueAt(index);
3015 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3016 mUidCached, patchDesc->mUid, uid);
3017 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3018 return INVALID_OPERATION;
3019 }
3020 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07003021 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003022 }
3023
3024 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003025 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003026 if (outputDesc == NULL) {
3027 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
3028 return BAD_VALUE;
3029 }
Eric Laurent84c70242014-06-23 08:46:27 -07003030 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
3031 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003032 if (patchDesc != 0) {
3033 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
3034 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
3035 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
3036 return BAD_VALUE;
3037 }
3038 }
Eric Laurent874c42872014-08-08 15:13:39 -07003039 DeviceVector devices;
3040 for (size_t i = 0; i < patch->num_sinks; i++) {
3041 // Only support mix to devices connection
3042 // TODO add support for mix to mix connection
3043 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3044 ALOGV("createAudioPatch() source mix but sink is not a device");
3045 return INVALID_OPERATION;
3046 }
3047 sp<DeviceDescriptor> devDesc =
3048 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3049 if (devDesc == 0) {
3050 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
3051 return BAD_VALUE;
3052 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003053
François Gaffie53615e22015-03-19 09:24:12 +01003054 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08003055 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07003056 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01003057 NULL, // updatedSamplingRate
3058 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003059 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01003060 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003061 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01003062 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07003063 ALOGV("createAudioPatch() profile not supported for device %08x",
3064 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07003065 return INVALID_OPERATION;
3066 }
3067 devices.add(devDesc);
3068 }
3069 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003070 return INVALID_OPERATION;
3071 }
Eric Laurent874c42872014-08-08 15:13:39 -07003072
Eric Laurent6a94d692014-05-20 11:18:06 -07003073 // TODO: reconfigure output format and channels here
3074 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07003075 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07003076 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003077 index = mAudioPatches.indexOfKey(*handle);
3078 if (index >= 0) {
3079 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3080 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
3081 }
3082 patchDesc = mAudioPatches.valueAt(index);
3083 patchDesc->mUid = uid;
3084 ALOGV("createAudioPatch() success");
3085 } else {
3086 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
3087 return INVALID_OPERATION;
3088 }
3089 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3090 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3091 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003092 // only one sink supported when connecting an input device to a mix
3093 if (patch->num_sinks > 1) {
3094 return INVALID_OPERATION;
3095 }
François Gaffie53615e22015-03-19 09:24:12 +01003096 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003097 if (inputDesc == NULL) {
3098 return BAD_VALUE;
3099 }
3100 if (patchDesc != 0) {
3101 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3102 return BAD_VALUE;
3103 }
3104 }
3105 sp<DeviceDescriptor> devDesc =
3106 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
3107 if (devDesc == 0) {
3108 return BAD_VALUE;
3109 }
3110
François Gaffie53615e22015-03-19 09:24:12 +01003111 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08003112 devDesc->mAddress,
3113 patch->sinks[0].sample_rate,
3114 NULL, /*updatedSampleRate*/
3115 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003116 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003117 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003118 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003119 // FIXME for the parameter type,
3120 // and the NONE
3121 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003122 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003123 return INVALID_OPERATION;
3124 }
3125 // TODO: reconfigure output format and channels here
3126 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01003127 devDesc->type(), inputDesc->mIoHandle);
3128 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003129 index = mAudioPatches.indexOfKey(*handle);
3130 if (index >= 0) {
3131 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3132 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
3133 }
3134 patchDesc = mAudioPatches.valueAt(index);
3135 patchDesc->mUid = uid;
3136 ALOGV("createAudioPatch() success");
3137 } else {
3138 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
3139 return INVALID_OPERATION;
3140 }
3141 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3142 // device to device connection
3143 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003144 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003145 return BAD_VALUE;
3146 }
3147 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003148 sp<DeviceDescriptor> srcDeviceDesc =
3149 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07003150 if (srcDeviceDesc == 0) {
3151 return BAD_VALUE;
3152 }
Eric Laurent874c42872014-08-08 15:13:39 -07003153
Eric Laurent6a94d692014-05-20 11:18:06 -07003154 //update source and sink with our own data as the data passed in the patch may
3155 // be incomplete.
3156 struct audio_patch newPatch = *patch;
3157 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003158
Eric Laurent874c42872014-08-08 15:13:39 -07003159 for (size_t i = 0; i < patch->num_sinks; i++) {
3160 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3161 ALOGV("createAudioPatch() source device but one sink is not a device");
3162 return INVALID_OPERATION;
3163 }
3164
3165 sp<DeviceDescriptor> sinkDeviceDesc =
3166 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3167 if (sinkDeviceDesc == 0) {
3168 return BAD_VALUE;
3169 }
3170 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
3171
Eric Laurent3bcf8592015-04-03 12:13:24 -07003172 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003173 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003174 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08003175 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003176 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003177 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003178 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003179 return INVALID_OPERATION;
3180 }
Eric Laurent874c42872014-08-08 15:13:39 -07003181 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01003182 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003183 // if the sink device is reachable via an opened output stream, request to go via
3184 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07003185 audio_io_handle_t output = selectOutput(outputs,
3186 AUDIO_OUTPUT_FLAG_NONE,
3187 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07003188 if (output != AUDIO_IO_HANDLE_NONE) {
3189 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3190 if (outputDesc->isDuplicated()) {
3191 return INVALID_OPERATION;
3192 }
3193 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003194 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003195 newPatch.num_sources = 2;
3196 }
Eric Laurent83b88082014-06-20 18:31:16 -07003197 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003198 }
3199 // TODO: check from routing capabilities in config file and other conflicting patches
3200
Mikhail Naganovdc769682018-05-04 15:34:08 -07003201 status_t status = installPatch(__func__, index, handle, &newPatch, 0, uid, &patchDesc);
3202 if (status != NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003203 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3204 status);
3205 return INVALID_OPERATION;
3206 }
3207 } else {
3208 return BAD_VALUE;
3209 }
3210 } else {
3211 return BAD_VALUE;
3212 }
3213 return NO_ERROR;
3214}
3215
3216status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3217 uid_t uid)
3218{
3219 ALOGV("releaseAudioPatch() patch %d", handle);
3220
3221 ssize_t index = mAudioPatches.indexOfKey(handle);
3222
3223 if (index < 0) {
3224 return BAD_VALUE;
3225 }
3226 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3227 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3228 mUidCached, patchDesc->mUid, uid);
3229 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3230 return INVALID_OPERATION;
3231 }
3232
3233 struct audio_patch *patch = &patchDesc->mPatch;
3234 patchDesc->mUid = mUidCached;
3235 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003236 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003237 if (outputDesc == NULL) {
3238 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3239 return BAD_VALUE;
3240 }
3241
Eric Laurentc75307b2015-03-17 15:29:32 -07003242 setOutputDevice(outputDesc,
3243 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07003244 true,
3245 0,
3246 NULL);
3247 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3248 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003249 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003250 if (inputDesc == NULL) {
3251 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3252 return BAD_VALUE;
3253 }
3254 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003255 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003256 true,
3257 NULL);
3258 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003259 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3260 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3261 status, patchDesc->mAfPatchHandle);
3262 removeAudioPatch(patchDesc->mHandle);
3263 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003264 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003265 } else {
3266 return BAD_VALUE;
3267 }
3268 } else {
3269 return BAD_VALUE;
3270 }
3271 return NO_ERROR;
3272}
3273
3274status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3275 struct audio_patch *patches,
3276 unsigned int *generation)
3277{
François Gaffie53615e22015-03-19 09:24:12 +01003278 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003279 return BAD_VALUE;
3280 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003281 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003282 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003283}
3284
Eric Laurente1715a42014-05-20 11:30:42 -07003285status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003286{
Eric Laurente1715a42014-05-20 11:30:42 -07003287 ALOGV("setAudioPortConfig()");
3288
3289 if (config == NULL) {
3290 return BAD_VALUE;
3291 }
3292 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3293 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003294 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3295 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003296 }
3297
Eric Laurenta121f902014-06-03 13:32:54 -07003298 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003299 if (config->type == AUDIO_PORT_TYPE_MIX) {
3300 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003301 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003302 if (outputDesc == NULL) {
3303 return BAD_VALUE;
3304 }
Eric Laurent84c70242014-06-23 08:46:27 -07003305 ALOG_ASSERT(!outputDesc->isDuplicated(),
3306 "setAudioPortConfig() called on duplicated output %d",
3307 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003308 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003309 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003310 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003311 if (inputDesc == NULL) {
3312 return BAD_VALUE;
3313 }
Eric Laurenta121f902014-06-03 13:32:54 -07003314 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003315 } else {
3316 return BAD_VALUE;
3317 }
3318 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3319 sp<DeviceDescriptor> deviceDesc;
3320 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3321 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3322 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3323 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3324 } else {
3325 return BAD_VALUE;
3326 }
3327 if (deviceDesc == NULL) {
3328 return BAD_VALUE;
3329 }
Eric Laurenta121f902014-06-03 13:32:54 -07003330 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003331 } else {
3332 return BAD_VALUE;
3333 }
3334
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003335 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003336 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3337 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003338 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003339 audioPortConfig->toAudioPortConfig(&newConfig, config);
3340 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003341 }
Eric Laurenta121f902014-06-03 13:32:54 -07003342 if (status != NO_ERROR) {
3343 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003344 }
Eric Laurente1715a42014-05-20 11:30:42 -07003345
3346 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003347}
3348
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003349void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3350{
Eric Laurentd60560a2015-04-10 11:31:20 -07003351 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003352 clearAudioPatches(uid);
3353 clearSessionRoutes(uid);
3354}
3355
Eric Laurent6a94d692014-05-20 11:18:06 -07003356void AudioPolicyManager::clearAudioPatches(uid_t uid)
3357{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003358 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003359 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3360 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003361 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003362 }
3363 }
3364}
3365
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003366void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3367 audio_io_handle_t ouptutToSkip)
3368{
3369 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3370 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3371 for (size_t j = 0; j < mOutputs.size(); j++) {
3372 if (mOutputs.keyAt(j) == ouptutToSkip) {
3373 continue;
3374 }
3375 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3376 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3377 continue;
3378 }
3379 // If the default device for this strategy is on another output mix,
3380 // invalidate all tracks in this strategy to force re connection.
3381 // Otherwise select new device on the output mix.
3382 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003383 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003384 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3385 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3386 }
3387 }
3388 } else {
3389 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3390 setOutputDevice(outputDesc, newDevice, false);
3391 }
3392 }
3393}
3394
3395void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3396{
3397 // remove output routes associated with this uid
3398 SortedVector<routing_strategy> affectedStrategies;
3399 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
3400 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
3401 if (route->mUid == uid) {
3402 mOutputRoutes.removeItemsAt(i);
3403 if (route->mDeviceDescriptor != 0) {
3404 affectedStrategies.add(getStrategy(route->mStreamType));
3405 }
3406 }
3407 }
3408 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003409 for (const auto& strategy : affectedStrategies) {
3410 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003411 }
3412
3413 // remove input routes associated with this uid
3414 SortedVector<audio_source_t> affectedSources;
3415 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
3416 sp<SessionRoute> route = mInputRoutes.valueAt(i);
3417 if (route->mUid == uid) {
3418 mInputRoutes.removeItemsAt(i);
3419 if (route->mDeviceDescriptor != 0) {
3420 affectedSources.add(route->mSource);
3421 }
3422 }
3423 }
3424 // reroute inputs if necessary
3425 SortedVector<audio_io_handle_t> inputsToClose;
3426 for (size_t i = 0; i < mInputs.size(); i++) {
3427 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003428 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003429 inputsToClose.add(inputDesc->mIoHandle);
3430 }
3431 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003432 for (const auto& input : inputsToClose) {
3433 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003434 }
3435}
3436
Eric Laurentd60560a2015-04-10 11:31:20 -07003437void AudioPolicyManager::clearAudioSources(uid_t uid)
3438{
3439 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003440 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3441 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07003442 stopAudioSource(mAudioSources.keyAt(i));
3443 }
3444 }
3445}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003446
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003447status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3448 audio_io_handle_t *ioHandle,
3449 audio_devices_t *device)
3450{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003451 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3452 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003453 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003454
François Gaffiedf372692015-03-19 10:43:27 +01003455 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003456}
3457
Eric Laurentd60560a2015-04-10 11:31:20 -07003458status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003459 const audio_attributes_t *attributes,
3460 audio_port_handle_t *portId,
3461 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003462{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003463 ALOGV("%s", __FUNCTION__);
3464 *portId = AUDIO_PORT_HANDLE_NONE;
3465
3466 if (source == NULL || attributes == NULL || portId == NULL) {
3467 ALOGW("%s invalid argument: source %p attributes %p handle %p",
3468 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003469 return BAD_VALUE;
3470 }
3471
Eric Laurentd60560a2015-04-10 11:31:20 -07003472 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3473 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003474 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
3475 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003476 return INVALID_OPERATION;
3477 }
3478
3479 sp<DeviceDescriptor> srcDeviceDesc =
3480 mAvailableInputDevices.getDevice(source->ext.device.type,
3481 String8(source->ext.device.address));
3482 if (srcDeviceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003483 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003484 return BAD_VALUE;
3485 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003486
3487 *portId = AudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07003488
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003489 struct audio_patch dummyPatch = {};
Eric Laurentd60560a2015-04-10 11:31:20 -07003490 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003491
3492 sp<SourceClientDescriptor> sourceDesc =
3493 new SourceClientDescriptor(*portId, uid, *attributes, patchDesc, srcDeviceDesc,
3494 streamTypefromAttributesInt(attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07003495
3496 status_t status = connectAudioSource(sourceDesc);
3497 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003498 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003499 }
3500 return status;
3501}
3502
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003503status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003504{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003505 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003506
3507 // make sure we only have one patch per source.
3508 disconnectAudioSource(sourceDesc);
3509
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003510 audio_attributes_t attributes = sourceDesc->attributes();
3511 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
3512 audio_stream_type_t stream = sourceDesc->stream();
3513 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->srcDevice();
Eric Laurentd60560a2015-04-10 11:31:20 -07003514
3515 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3516 sp<DeviceDescriptor> sinkDeviceDesc =
3517 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3518
3519 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003520
3521 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3522 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003523 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003524 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3525 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3526 // create patch between src device and output device
3527 // create Hwoutput and add to mHwOutputs
3528 } else {
3529 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3530 audio_io_handle_t output =
3531 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3532 if (output == AUDIO_IO_HANDLE_NONE) {
3533 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3534 return INVALID_OPERATION;
3535 }
3536 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3537 if (outputDesc->isDuplicated()) {
3538 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3539 return INVALID_OPERATION;
3540 }
Eric Laurent733ce942017-12-07 12:18:25 -08003541 status_t status = outputDesc->start();
3542 if (status != NO_ERROR) {
3543 return status;
3544 }
3545
Eric Laurentd60560a2015-04-10 11:31:20 -07003546 // create a special patch with no sink and two sources:
3547 // - the second source indicates to PatchPanel through which output mix this patch should
3548 // be connected as well as the stream type for volume control
3549 // - the sink is defined by whatever output device is currently selected for the output
3550 // though which this patch is routed.
Mikhail Naganovdc769682018-05-04 15:34:08 -07003551 PatchBuilder patchBuilder;
3552 patchBuilder.addSource(srcDeviceDesc).addSource(outputDesc, { .stream = stream });
3553 status = mpClientInterface->createAudioPatch(patchBuilder.patch(),
Eric Laurentd60560a2015-04-10 11:31:20 -07003554 &afPatchHandle,
3555 0);
3556 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3557 status, afPatchHandle);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003558 sourceDesc->patchDesc()->mPatch = *patchBuilder.patch();
Eric Laurentd60560a2015-04-10 11:31:20 -07003559 if (status != NO_ERROR) {
3560 ALOGW("%s patch panel could not connect device patch, error %d",
3561 __FUNCTION__, status);
3562 return INVALID_OPERATION;
3563 }
3564 uint32_t delayMs = 0;
Eric Laurentc40d9692016-04-13 19:14:13 -07003565 status = startSource(outputDesc, stream, sinkDevice, NULL, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003566
3567 if (status != NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003568 mpClientInterface->releaseAudioPatch(sourceDesc->patchDesc()->mAfPatchHandle, 0);
Eric Laurentd60560a2015-04-10 11:31:20 -07003569 return status;
3570 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003571 sourceDesc->setSwOutput(outputDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003572 if (delayMs != 0) {
3573 usleep(delayMs * 1000);
3574 }
3575 }
3576
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003577 sourceDesc->patchDesc()->mAfPatchHandle = afPatchHandle;
3578 addAudioPatch(sourceDesc->patchDesc()->mHandle, sourceDesc->patchDesc());
Eric Laurentd60560a2015-04-10 11:31:20 -07003579
3580 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003581}
3582
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003583status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07003584{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003585 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
3586 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003587 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003588 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003589 return BAD_VALUE;
3590 }
3591 status_t status = disconnectAudioSource(sourceDesc);
3592
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003593 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003594 return status;
3595}
3596
Andy Hung2ddee192015-12-18 17:34:44 -08003597status_t AudioPolicyManager::setMasterMono(bool mono)
3598{
3599 if (mMasterMono == mono) {
3600 return NO_ERROR;
3601 }
3602 mMasterMono = mono;
3603 // if enabling mono we close all offloaded devices, which will invalidate the
3604 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3605 // for recreating the new AudioTrack as non-offloaded PCM.
3606 //
3607 // If disabling mono, we leave all tracks as is: we don't know which clients
3608 // and tracks are able to be recreated as offloaded. The next "song" should
3609 // play back offloaded.
3610 if (mMasterMono) {
3611 Vector<audio_io_handle_t> offloaded;
3612 for (size_t i = 0; i < mOutputs.size(); ++i) {
3613 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3614 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3615 offloaded.push(desc->mIoHandle);
3616 }
3617 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003618 for (const auto& handle : offloaded) {
3619 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003620 }
3621 }
3622 // update master mono for all remaining outputs
3623 for (size_t i = 0; i < mOutputs.size(); ++i) {
3624 updateMono(mOutputs.keyAt(i));
3625 }
3626 return NO_ERROR;
3627}
3628
3629status_t AudioPolicyManager::getMasterMono(bool *mono)
3630{
3631 *mono = mMasterMono;
3632 return NO_ERROR;
3633}
3634
Eric Laurentac9cef52017-06-09 15:46:26 -07003635float AudioPolicyManager::getStreamVolumeDB(
3636 audio_stream_type_t stream, int index, audio_devices_t device)
3637{
3638 return computeVolume(stream, index, device);
3639}
3640
jiabin81772902018-04-02 17:52:27 -07003641status_t AudioPolicyManager::getSupportedFormats(audio_io_handle_t ioHandle,
3642 FormatVector& formats) {
3643 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
3644 return BAD_VALUE;
3645 }
3646 String8 reply;
3647 reply = mpClientInterface->getParameters(
3648 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
3649 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
3650 AudioParameter repliedParameters(reply);
3651 if (repliedParameters.get(
3652 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
3653 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
3654 return BAD_VALUE;
3655 }
3656 for (auto format : formatsFromString(reply.string())) {
3657 // Only AUDIO_FORMAT_AAC_LC will be used in Settings UI for all AAC formats.
3658 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3659 if (format == AAC_FORMATS[i]) {
3660 format = AUDIO_FORMAT_AAC_LC;
3661 break;
3662 }
3663 }
3664 bool exist = false;
3665 for (size_t i = 0; i < formats.size(); i++) {
3666 if (format == formats[i]) {
3667 exist = true;
3668 break;
3669 }
3670 }
3671 bool isSurroundFormat = false;
3672 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3673 if (SURROUND_FORMATS[i] == format) {
3674 isSurroundFormat = true;
3675 break;
3676 }
3677 }
3678 if (!exist && isSurroundFormat) {
3679 formats.add(format);
3680 }
3681 }
3682 return NO_ERROR;
3683}
3684
3685status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3686 audio_format_t *surroundFormats,
3687 bool *surroundFormatsEnabled,
3688 bool reported)
3689{
3690 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3691 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3692 return BAD_VALUE;
3693 }
3694 ALOGV("getSurroundFormats() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
3695 *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
3696
3697 // Only return value if there is HDMI output.
3698 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3699 return INVALID_OPERATION;
3700 }
3701
3702 size_t formatsWritten = 0;
3703 size_t formatsMax = *numSurroundFormats;
3704 *numSurroundFormats = 0;
3705 FormatVector formats;
3706 if (reported) {
3707 // Only get surround formats which are reported by device.
3708 // First list already open outputs that can be routed to this device
3709 audio_devices_t device = AUDIO_DEVICE_OUT_HDMI;
3710 SortedVector<audio_io_handle_t> outputs;
3711 bool reportedFormatFound = false;
3712 status_t status;
3713 sp<SwAudioOutputDescriptor> desc;
3714 for (size_t i = 0; i < mOutputs.size(); i++) {
3715 desc = mOutputs.valueAt(i);
3716 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
3717 outputs.add(mOutputs.keyAt(i));
3718 }
3719 }
3720 // Open an output to query dynamic parameters.
Mikhail Naganov708e0382018-05-30 09:53:04 -07003721 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003722 AUDIO_DEVICE_OUT_HDMI);
3723 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3724 String8 address = hdmiOutputDevices[i]->mAddress;
3725 for (const auto& hwModule : mHwModules) {
3726 for (size_t i = 0; i < hwModule->getOutputProfiles().size(); i++) {
3727 sp<IOProfile> profile = hwModule->getOutputProfiles()[i];
3728 if (profile->supportDevice(AUDIO_DEVICE_OUT_HDMI) &&
3729 profile->supportDeviceAddress(address)) {
3730 size_t j;
3731 for (j = 0; j < outputs.size(); j++) {
3732 desc = mOutputs.valueFor(outputs.itemAt(j));
3733 if (!desc->isDuplicated() && desc->mProfile == profile) {
3734 break;
3735 }
3736 }
3737 if (j != outputs.size()) {
3738 status = getSupportedFormats(outputs.itemAt(j), formats);
3739 reportedFormatFound |= (status == NO_ERROR);
3740 continue;
3741 }
3742
3743 if (!profile->canOpenNewIo()) {
3744 ALOGW("Max Output number %u already opened for this profile %s",
3745 profile->maxOpenCount, profile->getTagName().c_str());
3746 continue;
3747 }
3748
3749 ALOGV("opening output for device %08x with params %s profile %p name %s",
3750 device, address.string(), profile.get(), profile->getName().string());
3751 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
3752 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3753 status_t status = desc->open(nullptr, device, address,
3754 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE,
3755 &output);
3756
3757 if (status == NO_ERROR) {
3758 status = getSupportedFormats(output, formats);
3759 reportedFormatFound |= (status == NO_ERROR);
3760 desc->close();
3761 output = AUDIO_IO_HANDLE_NONE;
3762 }
3763 }
3764 }
3765 }
3766 }
3767
3768 if (!reportedFormatFound) {
3769 return UNKNOWN_ERROR;
3770 }
3771 } else {
3772 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3773 formats.add(SURROUND_FORMATS[i]);
3774 }
3775 }
3776 for (size_t i = 0; i < formats.size(); i++) {
3777 if (formatsWritten < formatsMax) {
3778 surroundFormats[formatsWritten] = formats[i];
3779 bool formatEnabled = false;
3780 if (formats[i] == AUDIO_FORMAT_AAC_LC) {
3781 for (size_t j = 0; j < ARRAY_SIZE(AAC_FORMATS); j++) {
3782 formatEnabled =
3783 mSurroundFormats.find(AAC_FORMATS[i]) != mSurroundFormats.end();
3784 break;
3785 }
3786 } else {
3787 formatEnabled = mSurroundFormats.find(formats[i]) != mSurroundFormats.end();
3788 }
3789 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3790 }
3791 (*numSurroundFormats)++;
3792 }
3793 return NO_ERROR;
3794}
3795
3796status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3797{
3798 // Check if audio format is a surround formats.
3799 bool isSurroundFormat = false;
3800 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3801 if (audioFormat == SURROUND_FORMATS[i]) {
3802 isSurroundFormat = true;
3803 break;
3804 }
3805 }
3806 if (!isSurroundFormat) {
3807 return BAD_VALUE;
3808 }
3809
3810 // Should only be called when MANUAL.
3811 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3812 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
3813 if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3814 return INVALID_OPERATION;
3815 }
3816
3817 if ((mSurroundFormats.find(audioFormat) != mSurroundFormats.end() && enabled)
3818 || (mSurroundFormats.find(audioFormat) == mSurroundFormats.end() && !enabled)) {
3819 return NO_ERROR;
3820 }
3821
3822 // The operation is valid only when there is HDMI output available.
3823 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3824 return INVALID_OPERATION;
3825 }
3826
3827 if (enabled) {
3828 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3829 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3830 mSurroundFormats.insert(AAC_FORMATS[i]);
3831 }
3832 } else {
3833 mSurroundFormats.insert(audioFormat);
3834 }
3835 } else {
3836 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3837 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3838 mSurroundFormats.erase(AAC_FORMATS[i]);
3839 }
3840 } else {
3841 mSurroundFormats.erase(audioFormat);
3842 }
3843 }
3844
3845 sp<SwAudioOutputDescriptor> outputDesc;
3846 bool profileUpdated = false;
Mikhail Naganov708e0382018-05-30 09:53:04 -07003847 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003848 AUDIO_DEVICE_OUT_HDMI);
3849 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3850 // Simulate reconnection to update enabled surround sound formats.
3851 String8 address = hdmiOutputDevices[i]->mAddress;
3852 String8 name = hdmiOutputDevices[i]->getName();
3853 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3854 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3855 address.c_str(),
3856 name.c_str());
3857 if (status != NO_ERROR) {
3858 continue;
3859 }
3860 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3861 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3862 address.c_str(),
3863 name.c_str());
3864 profileUpdated |= (status == NO_ERROR);
3865 }
Mikhail Naganov708e0382018-05-30 09:53:04 -07003866 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003867 AUDIO_DEVICE_IN_HDMI);
3868 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3869 // Simulate reconnection to update enabled surround sound formats.
3870 String8 address = hdmiInputDevices[i]->mAddress;
3871 String8 name = hdmiInputDevices[i]->getName();
3872 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3873 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3874 address.c_str(),
3875 name.c_str());
3876 if (status != NO_ERROR) {
3877 continue;
3878 }
3879 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3880 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3881 address.c_str(),
3882 name.c_str());
3883 profileUpdated |= (status == NO_ERROR);
3884 }
3885
3886 // Undo the surround formats change due to no audio profiles updated.
3887 if (!profileUpdated) {
3888 if (enabled) {
3889 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3890 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3891 mSurroundFormats.erase(AAC_FORMATS[i]);
3892 }
3893 } else {
3894 mSurroundFormats.erase(audioFormat);
3895 }
3896 } else {
3897 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3898 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3899 mSurroundFormats.insert(AAC_FORMATS[i]);
3900 }
3901 } else {
3902 mSurroundFormats.insert(audioFormat);
3903 }
3904 }
3905 }
3906
3907 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3908}
3909
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003910void AudioPolicyManager::setRecordSilenced(uid_t uid, bool silenced)
3911{
3912 ALOGV("AudioPolicyManager:setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
3913
3914 Vector<sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
3915 for (size_t i = 0; i < activeInputs.size(); i++) {
3916 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
3917 AudioSessionCollection activeSessions = activeDesc->getAudioSessions(true);
3918 for (size_t j = 0; j < activeSessions.size(); j++) {
3919 sp<AudioSession> activeSession = activeSessions.valueAt(j);
3920 if (activeSession->uid() == uid) {
3921 activeSession->setSilenced(silenced);
3922 }
3923 }
3924 }
3925}
3926
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003927status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003928{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003929 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003930
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003931 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003932 if (patchDesc == 0) {
3933 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003934 sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003935 return BAD_VALUE;
3936 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003937 removeAudioPatch(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003938
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003939 audio_stream_type_t stream = sourceDesc->stream();
3940 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003941 if (swOutputDesc != 0) {
Eric Laurent733ce942017-12-07 12:18:25 -08003942 status_t status = stopSource(swOutputDesc, stream, false);
3943 if (status == NO_ERROR) {
3944 swOutputDesc->stop();
3945 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003946 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3947 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003948 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003949 if (hwOutputDesc != 0) {
3950 // release patch between src device and output device
3951 // close Hwoutput and remove from mHwOutputs
3952 } else {
3953 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3954 }
3955 }
3956 return NO_ERROR;
3957}
3958
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003959sp<SourceClientDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
Eric Laurentd60560a2015-04-10 11:31:20 -07003960 audio_io_handle_t output, routing_strategy strategy)
3961{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003962 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07003963 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003964 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3965 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurentd60560a2015-04-10 11:31:20 -07003966 routing_strategy sourceStrategy =
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003967 (routing_strategy) getStrategyForAttr(&attributes);
3968 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003969 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3970 source = sourceDesc;
3971 break;
3972 }
3973 }
3974 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003975}
3976
Eric Laurente552edb2014-03-10 17:42:56 -07003977// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003978// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003979// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003980uint32_t AudioPolicyManager::nextAudioPortGeneration()
3981{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003982 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003983}
3984
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003985#ifdef USE_XML_AUDIO_POLICY_CONF
3986// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3987static const char *kConfigLocationList[] =
3988 {"/odm/etc", "/vendor/etc", "/system/etc"};
3989static const int kConfigLocationListSize =
3990 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3991
3992static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3993 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07003994 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003995 status_t ret;
3996
Petri Gyntherf497f292018-04-17 18:46:10 -07003997 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
3998 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
3999 // A2DP offload supported but disabled: try to use special XML file
4000 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
4001 }
4002 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
4003
4004 for (const char* fileName : fileNames) {
4005 for (int i = 0; i < kConfigLocationListSize; i++) {
4006 PolicySerializer serializer;
4007 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
4008 "%s/%s", kConfigLocationList[i], fileName);
4009 ret = serializer.deserialize(audioPolicyXmlConfigFile, config);
4010 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004011 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07004012 return ret;
4013 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004014 }
4015 }
4016 return ret;
4017}
4018#endif
4019
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004020AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
4021 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07004022 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07004023 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004024 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07004025 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07004026 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004027#ifdef USE_XML_AUDIO_POLICY_CONF
4028 mVolumeCurves(new VolumeCurvesCollection()),
4029 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08004030 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004031#else
4032 mVolumeCurves(new StreamDescriptorCollection()),
4033 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
4034 mDefaultOutputDevice),
4035#endif
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004036 mAudioPortGeneration(1),
4037 mBeaconMuteRefCount(0),
4038 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07004039 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08004040 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07004041 mMasterMono(false),
Chris Thornton2b864642017-06-27 21:26:07 -07004042 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE),
4043 mHasComputedSoundTriggerSupportsConcurrentCapture(false)
Eric Laurente552edb2014-03-10 17:42:56 -07004044{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004045}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004046
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004047AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
4048 : AudioPolicyManager(clientInterface, false /*forTesting*/)
4049{
4050 loadConfig();
4051 initialize();
4052}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004053
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004054void AudioPolicyManager::loadConfig() {
François Gaffied1ab2bd2015-12-02 18:20:06 +01004055#ifdef USE_XML_AUDIO_POLICY_CONF
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004056 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01004057#else
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004058 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, getConfig()) != NO_ERROR)
4059 && (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, getConfig()) != NO_ERROR)) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01004060#endif
4061 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004062 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01004063 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004064}
4065
4066status_t AudioPolicyManager::initialize() {
4067 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01004068
4069 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01004070 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
4071 if (!engineInstance) {
4072 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004073 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01004074 }
4075 // Retrieve the Policy Manager Interface
4076 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
4077 if (mEngine == NULL) {
4078 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004079 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01004080 }
4081 mEngine->setObserver(this);
4082 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004083 if (status != NO_ERROR) {
4084 LOG_FATAL("Policy engine not initialized(err=%d)", status);
4085 return status;
4086 }
François Gaffie2110e042015-03-24 08:41:51 +01004087
Eric Laurent3a4311c2014-03-17 12:00:47 -07004088 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07004089 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07004090 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
4091 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Mikhail Naganovd4120142017-12-06 15:49:22 -08004092 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004093 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08004094 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
4095 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07004096 continue;
4097 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08004098 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07004099 // open all output streams needed to access attached devices
4100 // except for direct output streams that are only opened when they are actually
4101 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07004102 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004103 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004104 if (!outProfile->canOpenNewIo()) {
4105 ALOGE("Invalid Output profile max open count %u for profile %s",
4106 outProfile->maxOpenCount, outProfile->getTagName().c_str());
4107 continue;
4108 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004109 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004110 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004111 continue;
4112 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004113 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004114 mTtsOutputAvailable = true;
4115 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004116
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004117 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07004118 continue;
4119 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004120 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01004121 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
4122 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07004123 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004124 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07004125 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004126 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07004127 }
Eric Laurentd78f1532014-09-16 16:38:20 -07004128 if ((profileType & outputDeviceTypes) == 0) {
4129 continue;
4130 }
Eric Laurentc75307b2015-03-17 15:29:32 -07004131 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
4132 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07004133 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov708e0382018-05-30 09:53:04 -07004134 const DeviceVector &devicesForType = supportedDevices.getDevicesFromTypeMask(
4135 profileType);
Eric Laurentc40d9692016-04-13 19:14:13 -07004136 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
4137 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07004138 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004139 status_t status = outputDesc->open(nullptr, profileType, address,
4140 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07004141
4142 if (status != NO_ERROR) {
4143 ALOGW("Cannot open output stream for device %08x on hw module %s",
4144 outputDesc->mDevice,
Mikhail Naganovd4120142017-12-06 15:49:22 -08004145 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07004146 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004147 for (const auto& dev : supportedDevices) {
4148 ssize_t index = mAvailableOutputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07004149 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08004150 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004151 mAvailableOutputDevices[index]->attach(hwModule);
Eric Laurentd78f1532014-09-16 16:38:20 -07004152 }
4153 }
4154 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004155 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004156 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07004157 }
4158 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07004159 setOutputDevice(outputDesc,
Eric Laurentfe231122017-11-17 17:48:06 -08004160 profileType,
Eric Laurentc40d9692016-04-13 19:14:13 -07004161 true,
4162 0,
4163 NULL,
Eric Laurentfe231122017-11-17 17:48:06 -08004164 address);
Eric Laurentd78f1532014-09-16 16:38:20 -07004165 }
Eric Laurente552edb2014-03-10 17:42:56 -07004166 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004167 // open input streams needed to access attached devices to validate
4168 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004169 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004170 if (!inProfile->canOpenNewIo()) {
4171 ALOGE("Invalid Input profile max open count %u for profile %s",
4172 inProfile->maxOpenCount, inProfile->getTagName().c_str());
4173 continue;
4174 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004175 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004176 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004177 continue;
4178 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004179 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07004180 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004181 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
4182
Eric Laurentd78f1532014-09-16 16:38:20 -07004183 if ((profileType & inputDeviceTypes) == 0) {
4184 continue;
4185 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08004186 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08004187 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004188
Mikhail Naganov708e0382018-05-30 09:53:04 -07004189 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(profileType);
Eric Laurent53b810e2017-12-10 17:25:10 -08004190 // the inputs vector must be of size >= 1, but we don't want to crash here
4191 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
4192 : String8("");
4193 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
4194 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
4195
Eric Laurentd78f1532014-09-16 16:38:20 -07004196 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004197 status_t status = inputDesc->open(nullptr,
4198 profileType,
Eric Laurent53b810e2017-12-10 17:25:10 -08004199 address,
Eric Laurentfe231122017-11-17 17:48:06 -08004200 AUDIO_SOURCE_MIC,
4201 AUDIO_INPUT_FLAG_NONE,
4202 &input);
Eric Laurentd78f1532014-09-16 16:38:20 -07004203
4204 if (status == NO_ERROR) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004205 for (const auto& dev : inProfile->getSupportedDevices()) {
4206 ssize_t index = mAvailableInputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07004207 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07004208 if (index >= 0) {
4209 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
4210 if (!devDesc->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004211 devDesc->attach(hwModule);
Eric Laurent83efe1c2017-07-09 16:51:08 -07004212 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07004213 }
Eric Laurentd78f1532014-09-16 16:38:20 -07004214 }
4215 }
Eric Laurentfe231122017-11-17 17:48:06 -08004216 inputDesc->close();
Eric Laurentd78f1532014-09-16 16:38:20 -07004217 } else {
4218 ALOGW("Cannot open input stream for device %08x on hw module %s",
Eric Laurentfe231122017-11-17 17:48:06 -08004219 profileType,
Mikhail Naganovd4120142017-12-06 15:49:22 -08004220 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07004221 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004222 }
4223 }
4224 // make sure all attached devices have been allocated a unique ID
4225 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004226 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004227 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004228 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
4229 continue;
4230 }
François Gaffie2110e042015-03-24 08:41:51 +01004231 // The device is now validated and can be appended to the available devices of the engine
4232 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
4233 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004234 i++;
4235 }
4236 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004237 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01004238 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004239 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
4240 continue;
4241 }
François Gaffie2110e042015-03-24 08:41:51 +01004242 // The device is now validated and can be appended to the available devices of the engine
4243 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
4244 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004245 i++;
4246 }
4247 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004248 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01004249 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004250 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004251 }
jiabin9ff780e2018-03-19 18:19:52 -07004252 // If microphones address is empty, set it according to device type
4253 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
4254 if (mAvailableInputDevices[i]->mAddress.isEmpty()) {
4255 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
4256 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
4257 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
4258 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BACK_MICROPHONE_ADDRESS);
4259 }
4260 }
4261 }
Eric Laurente552edb2014-03-10 17:42:56 -07004262
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004263 if (mPrimaryOutput == 0) {
4264 ALOGE("Failed to open primary output");
4265 status = NO_INIT;
4266 }
Eric Laurente552edb2014-03-10 17:42:56 -07004267
4268 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004269 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004270}
4271
Eric Laurente0720872014-03-11 09:30:41 -07004272AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004273{
Eric Laurente552edb2014-03-10 17:42:56 -07004274 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004275 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004276 }
4277 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004278 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004279 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004280 mAvailableOutputDevices.clear();
4281 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004282 mOutputs.clear();
4283 mInputs.clear();
4284 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004285 mHwModulesAll.clear();
jiabin81772902018-04-02 17:52:27 -07004286 mSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004287}
4288
Eric Laurente0720872014-03-11 09:30:41 -07004289status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004290{
Eric Laurent87ffa392015-05-22 10:32:38 -07004291 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004292}
4293
Eric Laurente552edb2014-03-10 17:42:56 -07004294// ---
4295
Eric Laurent98e38192018-02-15 18:31:53 -08004296void AudioPolicyManager::addOutput(audio_io_handle_t output,
4297 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004298{
Eric Laurent1c333e22014-05-20 10:48:17 -07004299 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08004300 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004301 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004302 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004303 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004304}
4305
François Gaffie53615e22015-03-19 09:24:12 +01004306void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4307{
4308 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004309 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004310}
4311
Eric Laurent98e38192018-02-15 18:31:53 -08004312void AudioPolicyManager::addInput(audio_io_handle_t input,
4313 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004314{
Eric Laurent1c333e22014-05-20 10:48:17 -07004315 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004316 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004317}
Eric Laurente552edb2014-03-10 17:42:56 -07004318
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004319void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08004320 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004321 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004322 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08004323 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004324 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08004325 if (devDesc != 0) {
4326 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
4327 desc->mIoHandle, address.string());
4328 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004329 }
4330}
4331
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004332status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004333 audio_policy_dev_state_t state,
4334 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004335 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07004336{
François Gaffie53615e22015-03-19 09:24:12 +01004337 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07004338 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004339
4340 if (audio_device_is_digital(device)) {
4341 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004342 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004343 }
Eric Laurente552edb2014-03-10 17:42:56 -07004344
Eric Laurent3b73df72014-03-11 09:06:29 -07004345 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004346 // first list already open outputs that can be routed to this device
4347 for (size_t i = 0; i < mOutputs.size(); i++) {
4348 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07004349 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004350 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004351 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
4352 outputs.add(mOutputs.keyAt(i));
4353 } else {
4354 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08004355 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004356 }
Eric Laurente552edb2014-03-10 17:42:56 -07004357 }
4358 }
4359 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004360 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004361 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004362 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4363 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004364 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004365 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004366 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004367 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004368 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4369 j, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004370 }
Eric Laurente552edb2014-03-10 17:42:56 -07004371 }
4372 }
4373 }
4374
Eric Laurent7b279bb2015-12-14 10:18:23 -08004375 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004376
Eric Laurente552edb2014-03-10 17:42:56 -07004377 if (profiles.isEmpty() && outputs.isEmpty()) {
4378 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4379 return BAD_VALUE;
4380 }
4381
4382 // open outputs for matching profiles if needed. Direct outputs are also opened to
4383 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4384 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004385 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004386
4387 // nothing to do if one output is already opened for this profile
4388 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004389 for (j = 0; j < outputs.size(); j++) {
4390 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004391 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004392 // matching profile: save the sample rates, format and channel masks supported
4393 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07004394 if (audio_device_is_digital(device)) {
4395 devDesc->importAudioPort(profile);
4396 }
Eric Laurente552edb2014-03-10 17:42:56 -07004397 break;
4398 }
4399 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004400 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004401 continue;
4402 }
4403
Eric Laurent3974e3b2017-12-07 17:58:43 -08004404 if (!profile->canOpenNewIo()) {
4405 ALOGW("Max Output number %u already opened for this profile %s",
4406 profile->maxOpenCount, profile->getTagName().c_str());
4407 continue;
4408 }
4409
Eric Laurent83efe1c2017-07-09 16:51:08 -07004410 ALOGV("opening output for device %08x with params %s profile %p name %s",
4411 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004412 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004413 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004414 status_t status = desc->open(nullptr, device, address,
4415 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004416
Eric Laurentfe231122017-11-17 17:48:06 -08004417 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004418 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004419 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004420 char *param = audio_device_address_to_parameter(device, address);
4421 mpClientInterface->setParameters(output, String8(param));
4422 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004423 }
Phil Burk00eeb322016-03-31 12:41:00 -07004424 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004425 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004426 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004427 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004428 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004429 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004430 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004431 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004432 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4433 profile->pickAudioProfile(
4434 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004435 config.offload_info.sample_rate = config.sample_rate;
4436 config.offload_info.channel_mask = config.channel_mask;
4437 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004438
4439 status_t status = desc->open(&config, device, address, AUDIO_STREAM_DEFAULT,
4440 AUDIO_OUTPUT_FLAG_NONE, &output);
4441 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004442 output = AUDIO_IO_HANDLE_NONE;
4443 }
Eric Laurentd4692962014-05-05 18:13:44 -07004444 }
4445
Eric Laurentcf2c0212014-07-25 16:20:43 -07004446 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004447 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01004448 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004449 sp<AudioPolicyMix> policyMix;
4450 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004451 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
4452 address.string());
4453 }
François Gaffie036e1e92015-03-19 10:16:24 +01004454 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07004455 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01004456
Eric Laurent87ffa392015-05-22 10:32:38 -07004457 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4458 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004459 // no duplicated output for direct outputs and
4460 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004461 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004462
Eric Laurentd4692962014-05-05 18:13:44 -07004463 //TODO: configure audio effect output stage here
4464
4465 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004466 sp<SwAudioOutputDescriptor> dupOutputDesc =
4467 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4468 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4469 &duplicatedOutput);
4470 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004471 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004472 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004473 } else {
4474 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004475 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004476 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004477 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004478 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004479 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004480 }
Eric Laurente552edb2014-03-10 17:42:56 -07004481 }
4482 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004483 } else {
4484 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004485 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004486 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004487 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004488 profiles.removeAt(profile_index);
4489 profile_index--;
4490 } else {
4491 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004492 // Load digital format info only for digital devices
4493 if (audio_device_is_digital(device)) {
4494 devDesc->importAudioPort(profile);
4495 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004496
François Gaffie53615e22015-03-19 09:24:12 +01004497 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004498 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4499 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004500 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004501 NULL/*patch handle*/, address.string());
4502 }
Eric Laurente552edb2014-03-10 17:42:56 -07004503 ALOGV("checkOutputsForDevice(): adding output %d", output);
4504 }
4505 }
4506
4507 if (profiles.isEmpty()) {
4508 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4509 return BAD_VALUE;
4510 }
Eric Laurentd4692962014-05-05 18:13:44 -07004511 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004512 // check if one opened output is not needed any more after disconnecting one device
4513 for (size_t i = 0; i < mOutputs.size(); i++) {
4514 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004515 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004516 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004517 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004518 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004519 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004520 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004521 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4522 mOutputs.keyAt(i));
4523 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004524 }
Eric Laurente552edb2014-03-10 17:42:56 -07004525 }
4526 }
Eric Laurentd4692962014-05-05 18:13:44 -07004527 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004528 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004529 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4530 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004531 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004532 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004533 "clearing direct output profile %zu on module %s",
4534 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004535 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004536 }
4537 }
4538 }
4539 }
4540 return NO_ERROR;
4541}
4542
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004543status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004544 audio_policy_dev_state_t state,
4545 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004546 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004547{
Paul McLean9080a4c2015-06-18 08:24:02 -07004548 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004549 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004550
4551 if (audio_device_is_digital(device)) {
4552 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004553 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004554 }
4555
Eric Laurentd4692962014-05-05 18:13:44 -07004556 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4557 // first list already open inputs that can be routed to this device
4558 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4559 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004560 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004561 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4562 inputs.add(mInputs.keyAt(input_index));
4563 }
4564 }
4565
4566 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004567 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004568 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004569 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004570 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004571 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004572 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004573
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004574 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004575 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004576 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004577 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004578 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4579 profile_index, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004580 }
Eric Laurentd4692962014-05-05 18:13:44 -07004581 }
4582 }
4583 }
4584
4585 if (profiles.isEmpty() && inputs.isEmpty()) {
4586 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4587 return BAD_VALUE;
4588 }
4589
4590 // open inputs for matching profiles if needed. Direct inputs are also opened to
4591 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4592 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4593
Eric Laurent1c333e22014-05-20 10:48:17 -07004594 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004595
Eric Laurentd4692962014-05-05 18:13:44 -07004596 // nothing to do if one input is already opened for this profile
4597 size_t input_index;
4598 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4599 desc = mInputs.valueAt(input_index);
4600 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004601 if (audio_device_is_digital(device)) {
4602 devDesc->importAudioPort(profile);
4603 }
Eric Laurentd4692962014-05-05 18:13:44 -07004604 break;
4605 }
4606 }
4607 if (input_index != mInputs.size()) {
4608 continue;
4609 }
4610
Eric Laurent3974e3b2017-12-07 17:58:43 -08004611 if (!profile->canOpenNewIo()) {
4612 ALOGW("Max Input number %u already opened for this profile %s",
4613 profile->maxOpenCount, profile->getTagName().c_str());
4614 continue;
4615 }
4616
Eric Laurentfe231122017-11-17 17:48:06 -08004617 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004618 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004619 status_t status = desc->open(nullptr,
4620 device,
4621 address,
4622 AUDIO_SOURCE_MIC,
4623 AUDIO_INPUT_FLAG_NONE,
4624 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004625
Eric Laurentcf2c0212014-07-25 16:20:43 -07004626 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004627 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004628 char *param = audio_device_address_to_parameter(device, address);
4629 mpClientInterface->setParameters(input, String8(param));
4630 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004631 }
Phil Burk00eeb322016-03-31 12:41:00 -07004632 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004633 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004634 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004635 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004636 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004637 }
4638
4639 if (input != 0) {
4640 addInput(input, desc);
4641 }
4642 } // endif input != 0
4643
Eric Laurentcf2c0212014-07-25 16:20:43 -07004644 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004645 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004646 profiles.removeAt(profile_index);
4647 profile_index--;
4648 } else {
4649 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004650 if (audio_device_is_digital(device)) {
4651 devDesc->importAudioPort(profile);
4652 }
Eric Laurentd4692962014-05-05 18:13:44 -07004653 ALOGV("checkInputsForDevice(): adding input %d", input);
4654 }
4655 } // end scan profiles
4656
4657 if (profiles.isEmpty()) {
4658 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4659 return BAD_VALUE;
4660 }
4661 } else {
4662 // Disconnect
4663 // check if one opened input is not needed any more after disconnecting one device
4664 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4665 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004666 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004667 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4668 mInputs.keyAt(input_index));
4669 inputs.add(mInputs.keyAt(input_index));
4670 }
4671 }
4672 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004673 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004674 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004675 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004676 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004677 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004678 if (profile->supportDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004679 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4680 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004681 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004682 }
4683 }
4684 }
4685 } // end disconnect
4686
4687 return NO_ERROR;
4688}
4689
4690
Eric Laurente0720872014-03-11 09:30:41 -07004691void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004692{
4693 ALOGV("closeOutput(%d)", output);
4694
Eric Laurentc75307b2015-03-17 15:29:32 -07004695 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004696 if (outputDesc == NULL) {
4697 ALOGW("closeOutput() unknown output %d", output);
4698 return;
4699 }
François Gaffie036e1e92015-03-19 10:16:24 +01004700 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004701
Eric Laurente552edb2014-03-10 17:42:56 -07004702 // look for duplicated outputs connected to the output being removed.
4703 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004704 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004705 if (dupOutputDesc->isDuplicated() &&
4706 (dupOutputDesc->mOutput1 == outputDesc ||
4707 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004708 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004709 if (dupOutputDesc->mOutput1 == outputDesc) {
4710 outputDesc2 = dupOutputDesc->mOutput2;
4711 } else {
4712 outputDesc2 = dupOutputDesc->mOutput1;
4713 }
4714 // As all active tracks on duplicated output will be deleted,
4715 // and as they were also referenced on the other output, the reference
4716 // count for their stream type must be adjusted accordingly on
4717 // the other output.
Eric Laurent733ce942017-12-07 12:18:25 -08004718 bool wasActive = outputDesc2->isActive();
Eric Laurent3b73df72014-03-11 09:06:29 -07004719 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004720 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07004721 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004722 }
Eric Laurent733ce942017-12-07 12:18:25 -08004723 // stop() will be a no op if the output is still active but is needed in case all
4724 // active streams refcounts where cleared above
4725 if (wasActive) {
4726 outputDesc2->stop();
4727 }
Eric Laurente552edb2014-03-10 17:42:56 -07004728 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4729 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4730
4731 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004732 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004733 }
4734 }
4735
Eric Laurent05b90f82014-08-27 15:32:29 -07004736 nextAudioPortGeneration();
4737
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004738 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004739 if (index >= 0) {
4740 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004741 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004742 mAudioPatches.removeItemsAt(index);
4743 mpClientInterface->onAudioPatchListUpdate();
4744 }
4745
Eric Laurentfe231122017-11-17 17:48:06 -08004746 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004747
François Gaffie53615e22015-03-19 09:24:12 +01004748 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004749 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004750}
4751
4752void AudioPolicyManager::closeInput(audio_io_handle_t input)
4753{
4754 ALOGV("closeInput(%d)", input);
4755
4756 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4757 if (inputDesc == NULL) {
4758 ALOGW("closeInput() unknown input %d", input);
4759 return;
4760 }
4761
Eric Laurent6a94d692014-05-20 11:18:06 -07004762 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004763
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004764 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004765 if (index >= 0) {
4766 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004767 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004768 mAudioPatches.removeItemsAt(index);
4769 mpClientInterface->onAudioPatchListUpdate();
4770 }
4771
Eric Laurentfe231122017-11-17 17:48:06 -08004772 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004773 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004774}
4775
Eric Laurentc75307b2015-03-17 15:29:32 -07004776SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4777 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004778 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004779{
4780 SortedVector<audio_io_handle_t> outputs;
4781
4782 ALOGVV("getOutputsForDevice() device %04x", device);
4783 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004784 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004785 i, openOutputs.valueAt(i)->isDuplicated(),
4786 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004787 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4788 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4789 outputs.add(openOutputs.keyAt(i));
4790 }
4791 }
4792 return outputs;
4793}
4794
Mikhail Naganov37977152018-07-11 15:54:44 -07004795void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
4796{
4797 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
4798 // output is suspended before any tracks are moved to it
4799 checkA2dpSuspend();
4800 checkOutputForAllStrategies();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004801 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07004802 updateDevicesAndOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004803 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
4804 setMsdPatch();
4805 }
Mikhail Naganov37977152018-07-11 15:54:44 -07004806}
4807
Eric Laurente0720872014-03-11 09:30:41 -07004808void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004809{
4810 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4811 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4812 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4813 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4814
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004815 // also take into account external policy-related changes: add all outputs which are
4816 // associated with policies in the "before" and "after" output vectors
4817 ALOGVV("checkOutputForStrategy(): policy related outputs");
4818 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004819 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004820 if (desc != 0 && desc->mPolicyMix != NULL) {
4821 srcOutputs.add(desc->mIoHandle);
4822 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4823 }
4824 }
4825 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004826 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004827 if (desc != 0 && desc->mPolicyMix != NULL) {
4828 dstOutputs.add(desc->mIoHandle);
4829 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4830 }
4831 }
4832
Mikhail Naganov9de8bd12018-07-23 16:41:31 -07004833 if (srcOutputs != dstOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004834 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4835 // audio from invalidated tracks will be rendered when unmuting
4836 uint32_t maxLatency = 0;
4837 for (audio_io_handle_t srcOut : srcOutputs) {
4838 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4839 if (desc != 0 && maxLatency < desc->latency()) {
4840 maxLatency = desc->latency();
4841 }
4842 }
Eric Laurente552edb2014-03-10 17:42:56 -07004843 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4844 strategy, srcOutputs[0], dstOutputs[0]);
4845 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004846 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004847 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4848 if (desc != 0 && isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004849 setStrategyMute(strategy, true, desc);
Eric Laurentac3a6902018-05-11 16:39:10 -07004850 setStrategyMute(strategy, false, desc, maxLatency * LATENCY_MUTE_FACTOR, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004851 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004852 sp<SourceClientDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004853 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004854 if (source != 0){
4855 connectAudioSource(source);
4856 }
Eric Laurente552edb2014-03-10 17:42:56 -07004857 }
4858
4859 // Move effects associated to this strategy from previous output to new output
4860 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004861 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004862 }
4863 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004864 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004865 if (getStrategy((audio_stream_type_t)i) == strategy) {
4866 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004867 }
4868 }
4869 }
4870}
4871
Eric Laurente0720872014-03-11 09:30:41 -07004872void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004873{
François Gaffie2110e042015-03-24 08:41:51 +01004874 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004875 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004876 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004877 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004878 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004879 checkOutputForStrategy(STRATEGY_SONIFICATION);
4880 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004881 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004882 checkOutputForStrategy(STRATEGY_MEDIA);
4883 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004884 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004885}
4886
Eric Laurente0720872014-03-11 09:30:41 -07004887void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004888{
François Gaffie53615e22015-03-19 09:24:12 +01004889 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004890 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004891 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004892 return;
4893 }
4894
Eric Laurent3a4311c2014-03-17 12:00:47 -07004895 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004896 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4897 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4898 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004899
4900 // if suspended, restore A2DP output if:
4901 // ((SCO device is NOT connected) ||
4902 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4903 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004904 //
Eric Laurentf732e072016-08-03 19:30:28 -07004905 // if not suspended, suspend A2DP output if:
4906 // (SCO device is connected) &&
4907 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4908 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004909 //
4910 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004911 if (!isScoConnected ||
4912 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4913 AUDIO_POLICY_FORCE_BT_SCO) &&
4914 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4915 AUDIO_POLICY_FORCE_BT_SCO) &&
4916 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004917 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004918
4919 mpClientInterface->restoreOutput(a2dpOutput);
4920 mA2dpSuspended = false;
4921 }
4922 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004923 if (isScoConnected &&
4924 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4925 AUDIO_POLICY_FORCE_BT_SCO) ||
4926 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4927 AUDIO_POLICY_FORCE_BT_SCO) ||
4928 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004929 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004930
4931 mpClientInterface->suspendOutput(a2dpOutput);
4932 mA2dpSuspended = true;
4933 }
4934 }
4935}
4936
Eric Laurentc75307b2015-03-17 15:29:32 -07004937audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4938 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004939{
4940 audio_devices_t device = AUDIO_DEVICE_NONE;
4941
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004942 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004943 if (index >= 0) {
4944 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4945 if (patchDesc->mUid != mUidCached) {
4946 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004947 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004948 return outputDesc->device();
4949 }
4950 }
4951
Eric Laurentf3a5a602018-05-22 18:42:55 -07004952 // Check if an explicit routing request exists for an active stream on this output and
4953 // use it in priority before any other rule
4954 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
4955 if (outputDesc->isStreamActive((audio_stream_type_t)stream)) {
4956 audio_devices_t forcedDevice =
4957 mOutputRoutes.getActiveDeviceForStream(
4958 (audio_stream_type_t)stream, mAvailableOutputDevices);
4959
4960 if (forcedDevice != AUDIO_DEVICE_NONE) {
4961 return forcedDevice;
4962 }
4963 }
4964 }
4965
Eric Laurente552edb2014-03-10 17:42:56 -07004966 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004967 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004968 // use device for strategy enforced audible
4969 // 2: we are in call or the strategy phone is active on the output:
4970 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004971 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004972 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004973 // 4: the strategy for enforced audible is active but not enforced on the output:
4974 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004975 // 5: the strategy accessibility is active on the output:
4976 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004977 // 6: the strategy "respectful" sonification is active on the output:
4978 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004979 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004980 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004981 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004982 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004983 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004984 // use device for strategy t-t-s
Eric Laurent484e9272018-06-07 17:29:23 -07004985
4986 // FIXME: extend use of isStrategyActiveOnSameModule() to all strategies
4987 // with a refined rule considering mutually exclusive devices (using same backend)
4988 // as opposed to all streams on the same audio HAL module.
François Gaffiead3183e2015-03-18 16:55:35 +01004989 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004990 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004991 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4992 } else if (isInCall() ||
Eric Laurent484e9272018-06-07 17:29:23 -07004993 isStrategyActiveOnSameModule(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004994 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004995 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004996 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004997 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
4998 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004999 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
5000 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01005001 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005002 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01005003 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005004 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01005005 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005006 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01005007 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005008 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01005009 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005010 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07005011 }
5012
Eric Laurent1c333e22014-05-20 10:48:17 -07005013 ALOGV("getNewOutputDevice() selected device %x", device);
5014 return device;
5015}
5016
Eric Laurentfb66dd92016-01-28 18:32:03 -08005017audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07005018{
Eric Laurentfb66dd92016-01-28 18:32:03 -08005019 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005020
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005021 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005022 if (index >= 0) {
5023 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5024 if (patchDesc->mUid != mUidCached) {
5025 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005026 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005027 return inputDesc->mDevice;
5028 }
5029 }
5030
Eric Laurentdc95a252018-04-12 12:46:56 -07005031 // If we are not in call and no client is active on this input, this methods returns
5032 // AUDIO_DEVICE_NONE, causing the patch on the input stream to be released.
Eric Laurentfb66dd92016-01-28 18:32:03 -08005033 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
Eric Laurentdc95a252018-04-12 12:46:56 -07005034 if (source == AUDIO_SOURCE_DEFAULT && isInCall()) {
5035 source = AUDIO_SOURCE_VOICE_COMMUNICATION;
5036 }
5037 if (source != AUDIO_SOURCE_DEFAULT) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08005038 device = getDeviceAndMixForInputSource(source);
5039 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005040
Eric Laurente552edb2014-03-10 17:42:56 -07005041 return device;
5042}
5043
Eric Laurent794fde22016-03-11 09:50:45 -08005044bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
5045 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08005046 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08005047}
5048
Eric Laurente0720872014-03-11 09:30:41 -07005049uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005050 return (uint32_t)getStrategy(stream);
5051}
5052
Eric Laurente0720872014-03-11 09:30:41 -07005053audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005054 // By checking the range of stream before calling getStrategy, we avoid
5055 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
5056 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08005057 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005058 return AUDIO_DEVICE_NONE;
5059 }
Eric Laurent28d09f02016-03-08 10:43:05 -08005060 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08005061 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
5062 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08005063 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07005064 }
Eric Laurent794fde22016-03-11 09:50:45 -08005065 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08005066 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07005067 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005068 for (audio_io_handle_t output : getOutputsForDevice(curDevices, mOutputs)) {
5069 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08005070 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08005071 curDevices |= outputDesc->device();
5072 }
5073 }
5074 devices |= curDevices;
Eric Laurente552edb2014-03-10 17:42:56 -07005075 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005076
5077 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
5078 and doesn't really need to.*/
5079 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
5080 devices |= AUDIO_DEVICE_OUT_SPEAKER;
5081 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
5082 }
Eric Laurente552edb2014-03-10 17:42:56 -07005083 return devices;
5084}
5085
François Gaffie2110e042015-03-24 08:41:51 +01005086routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
5087{
Eric Laurent223fd5c2014-11-11 13:43:36 -08005088 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01005089 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005090}
5091
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005092uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
5093 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005094 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5095 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
5096 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005097 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5098 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
5099 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005100 // usage to strategy mapping
François Gaffie2110e042015-03-24 08:41:51 +01005101 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005102}
5103
Eric Laurente0720872014-03-11 09:30:41 -07005104void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005105 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005106 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07005107 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
5108 updateDevicesAndOutputs();
5109 break;
5110 default:
5111 break;
5112 }
5113}
5114
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005115uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07005116
5117 // skip beacon mute management if a dedicated TTS output is available
5118 if (mTtsOutputAvailable) {
5119 return 0;
5120 }
5121
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005122 switch(event) {
5123 case STARTING_OUTPUT:
5124 mBeaconMuteRefCount++;
5125 break;
5126 case STOPPING_OUTPUT:
5127 if (mBeaconMuteRefCount > 0) {
5128 mBeaconMuteRefCount--;
5129 }
5130 break;
5131 case STARTING_BEACON:
5132 mBeaconPlayingRefCount++;
5133 break;
5134 case STOPPING_BEACON:
5135 if (mBeaconPlayingRefCount > 0) {
5136 mBeaconPlayingRefCount--;
5137 }
5138 break;
5139 }
5140
5141 if (mBeaconMuteRefCount > 0) {
5142 // any playback causes beacon to be muted
5143 return setBeaconMute(true);
5144 } else {
5145 // no other playback: unmute when beacon starts playing, mute when it stops
5146 return setBeaconMute(mBeaconPlayingRefCount == 0);
5147 }
5148}
5149
5150uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5151 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5152 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5153 // keep track of muted state to avoid repeating mute/unmute operations
5154 if (mBeaconMuted != mute) {
5155 // mute/unmute AUDIO_STREAM_TTS on all outputs
5156 ALOGV("\t muting %d", mute);
5157 uint32_t maxLatency = 0;
5158 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005159 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005160 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07005161 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005162 0 /*delay*/, AUDIO_DEVICE_NONE);
5163 const uint32_t latency = desc->latency() * 2;
5164 if (latency > maxLatency) {
5165 maxLatency = latency;
5166 }
5167 }
5168 mBeaconMuted = mute;
5169 return maxLatency;
5170 }
5171 return 0;
5172}
5173
Eric Laurente0720872014-03-11 09:30:41 -07005174audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01005175 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005176{
Eric Laurentf3a5a602018-05-22 18:42:55 -07005177 // Check if an explicit routing request exists for a stream type corresponding to the
5178 // specified strategy and use it in priority over default routing rules.
5179 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
5180 if (getStrategy((audio_stream_type_t)stream) == strategy) {
5181 audio_devices_t forcedDevice =
5182 mOutputRoutes.getActiveDeviceForStream(
5183 (audio_stream_type_t)stream, mAvailableOutputDevices);
5184 if (forcedDevice != AUDIO_DEVICE_NONE) {
5185 return forcedDevice;
5186 }
Paul McLeanaa981192015-03-21 09:55:15 -07005187 }
5188 }
5189
Eric Laurente552edb2014-03-10 17:42:56 -07005190 if (fromCache) {
5191 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
5192 strategy, mDeviceForStrategy[strategy]);
5193 return mDeviceForStrategy[strategy];
5194 }
François Gaffie2110e042015-03-24 08:41:51 +01005195 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07005196}
5197
Eric Laurente0720872014-03-11 09:30:41 -07005198void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005199{
5200 for (int i = 0; i < NUM_STRATEGIES; i++) {
5201 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
5202 }
5203 mPreviousOutputs = mOutputs;
5204}
5205
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005206uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005207 audio_devices_t prevDevice,
5208 uint32_t delayMs)
5209{
5210 // mute/unmute strategies using an incompatible device combination
5211 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5212 // if unmuting, unmute only after the specified delay
5213 if (outputDesc->isDuplicated()) {
5214 return 0;
5215 }
5216
5217 uint32_t muteWaitMs = 0;
5218 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07005219 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005220
5221 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
5222 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07005223 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07005224 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
5225 bool doMute = false;
5226
5227 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
5228 doMute = true;
5229 outputDesc->mStrategyMutedByDevice[i] = true;
5230 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
5231 doMute = true;
5232 outputDesc->mStrategyMutedByDevice[i] = false;
5233 }
Eric Laurent99401132014-05-07 19:48:15 -07005234 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005235 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005236 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005237 // skip output if it does not share any device with current output
5238 if ((desc->supportedDevices() & outputDesc->supportedDevices())
5239 == AUDIO_DEVICE_NONE) {
5240 continue;
5241 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005242 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07005243 mute ? "muting" : "unmuting", i, curDevice);
5244 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005245 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005246 if (mute) {
5247 // FIXME: should not need to double latency if volume could be applied
5248 // immediately by the audioflinger mixer. We must account for the delay
5249 // between now and the next time the audioflinger thread for this output
5250 // will process a buffer (which corresponds to one buffer size,
5251 // usually 1/2 or 1/4 of the latency).
5252 if (muteWaitMs < desc->latency() * 2) {
5253 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005254 }
5255 }
5256 }
5257 }
5258 }
5259 }
5260
Eric Laurent99401132014-05-07 19:48:15 -07005261 // temporary mute output if device selection changes to avoid volume bursts due to
5262 // different per device volumes
5263 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005264 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5265 // temporary mute duration is conservatively set to 4 times the reported latency
5266 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5267 if (muteWaitMs < tempMuteWaitMs) {
5268 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005269 }
Eric Laurentdc462862016-07-19 12:29:53 -07005270
Eric Laurent99401132014-05-07 19:48:15 -07005271 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005272 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005273 // make sure that we do not start the temporary mute period too early in case of
5274 // delayed device change
5275 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005276 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07005277 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07005278 }
5279 }
5280 }
5281
Eric Laurente552edb2014-03-10 17:42:56 -07005282 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5283 if (muteWaitMs > delayMs) {
5284 muteWaitMs -= delayMs;
5285 usleep(muteWaitMs * 1000);
5286 return muteWaitMs;
5287 }
5288 return 0;
5289}
5290
Eric Laurentc75307b2015-03-17 15:29:32 -07005291uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005292 audio_devices_t device,
5293 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07005294 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005295 audio_patch_handle_t *patchHandle,
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005296 const char *address,
5297 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005298{
Eric Laurentc75307b2015-03-17 15:29:32 -07005299 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005300 AudioParameter param;
5301 uint32_t muteWaitMs;
5302
5303 if (outputDesc->isDuplicated()) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005304 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs,
5305 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
5306 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs,
5307 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005308 return muteWaitMs;
5309 }
5310 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5311 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07005312 if ((device != AUDIO_DEVICE_NONE) &&
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005313 ((device & outputDesc->supportedDevices()) == AUDIO_DEVICE_NONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005314 return 0;
5315 }
5316
5317 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07005318 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07005319
5320 audio_devices_t prevDevice = outputDesc->mDevice;
5321
Paul McLeanaa981192015-03-21 09:55:15 -07005322 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005323
5324 if (device != AUDIO_DEVICE_NONE) {
5325 outputDesc->mDevice = device;
5326 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005327
5328 // if the outputs are not materially active, there is no need to mute.
5329 if (requiresMuteCheck) {
5330 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
5331 } else {
5332 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5333 muteWaitMs = 0;
5334 }
Eric Laurente552edb2014-03-10 17:42:56 -07005335
5336 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005337 // the requested device is AUDIO_DEVICE_NONE
5338 // OR the requested device is the same as current device
5339 // AND force is not specified
5340 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07005341 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07005342 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
5343 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005344 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005345 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005346 return muteWaitMs;
5347 }
5348
5349 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07005350
Eric Laurente552edb2014-03-10 17:42:56 -07005351 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07005352 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005353 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005354 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07005355 DeviceVector deviceList;
5356 if ((address == NULL) || (strlen(address) == 0)) {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005357 deviceList = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurentc40d9692016-04-13 19:14:13 -07005358 } else {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005359 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
5360 device, String8(address));
5361 if (deviceDesc) deviceList.add(deviceDesc);
Eric Laurentc40d9692016-04-13 19:14:13 -07005362 }
5363
Eric Laurent1c333e22014-05-20 10:48:17 -07005364 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005365 PatchBuilder patchBuilder;
5366 patchBuilder.addSource(outputDesc);
Eric Laurent1c333e22014-05-20 10:48:17 -07005367 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005368 patchBuilder.addSink(deviceList.itemAt(i));
Eric Laurent1c333e22014-05-20 10:48:17 -07005369 }
Mikhail Naganovdc769682018-05-04 15:34:08 -07005370 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005371 }
bryant_liuf5e7e792014-08-19 20:07:05 +08005372
5373 // inform all input as well
5374 for (size_t i = 0; i < mInputs.size(); i++) {
5375 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01005376 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08005377 AudioParameter inputCmd = AudioParameter();
5378 ALOGV("%s: inform input %d of device:%d", __func__,
5379 inputDescriptor->mIoHandle, device);
5380 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
5381 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
5382 inputCmd.toString(),
5383 delayMs);
5384 }
5385 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005386 }
Eric Laurente552edb2014-03-10 17:42:56 -07005387
5388 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07005389 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005390
5391 return muteWaitMs;
5392}
5393
Eric Laurentc75307b2015-03-17 15:29:32 -07005394status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005395 int delayMs,
5396 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005397{
Eric Laurent6a94d692014-05-20 11:18:06 -07005398 ssize_t index;
5399 if (patchHandle) {
5400 index = mAudioPatches.indexOfKey(*patchHandle);
5401 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005402 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005403 }
5404 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005405 return INVALID_OPERATION;
5406 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005407 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5408 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005409 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005410 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005411 removeAudioPatch(patchDesc->mHandle);
5412 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005413 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005414 return status;
5415}
5416
5417status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5418 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005419 bool force,
5420 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005421{
5422 status_t status = NO_ERROR;
5423
Eric Laurent1f2f2232014-06-02 12:01:23 -07005424 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005425 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5426 inputDesc->mDevice = device;
5427
Mikhail Naganov708e0382018-05-30 09:53:04 -07005428 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005429 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005430 PatchBuilder patchBuilder;
5431 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005432 // AUDIO_SOURCE_HOTWORD is for internal use only:
5433 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07005434 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5435 auto result = usecase;
5436 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5437 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5438 }
5439 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07005440 //only one input device for now
Mikhail Naganovdc769682018-05-04 15:34:08 -07005441 addSource(deviceList.itemAt(0));
5442 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005443 }
5444 }
5445 return status;
5446}
5447
Eric Laurent6a94d692014-05-20 11:18:06 -07005448status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5449 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005450{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005451 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005452 ssize_t index;
5453 if (patchHandle) {
5454 index = mAudioPatches.indexOfKey(*patchHandle);
5455 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005456 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005457 }
5458 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005459 return INVALID_OPERATION;
5460 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005461 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5462 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005463 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005464 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005465 removeAudioPatch(patchDesc->mHandle);
5466 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005467 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005468 return status;
5469}
5470
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005471sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005472 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005473 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005474 audio_format_t& format,
5475 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005476 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005477{
5478 // Choose an input profile based on the requested capture parameters: select the first available
5479 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005480 //
5481 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5482 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005483
Glenn Kasten730b9262018-03-29 15:01:26 -07005484 sp<IOProfile> firstInexact;
5485 uint32_t updatedSamplingRate = 0;
5486 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5487 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005488 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005489 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005490 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005491 //updatedFormat = format;
Eric Laurent275e8e92014-11-30 15:14:47 -08005492 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005493 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005494 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005495 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005496 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005497 &channelMask /*updatedChannelMask*/,
5498 // FIXME ugly cast
5499 (audio_output_flags_t) flags,
5500 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005501 return profile;
5502 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005503 if (firstInexact == nullptr && profile->isCompatibleProfile(device, address,
5504 samplingRate,
5505 &updatedSamplingRate,
5506 format,
5507 &updatedFormat,
5508 channelMask,
5509 &updatedChannelMask,
5510 // FIXME ugly cast
5511 (audio_output_flags_t) flags,
5512 false /*exactMatchRequiredForInputFlags*/)) {
5513 firstInexact = profile;
5514 }
5515
Eric Laurente552edb2014-03-10 17:42:56 -07005516 }
5517 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005518 if (firstInexact != nullptr) {
5519 samplingRate = updatedSamplingRate;
5520 format = updatedFormat;
5521 channelMask = updatedChannelMask;
5522 return firstInexact;
5523 }
Eric Laurente552edb2014-03-10 17:42:56 -07005524 return NULL;
5525}
5526
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005527
5528audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005529 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005530{
François Gaffie036e1e92015-03-19 10:16:24 +01005531 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5532 audio_devices_t selectedDeviceFromMix =
5533 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005534
François Gaffie036e1e92015-03-19 10:16:24 +01005535 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5536 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005537 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005538 return getDeviceForInputSource(inputSource);
5539}
5540
5541audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5542{
Eric Laurentad2e7b92017-09-14 20:06:42 -07005543 // Routing
5544 // Scan the whole RouteMap to see if we have an explicit route:
5545 // if the input source in the RouteMap is the same as the argument above,
5546 // and activity count is non-zero and the device in the route descriptor is available
5547 // then select this device.
Paul McLean466dc8e2015-04-17 13:15:36 -06005548 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
5549 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
Eric Laurent2157f5b2018-04-25 18:33:02 -07005550 if ((inputSource == route->mSource) && route->isActiveOrChanged() &&
Eric Laurentad2e7b92017-09-14 20:06:42 -07005551 (mAvailableInputDevices.indexOf(route->mDeviceDescriptor) >= 0)) {
Paul McLean466dc8e2015-04-17 13:15:36 -06005552 return route->mDeviceDescriptor->type();
5553 }
5554 }
5555
5556 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005557}
5558
Eric Laurente0720872014-03-11 09:30:41 -07005559float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005560 int index,
5561 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005562{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005563 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005564
5565 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5566 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5567 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5568 // the ringtone volume
5569 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5570 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5571 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5572 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5573 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5574 }
5575
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005576 // in-call: always cap volume by voice volume + some low headroom
5577 if ((stream != AUDIO_STREAM_VOICE_CALL) &&
Eric Laurent7731b5a2018-04-06 15:47:22 -07005578 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005579 switch (stream) {
5580 case AUDIO_STREAM_SYSTEM:
5581 case AUDIO_STREAM_RING:
5582 case AUDIO_STREAM_MUSIC:
5583 case AUDIO_STREAM_ALARM:
5584 case AUDIO_STREAM_NOTIFICATION:
5585 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5586 case AUDIO_STREAM_DTMF:
5587 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005588 int voiceVolumeIndex =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005589 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, device);
Eric Laurent7731b5a2018-04-06 15:47:22 -07005590 const float maxVoiceVolDb =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005591 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, device)
Eric Laurent7731b5a2018-04-06 15:47:22 -07005592 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005593 if (volumeDB > maxVoiceVolDb) {
5594 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5595 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5596 volumeDB = maxVoiceVolDb;
5597 }
5598 } break;
5599 default:
5600 break;
5601 }
5602 }
5603
Eric Laurente552edb2014-03-10 17:42:56 -07005604 // if a headset is connected, apply the following rules to ring tones and notifications
5605 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005606 // - always attenuate notifications volume by 6dB
5607 // - attenuate ring tones volume by 6dB unless music is not playing and
5608 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005609 // - if music is playing, always limit the volume to current music volume,
5610 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005611 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005612 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5613 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5614 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005615 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005616 AUDIO_DEVICE_OUT_USB_HEADSET |
5617 AUDIO_DEVICE_OUT_HEARING_AID)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005618 ((stream_strategy == STRATEGY_SONIFICATION)
5619 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005620 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005621 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005622 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005623 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005624 // when the phone is ringing we must consider that music could have been paused just before
5625 // by the music application and behave as if music was active if the last music track was
5626 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005627 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005628 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005629 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005630 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005631 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005632 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5633 musicDevice),
5634 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005635 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5636 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005637 if (volumeDB > minVolDB) {
5638 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005639 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005640 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005641 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5642 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5643 // on A2DP, also ensure notification volume is not too low compared to media when
5644 // intended to be played
5645 if ((volumeDB > -96.0f) &&
5646 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5647 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5648 stream, device,
5649 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5650 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5651 }
5652 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005653 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5654 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005655 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005656 }
5657 }
5658
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005659 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005660}
5661
Eric Laurent3839bc02018-07-10 18:33:34 -07005662int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
5663 audio_stream_type_t srcStream,
5664 audio_stream_type_t dstStream)
5665{
5666 if (srcStream == dstStream) {
5667 return srcIndex;
5668 }
5669 float minSrc = (float)mVolumeCurves->getVolumeIndexMin(srcStream);
5670 float maxSrc = (float)mVolumeCurves->getVolumeIndexMax(srcStream);
5671 float minDst = (float)mVolumeCurves->getVolumeIndexMin(dstStream);
5672 float maxDst = (float)mVolumeCurves->getVolumeIndexMax(dstStream);
5673
5674 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
5675}
5676
Eric Laurente0720872014-03-11 09:30:41 -07005677status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005678 int index,
5679 const sp<AudioOutputDescriptor>& outputDesc,
5680 audio_devices_t device,
5681 int delayMs,
5682 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005683{
Eric Laurente552edb2014-03-10 17:42:56 -07005684 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005685 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005686 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005687 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005688 return NO_ERROR;
5689 }
François Gaffie2110e042015-03-24 08:41:51 +01005690 audio_policy_forced_cfg_t forceUseForComm =
5691 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005692 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005693 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5694 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005695 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005696 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005697 return INVALID_OPERATION;
5698 }
5699
Eric Laurentc75307b2015-03-17 15:29:32 -07005700 if (device == AUDIO_DEVICE_NONE) {
5701 device = outputDesc->device();
5702 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005703
Eric Laurentffbc80f2015-03-18 18:30:19 -07005704 float volumeDb = computeVolume(stream, index, device);
HW Leeda7581e2018-05-22 18:31:34 +08005705 if (outputDesc->isFixedVolume(device) ||
5706 // Force VoIP volume to max for bluetooth SCO
5707 ((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
5708 (device & AUDIO_DEVICE_OUT_ALL_SCO) != 0)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005709 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005710 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005711
Eric Laurentffbc80f2015-03-18 18:30:19 -07005712 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005713
Eric Laurent3b73df72014-03-11 09:06:29 -07005714 if (stream == AUDIO_STREAM_VOICE_CALL ||
5715 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005716 float voiceVolume;
5717 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005718 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurent3839bc02018-07-10 18:33:34 -07005719 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005720 } else {
5721 voiceVolume = 1.0;
5722 }
5723
Eric Laurent18fba842016-03-31 14:41:26 -07005724 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005725 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5726 mLastVoiceVolume = voiceVolume;
5727 }
5728 }
5729
5730 return NO_ERROR;
5731}
5732
Eric Laurentc75307b2015-03-17 15:29:32 -07005733void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5734 audio_devices_t device,
5735 int delayMs,
5736 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005737{
Eric Laurentc75307b2015-03-17 15:29:32 -07005738 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005739
Eric Laurent794fde22016-03-11 09:50:45 -08005740 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005741 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005742 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005743 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005744 device,
5745 delayMs,
5746 force);
5747 }
5748}
5749
Eric Laurente0720872014-03-11 09:30:41 -07005750void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005751 bool on,
5752 const sp<AudioOutputDescriptor>& outputDesc,
5753 int delayMs,
5754 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005755{
Eric Laurent72249d52015-06-08 11:12:15 -07005756 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5757 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005758 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005759 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005760 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005761 }
5762 }
5763}
5764
Eric Laurente0720872014-03-11 09:30:41 -07005765void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005766 bool on,
5767 const sp<AudioOutputDescriptor>& outputDesc,
5768 int delayMs,
5769 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005770{
Eric Laurente552edb2014-03-10 17:42:56 -07005771 if (device == AUDIO_DEVICE_NONE) {
5772 device = outputDesc->device();
5773 }
5774
Eric Laurentc75307b2015-03-17 15:29:32 -07005775 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5776 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005777
5778 if (on) {
5779 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005780 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005781 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005782 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005783 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005784 }
5785 }
5786 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5787 outputDesc->mMuteCount[stream]++;
5788 } else {
5789 if (outputDesc->mMuteCount[stream] == 0) {
5790 ALOGV("setStreamMute() unmuting non muted stream!");
5791 return;
5792 }
5793 if (--outputDesc->mMuteCount[stream] == 0) {
5794 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005795 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005796 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005797 device,
5798 delayMs);
5799 }
5800 }
5801}
5802
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005803audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5804{
5805 // flags to stream type mapping
5806 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5807 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5808 }
5809 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5810 return AUDIO_STREAM_BLUETOOTH_SCO;
5811 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005812 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5813 return AUDIO_STREAM_TTS;
5814 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005815
5816 // usage to stream type mapping
5817 switch (attr->usage) {
5818 case AUDIO_USAGE_MEDIA:
5819 case AUDIO_USAGE_GAME:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005820 case AUDIO_USAGE_ASSISTANT:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005821 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5822 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005823 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5824 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005825 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5826 return AUDIO_STREAM_SYSTEM;
5827 case AUDIO_USAGE_VOICE_COMMUNICATION:
5828 return AUDIO_STREAM_VOICE_CALL;
5829
5830 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5831 return AUDIO_STREAM_DTMF;
5832
5833 case AUDIO_USAGE_ALARM:
5834 return AUDIO_STREAM_ALARM;
5835 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5836 return AUDIO_STREAM_RING;
5837
5838 case AUDIO_USAGE_NOTIFICATION:
5839 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5840 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5841 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5842 case AUDIO_USAGE_NOTIFICATION_EVENT:
5843 return AUDIO_STREAM_NOTIFICATION;
5844
5845 case AUDIO_USAGE_UNKNOWN:
5846 default:
5847 return AUDIO_STREAM_MUSIC;
5848 }
5849}
Eric Laurente83b55d2014-11-14 10:06:21 -08005850
François Gaffie53615e22015-03-19 09:24:12 +01005851bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5852{
Eric Laurente83b55d2014-11-14 10:06:21 -08005853 // has flags that map to a strategy?
5854 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5855 return true;
5856 }
5857
5858 // has known usage?
5859 switch (paa->usage) {
5860 case AUDIO_USAGE_UNKNOWN:
5861 case AUDIO_USAGE_MEDIA:
5862 case AUDIO_USAGE_VOICE_COMMUNICATION:
5863 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5864 case AUDIO_USAGE_ALARM:
5865 case AUDIO_USAGE_NOTIFICATION:
5866 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5867 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5868 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5869 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5870 case AUDIO_USAGE_NOTIFICATION_EVENT:
5871 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5872 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5873 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5874 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005875 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005876 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005877 break;
5878 default:
5879 return false;
5880 }
5881 return true;
5882}
5883
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005884bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005885 routing_strategy strategy, uint32_t inPastMs,
5886 nsecs_t sysTime) const
5887{
5888 if ((sysTime == 0) && (inPastMs != 0)) {
5889 sysTime = systemTime();
5890 }
Eric Laurent794fde22016-03-11 09:50:45 -08005891 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005892 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5893 (NUM_STRATEGIES == strategy)) &&
5894 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5895 return true;
5896 }
5897 }
5898 return false;
5899}
5900
Eric Laurent484e9272018-06-07 17:29:23 -07005901bool AudioPolicyManager::isStrategyActiveOnSameModule(const sp<AudioOutputDescriptor>& outputDesc,
5902 routing_strategy strategy, uint32_t inPastMs,
5903 nsecs_t sysTime) const
5904{
5905 for (size_t i = 0; i < mOutputs.size(); i++) {
5906 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5907 if (outputDesc->sharesHwModuleWith(desc)
5908 && isStrategyActive(desc, strategy, inPastMs, sysTime)) {
5909 return true;
5910 }
5911 }
5912 return false;
5913}
5914
François Gaffie2110e042015-03-24 08:41:51 +01005915audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5916{
5917 return mEngine->getForceUse(usage);
5918}
5919
5920bool AudioPolicyManager::isInCall()
5921{
5922 return isStateInCall(mEngine->getPhoneState());
5923}
5924
5925bool AudioPolicyManager::isStateInCall(int state)
5926{
5927 return is_state_in_call(state);
5928}
5929
Eric Laurentd60560a2015-04-10 11:31:20 -07005930void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5931{
5932 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005933 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5934 if (sourceDesc->srcDevice()->equals(deviceDesc)) {
5935 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->portId());
5936 stopAudioSource(sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005937 }
5938 }
5939
5940 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5941 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5942 bool release = false;
5943 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5944 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5945 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5946 source->ext.device.type == deviceDesc->type()) {
5947 release = true;
5948 }
5949 }
5950 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5951 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5952 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5953 sink->ext.device.type == deviceDesc->type()) {
5954 release = true;
5955 }
5956 }
5957 if (release) {
5958 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5959 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5960 }
5961 }
5962}
5963
Phil Burk09bc4612016-02-24 15:58:15 -08005964// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005965void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5966 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005967 // TODO Set this based on Config properties.
5968 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005969
5970 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5971 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005972 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005973
jiabin81772902018-04-02 17:52:27 -07005974 // If MANUAL, keep the supported surround sound formats as current enabled ones.
5975 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
5976 formats.clear();
5977 for (auto it = mSurroundFormats.begin(); it != mSurroundFormats.end(); it++) {
5978 formats.add(*it);
Phil Burk09bc4612016-02-24 15:58:15 -08005979 }
jiabin81772902018-04-02 17:52:27 -07005980 // Always enable IEC61937 when in MANUAL mode.
5981 formats.add(AUDIO_FORMAT_IEC61937);
5982 } else { // NEVER, AUTO or ALWAYS
5983 // Analyze original support for various formats.
5984 bool supportsAC3 = false;
5985 bool supportsOtherSurround = false;
5986 bool supportsIEC61937 = false;
5987 mSurroundFormats.clear();
5988 for (ssize_t formatIndex = 0; formatIndex < (ssize_t)formats.size(); formatIndex++) {
5989 audio_format_t format = formats[formatIndex];
5990 switch (format) {
5991 case AUDIO_FORMAT_AC3:
5992 supportsAC3 = true;
5993 break;
5994 case AUDIO_FORMAT_E_AC3:
5995 case AUDIO_FORMAT_DTS:
5996 case AUDIO_FORMAT_DTS_HD:
5997 // If ALWAYS, remove all other surround formats here
5998 // since we will add them later.
5999 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
6000 formats.removeAt(formatIndex);
6001 formatIndex--;
6002 }
6003 supportsOtherSurround = true;
6004 break;
6005 case AUDIO_FORMAT_IEC61937:
6006 supportsIEC61937 = true;
6007 break;
6008 default:
6009 break;
6010 }
6011 }
Phil Burk09bc4612016-02-24 15:58:15 -08006012
jiabin81772902018-04-02 17:52:27 -07006013 // Modify formats based on surround preferences.
6014 // If NEVER, remove support for surround formats.
6015 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
6016 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
6017 // Remove surround sound related formats.
6018 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
6019 audio_format_t format = formats[formatIndex];
6020 switch(format) {
6021 case AUDIO_FORMAT_AC3:
6022 case AUDIO_FORMAT_E_AC3:
6023 case AUDIO_FORMAT_DTS:
6024 case AUDIO_FORMAT_DTS_HD:
6025 case AUDIO_FORMAT_IEC61937:
6026 formats.removeAt(formatIndex);
6027 break;
6028 default:
6029 formatIndex++; // keep it
6030 break;
6031 }
6032 }
6033 supportsAC3 = false;
6034 supportsOtherSurround = false;
6035 supportsIEC61937 = false;
6036 }
6037 } else { // AUTO or ALWAYS
6038 // Most TVs support AC3 even if they do not report it in the EDID.
6039 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
6040 && !supportsAC3) {
6041 formats.add(AUDIO_FORMAT_AC3);
6042 supportsAC3 = true;
6043 }
6044
6045 // If ALWAYS, add support for raw surround formats if all are missing.
6046 // This assumes that if any of these formats are reported by the HAL
6047 // then the report is valid and should not be modified.
6048 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
6049 formats.add(AUDIO_FORMAT_E_AC3);
6050 formats.add(AUDIO_FORMAT_DTS);
6051 formats.add(AUDIO_FORMAT_DTS_HD);
6052 supportsOtherSurround = true;
6053 }
6054
6055 // Add support for IEC61937 if any raw surround supported.
6056 // The HAL could do this but add it here, just in case.
6057 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
6058 formats.add(AUDIO_FORMAT_IEC61937);
6059 supportsIEC61937 = true;
6060 }
6061
6062 // Add reported surround sound formats to enabled surround formats.
6063 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
Phil Burk07ac1142016-03-25 13:39:29 -07006064 audio_format_t format = formats[formatIndex];
6065 switch(format) {
6066 case AUDIO_FORMAT_AC3:
6067 case AUDIO_FORMAT_E_AC3:
6068 case AUDIO_FORMAT_DTS:
6069 case AUDIO_FORMAT_DTS_HD:
jiabin81772902018-04-02 17:52:27 -07006070 case AUDIO_FORMAT_AAC_LC:
6071 case AUDIO_FORMAT_DOLBY_TRUEHD:
6072 case AUDIO_FORMAT_E_AC3_JOC:
6073 mSurroundFormats.insert(format);
Phil Burk07ac1142016-03-25 13:39:29 -07006074 default:
Phil Burk07ac1142016-03-25 13:39:29 -07006075 break;
6076 }
Phil Burk09bc4612016-02-24 15:58:15 -08006077 }
Phil Burk07ac1142016-03-25 13:39:29 -07006078 }
Phil Burk09bc4612016-02-24 15:58:15 -08006079 }
Phil Burk0709b0a2016-03-31 12:54:57 -07006080}
6081
6082// Modify the list of channel masks supported.
6083void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
6084 ChannelsVector &channelMasks = *channelMasksPtr;
6085 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6086 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
6087
6088 // If NEVER, then remove support for channelMasks > stereo.
6089 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
6090 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
6091 audio_channel_mask_t channelMask = channelMasks[maskIndex];
6092 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
6093 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
6094 channelMasks.removeAt(maskIndex);
6095 } else {
6096 maskIndex++;
6097 }
6098 }
jiabin81772902018-04-02 17:52:27 -07006099 // If ALWAYS or MANUAL, then make sure we at least support 5.1
6100 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
6101 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006102 bool supports5dot1 = false;
6103 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006104 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006105 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
6106 supports5dot1 = true;
6107 break;
6108 }
6109 }
6110 // If not then add 5.1 support.
6111 if (!supports5dot1) {
6112 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
6113 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
6114 }
Phil Burk09bc4612016-02-24 15:58:15 -08006115 }
6116}
6117
Phil Burk00eeb322016-03-31 12:41:00 -07006118void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
6119 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01006120 AudioProfileVector &profiles)
6121{
6122 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07006123
François Gaffie112b0af2015-11-19 16:13:25 +01006124 // Format MUST be checked first to update the list of AudioProfile
6125 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006126 reply = mpClientInterface->getParameters(
6127 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07006128 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006129 AudioParameter repliedParameters(reply);
6130 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006131 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01006132 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
6133 return;
6134 }
Phil Burk09bc4612016-02-24 15:58:15 -08006135 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07006136 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006137 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07006138 }
Phil Burk09bc4612016-02-24 15:58:15 -08006139 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01006140 }
François Gaffie112b0af2015-11-19 16:13:25 +01006141
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006142 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08006143 ChannelsVector channelMasks;
6144 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01006145 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07006146 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01006147
6148 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006149 reply = mpClientInterface->getParameters(
6150 ioHandle,
6151 requestedParameters.toString() + ";" +
6152 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01006153 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006154 AudioParameter repliedParameters(reply);
6155 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006156 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006157 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01006158 }
6159 }
6160 if (profiles.hasDynamicChannelsFor(format)) {
6161 reply = mpClientInterface->getParameters(ioHandle,
6162 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07006163 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01006164 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006165 AudioParameter repliedParameters(reply);
6166 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006167 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006168 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07006169 if (device == AUDIO_DEVICE_OUT_HDMI) {
6170 filterSurroundChannelMasks(&channelMasks);
6171 }
François Gaffie112b0af2015-11-19 16:13:25 +01006172 }
6173 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08006174 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006175 }
6176}
Eric Laurentd60560a2015-04-10 11:31:20 -07006177
Mikhail Naganovdc769682018-05-04 15:34:08 -07006178status_t AudioPolicyManager::installPatch(const char *caller,
6179 audio_patch_handle_t *patchHandle,
6180 AudioIODescriptorInterface *ioDescriptor,
6181 const struct audio_patch *patch,
6182 int delayMs)
6183{
6184 ssize_t index = mAudioPatches.indexOfKey(
6185 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6186 *patchHandle : ioDescriptor->getPatchHandle());
6187 sp<AudioPatch> patchDesc;
6188 status_t status = installPatch(
6189 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6190 if (status == NO_ERROR) {
6191 ioDescriptor->setPatchHandle(patchDesc->mHandle);
6192 }
6193 return status;
6194}
6195
6196status_t AudioPolicyManager::installPatch(const char *caller,
6197 ssize_t index,
6198 audio_patch_handle_t *patchHandle,
6199 const struct audio_patch *patch,
6200 int delayMs,
6201 uid_t uid,
6202 sp<AudioPatch> *patchDescPtr)
6203{
6204 sp<AudioPatch> patchDesc;
6205 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6206 if (index >= 0) {
6207 patchDesc = mAudioPatches.valueAt(index);
6208 afPatchHandle = patchDesc->mAfPatchHandle;
6209 }
6210
6211 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6212 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6213 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6214 if (status == NO_ERROR) {
6215 if (index < 0) {
6216 patchDesc = new AudioPatch(patch, uid);
6217 addAudioPatch(patchDesc->mHandle, patchDesc);
6218 } else {
6219 patchDesc->mPatch = *patch;
6220 }
6221 patchDesc->mAfPatchHandle = afPatchHandle;
6222 if (patchHandle) {
6223 *patchHandle = patchDesc->mHandle;
6224 }
6225 nextAudioPortGeneration();
6226 mpClientInterface->onAudioPatchListUpdate();
6227 }
6228 if (patchDescPtr) *patchDescPtr = patchDesc;
6229 return status;
6230}
6231
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006232} // namespace android