blob: e4f3cf12a0de974d85ad65ed63cc7fffd61c0b24 [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
Eric Laurente552edb2014-03-10 17:42:56 -07001517 return NO_ERROR;
1518}
1519
Eric Laurent8fc147b2018-07-22 19:13:55 -07001520status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001521{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001522 ALOGV("%s portId %d", __FUNCTION__, portId);
1523
1524 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1525 if (outputDesc == 0) {
1526 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001527 return BAD_VALUE;
1528 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001529 sp<TrackClientDescriptor> client = outputDesc->clients()[portId];
1530 audio_stream_type_t stream = client->stream();
1531 audio_session_t session = client->session();
Eric Laurente552edb2014-03-10 17:42:56 -07001532
Eric Laurent8fc147b2018-07-22 19:13:55 -07001533 ALOGV("stopOutput() output %d, stream %d, session %d", outputDesc->mIoHandle, stream, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001534
Eric Laurentc75307b2015-03-17 15:29:32 -07001535 if (outputDesc->mRefCount[stream] == 1) {
1536 // Automatically disable the remote submix input when output is stopped on a
1537 // re routing mix of type MIX_TYPE_RECORDERS
1538 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1539 outputDesc->mPolicyMix != NULL &&
1540 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1541 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1542 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001543 outputDesc->mPolicyMix->mDeviceAddress,
Eric Laurentc75307b2015-03-17 15:29:32 -07001544 "remote-submix");
1545 }
1546 }
1547
1548 // Routing?
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001549 bool forceDeviceUpdate = false;
Eric Laurentc75307b2015-03-17 15:29:32 -07001550 if (outputDesc->mRefCount[stream] > 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001551 int activityCount = mOutputRoutes.decRouteActivity(session);
1552 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1553
1554 if (forceDeviceUpdate) {
1555 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1556 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001557 }
1558
Eric Laurent3974e3b2017-12-07 17:58:43 -08001559 status_t status = stopSource(outputDesc, stream, forceDeviceUpdate);
1560
Eric Laurent733ce942017-12-07 12:18:25 -08001561 if (status == NO_ERROR ) {
1562 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001563 }
1564 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001565}
1566
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001567status_t AudioPolicyManager::stopSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001568 audio_stream_type_t stream,
1569 bool forceDeviceUpdate)
Eric Laurentc75307b2015-03-17 15:29:32 -07001570{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001571 // always handle stream stop, check which stream type is stopping
1572 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1573
Eric Laurente552edb2014-03-10 17:42:56 -07001574 if (outputDesc->mRefCount[stream] > 0) {
1575 // decrement usage count of this stream on the output
1576 outputDesc->changeRefCount(stream, -1);
Paul McLeanaa981192015-03-21 09:55:15 -07001577
Eric Laurente552edb2014-03-10 17:42:56 -07001578 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001579 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001580 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001581 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001582 // delay the device switch by twice the latency because stopOutput() is executed when
1583 // the track stop() command is received and at that time the audio track buffer can
1584 // still contain data that needs to be drained. The latency only covers the audio HAL
1585 // and kernel buffers. Also the latency does not always include additional delay in the
1586 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001587 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001588
1589 // force restoring the device selection on other active outputs if it differs from the
1590 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001591 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001592 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001593 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001594 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001595 desc->isActive() &&
1596 outputDesc->sharesHwModuleWith(desc) &&
1597 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001598 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1599 bool force = desc->device() != newDevice2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001600
Eric Laurentc75307b2015-03-17 15:29:32 -07001601 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001602 newDevice2,
1603 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001604 delayMs);
1605 // re-apply device specific volume if not done by setOutputDevice()
1606 if (!force) {
1607 applyStreamVolumes(desc, newDevice2, delayMs);
1608 }
Eric Laurente552edb2014-03-10 17:42:56 -07001609 }
1610 }
1611 // update the outputs if stopping one with a stream that can affect notification routing
1612 handleNotificationRoutingForStream(stream);
1613 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001614
1615 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1616 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1617 setStrategyMute(STRATEGY_SONIFICATION, false, outputDesc);
1618 }
1619
Eric Laurent36829f92017-04-07 19:04:42 -07001620 if (stream == AUDIO_STREAM_MUSIC) {
1621 selectOutputForMusicEffects();
1622 }
Eric Laurente552edb2014-03-10 17:42:56 -07001623 return NO_ERROR;
1624 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001625 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001626 return INVALID_OPERATION;
1627 }
1628}
1629
Eric Laurent8fc147b2018-07-22 19:13:55 -07001630void AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001631{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001632 ALOGV("%s portId %d", __FUNCTION__, portId);
1633
1634 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1635 if (outputDesc == 0) {
1636 ALOGW("releaseOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001637 return;
1638 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001639 sp<TrackClientDescriptor> client = outputDesc->clients()[portId];
1640 audio_session_t session = client->session();
1641
1642 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001643
Paul McLeanaa981192015-03-21 09:55:15 -07001644 // Routing
1645 mOutputRoutes.removeRoute(session);
1646
Eric Laurent8fc147b2018-07-22 19:13:55 -07001647 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1648 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001649 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07001650 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001651 return;
1652 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001653 if (--outputDesc->mDirectOpenCount == 0) {
1654 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07001655 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001656 }
1657 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001658 outputDesc->clients().erase(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001659}
1660
1661
Eric Laurentcaf7f482014-11-25 17:50:47 -08001662status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1663 audio_io_handle_t *input,
1664 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001665 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001666 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001667 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001668 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001669 input_type_t *inputType,
1670 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001671{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001672 ALOGV("getInputForAttr() source %d, sampling rate %d, format %#x, channel mask %#x,"
Eric Laurentcaf7f482014-11-25 17:50:47 -08001673 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001674 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001675
Eric Laurentad2e7b92017-09-14 20:06:42 -07001676 status_t status = NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -08001677 // handle legacy remote submix case where the address was not always specified
1678 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001679 audio_source_t halInputSource;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001680 audio_source_t inputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001681 AudioMix *policyMix = NULL;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001682 DeviceVector inputDevices;
Eric Laurent8fc147b2018-07-22 19:13:55 -07001683 sp<AudioInputDescriptor> inputDesc;
1684 sp<RecordClientDescriptor> clientDesc;
1685 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Eric Laurent20b9ef02016-12-05 11:03:16 -08001686
Eric Laurentfe231122017-11-17 17:48:06 -08001687 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1688 inputSource = AUDIO_SOURCE_MIC;
1689 }
1690
Paul McLean466dc8e2015-04-17 13:15:36 -06001691 // Explicit routing?
1692 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -07001693 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
jiabinc0c831a2018-01-29 17:55:15 -08001694 deviceDesc = mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001695 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001696 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
Paul McLean466dc8e2015-04-17 13:15:36 -06001697
Eric Laurentad2e7b92017-09-14 20:06:42 -07001698 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1699 // possible
1700 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1701 *input != AUDIO_IO_HANDLE_NONE) {
1702 ssize_t index = mInputs.indexOfKey(*input);
1703 if (index < 0) {
1704 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1705 status = BAD_VALUE;
1706 goto error;
1707 }
1708 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1709 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1710 if (audioSession == 0) {
1711 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1712 status = BAD_VALUE;
1713 goto error;
1714 }
1715 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1716 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001717 // corresponds to a new client and is only permitted from the same UID.
1718 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurentad2e7b92017-09-14 20:06:42 -07001719 if (audioSession->openCount() == 1) {
1720 audioSession->setUid(uid);
1721 } else if (audioSession->uid() != uid) {
Eric Laurent331679c2018-04-16 17:03:16 -07001722 if (!audioSession->isSilenced()) {
1723 ALOGW("getInputForAttr() bad uid %d for session %d uid %d",
1724 uid, session, audioSession->uid());
1725 status = INVALID_OPERATION;
1726 goto error;
1727 }
1728 audioSession->setUid(uid);
1729 audioSession->setSilenced(false);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001730 }
1731 audioSession->changeOpenCount(1);
1732 *inputType = API_INPUT_LEGACY;
1733 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1734 *portId = AudioPort::getNextUniqueId();
1735 }
Mikhail Naganov708e0382018-05-30 09:53:04 -07001736 inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(inputDesc->mDevice);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001737 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1738 : AUDIO_PORT_HANDLE_NONE;
1739 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
1740
Eric Laurent8fc147b2018-07-22 19:13:55 -07001741 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001742 }
1743
1744 *input = AUDIO_IO_HANDLE_NONE;
1745 *inputType = API_INPUT_INVALID;
1746
Eric Laurentad2e7b92017-09-14 20:06:42 -07001747 halInputSource = inputSource;
1748
1749 // TODO: check for existing client for this port ID
1750 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1751 *portId = AudioPort::getNextUniqueId();
1752 }
1753
1754 audio_devices_t device;
1755
Eric Laurentc447ded2015-01-06 08:47:05 -08001756 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001757 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001758 status = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
1759 if (status != NO_ERROR) {
1760 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001761 }
1762 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001763 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1764 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001765 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001766 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001767 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001768 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001769 status = BAD_VALUE;
1770 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001771 }
Eric Laurentc722f302014-12-10 11:21:49 -08001772 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001773 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001774 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1775 // there is an external policy, but this input is attached to a mix of recorders,
1776 // meaning it receives audio injected into the framework, so the recorder doesn't
1777 // know about it and is therefore considered "legacy"
1778 *inputType = API_INPUT_LEGACY;
1779 } else {
1780 // recording a mix of players defined by an external policy, we're rerouting for
1781 // an external policy
1782 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1783 }
Eric Laurentc722f302014-12-10 11:21:49 -08001784 } else if (audio_is_remote_submix_device(device)) {
1785 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001786 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001787 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1788 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001789 } else {
1790 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001791 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001792
Eric Laurent599c7582015-12-07 18:05:55 -08001793 }
1794
1795 *input = getInputForDevice(device, address, session, uid, inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001796 config, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001797 policyMix);
1798 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001799 status = INVALID_OPERATION;
1800 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001801 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001802
Mikhail Naganov708e0382018-05-30 09:53:04 -07001803 inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -07001804 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1805 : AUDIO_PORT_HANDLE_NONE;
1806
Eric Laurent8fc147b2018-07-22 19:13:55 -07001807exit:
1808 clientDesc = new RecordClientDescriptor(*portId, uid, session,
1809 *attr, *config, requestedDeviceId, inputSource, flags);
1810 inputDesc = mInputs.valueFor(*input);
1811 inputDesc->clients().emplace(*portId, clientDesc);
1812
1813 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
1814 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001815
Eric Laurent599c7582015-12-07 18:05:55 -08001816 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001817
1818error:
1819 mInputRoutes.removeRoute(session);
1820 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001821}
1822
1823
1824audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1825 String8 address,
1826 audio_session_t session,
1827 uid_t uid,
1828 audio_source_t inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001829 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08001830 audio_input_flags_t flags,
1831 AudioMix *policyMix)
1832{
1833 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1834 audio_source_t halInputSource = inputSource;
1835 bool isSoundTrigger = false;
1836
1837 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1838 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1839 if (index >= 0) {
1840 input = mSoundTriggerSessions.valueFor(session);
1841 isSoundTrigger = true;
1842 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1843 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1844 } else {
1845 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001846 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001847 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08001848 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001849 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001850 }
1851
Andy Hungf129b032015-04-07 13:45:50 -07001852 // find a compatible input profile (not necessarily identical in parameters)
1853 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08001854 // sampling rate and flags may be updated by getInputProfile
1855 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
1856 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07001857 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08001858 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07001859 audio_input_flags_t profileFlags = flags;
1860 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07001861 profileFormat = config->format; // reset each time through loop, in case it is updated
Eric Laurent275e8e92014-11-30 15:14:47 -08001862 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001863 profileSamplingRate, profileFormat, profileChannelMask,
1864 profileFlags);
1865 if (profile != 0) {
1866 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001867 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1868 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001869 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1870 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1871 } else { // fail
Glenn Kastenfaa10a62017-05-25 15:52:05 -07001872 ALOGW("getInputForDevice() could not find profile for device 0x%X, "
Eric Laurentfe231122017-11-17 17:48:06 -08001873 "sampling rate %u, format %#x, channel mask 0x%X, flags %#x",
1874 device, config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001875 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001876 }
Eric Laurente552edb2014-03-10 17:42:56 -07001877 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001878 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08001879 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08001880 if (samplingRate == 0) {
1881 samplingRate = profileSamplingRate;
1882 }
Eric Laurente552edb2014-03-10 17:42:56 -07001883
Eric Laurent322b4d22015-04-03 15:57:54 -07001884 if (profile->getModuleHandle() == 0) {
1885 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001886 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001887 }
1888
Eric Laurent599c7582015-12-07 18:05:55 -08001889 sp<AudioSession> audioSession = new AudioSession(session,
Eric Laurentfe231122017-11-17 17:48:06 -08001890 inputSource,
1891 config->format,
1892 samplingRate,
1893 config->channel_mask,
1894 flags,
1895 uid,
Eric Laurenta18dced2018-07-20 15:14:54 -07001896 isSoundTrigger);
Eric Laurent599c7582015-12-07 18:05:55 -08001897
Eric Laurent3974e3b2017-12-07 17:58:43 -08001898 if (!profile->canOpenNewIo()) {
1899 return AUDIO_IO_HANDLE_NONE;
1900 }
1901
Eric Laurentfe231122017-11-17 17:48:06 -08001902 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001903
Eric Laurentfe231122017-11-17 17:48:06 -08001904 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
1905 lConfig.sample_rate = profileSamplingRate;
1906 lConfig.channel_mask = profileChannelMask;
1907 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07001908
Eric Laurent53b810e2017-12-10 17:25:10 -08001909 if (address == "") {
Mikhail Naganov708e0382018-05-30 09:53:04 -07001910 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -08001911 // the inputs vector must be of size >= 1, but we don't want to crash here
1912 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress : String8("");
1913 }
1914
Eric Laurentfe231122017-11-17 17:48:06 -08001915 status_t status = inputDesc->open(&lConfig, device, address,
1916 halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001917
1918 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001919 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08001920 (profileSamplingRate != lConfig.sample_rate) ||
1921 !audio_formats_match(profileFormat, lConfig.format) ||
1922 (profileChannelMask != lConfig.channel_mask)) {
1923 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001924 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08001925 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001926 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001927 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07001928 }
Eric Laurent599c7582015-12-07 18:05:55 -08001929 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001930 }
1931
Eric Laurentc722f302014-12-10 11:21:49 -08001932 inputDesc->mPolicyMix = policyMix;
Eric Laurent599c7582015-12-07 18:05:55 -08001933 inputDesc->addAudioSession(session, audioSession);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001934
Eric Laurent599c7582015-12-07 18:05:55 -08001935 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001936 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001937
Eric Laurent599c7582015-12-07 18:05:55 -08001938 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001939}
1940
Eric Laurentbb948092017-01-23 18:33:30 -08001941//static
1942bool AudioPolicyManager::isConcurrentSource(audio_source_t source)
1943{
1944 return (source == AUDIO_SOURCE_HOTWORD) ||
1945 (source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
1946 (source == AUDIO_SOURCE_FM_TUNER);
1947}
1948
Eric Laurentfb66dd92016-01-28 18:32:03 -08001949bool AudioPolicyManager::isConcurentCaptureAllowed(const sp<AudioInputDescriptor>& inputDesc,
1950 const sp<AudioSession>& audioSession)
1951{
1952 // Do not allow capture if an active voice call is using a software patch and
1953 // the call TX source device is on the same HW module.
1954 // FIXME: would be better to refine to only inputs whose profile connects to the
1955 // call TX device but this information is not in the audio patch
1956 if (mCallTxPatch != 0 &&
1957 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1958 return false;
1959 }
1960
1961 // starting concurrent capture is enabled if:
1962 // 1) capturing for re-routing
1963 // 2) capturing for HOTWORD source
1964 // 3) capturing for FM TUNER source
1965 // 3) All other active captures are either for re-routing or HOTWORD
1966
1967 if (is_virtual_input_device(inputDesc->mDevice) ||
Eric Laurentbb948092017-01-23 18:33:30 -08001968 isConcurrentSource(audioSession->inputSource())) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001969 return true;
1970 }
1971
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001972 for (const auto& activeInput : mInputs.getActiveInputs()) {
Eric Laurentbb948092017-01-23 18:33:30 -08001973 if (!isConcurrentSource(activeInput->inputSource(true)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001974 !is_virtual_input_device(activeInput->mDevice)) {
1975 return false;
1976 }
1977 }
1978
1979 return true;
1980}
1981
Chris Thornton2b864642017-06-27 21:26:07 -07001982// FIXME: remove when concurrent capture is ready. This is a hack to work around bug b/63083537.
1983bool AudioPolicyManager::soundTriggerSupportsConcurrentCapture() {
1984 if (!mHasComputedSoundTriggerSupportsConcurrentCapture) {
1985 bool soundTriggerSupportsConcurrentCapture = false;
1986 unsigned int numModules = 0;
1987 struct sound_trigger_module_descriptor* nModules = NULL;
1988
1989 status_t status = SoundTrigger::listModules(nModules, &numModules);
1990 if (status == NO_ERROR && numModules != 0) {
1991 nModules = (struct sound_trigger_module_descriptor*) calloc(
1992 numModules, sizeof(struct sound_trigger_module_descriptor));
1993 if (nModules == NULL) {
1994 // We failed to malloc the buffer, so just say no for now, and hope that we have more
1995 // ram the next time this function is called.
1996 ALOGE("Failed to allocate buffer for module descriptors");
1997 return false;
1998 }
1999
2000 status = SoundTrigger::listModules(nModules, &numModules);
2001 if (status == NO_ERROR) {
2002 soundTriggerSupportsConcurrentCapture = true;
2003 for (size_t i = 0; i < numModules; ++i) {
2004 soundTriggerSupportsConcurrentCapture &=
2005 nModules[i].properties.concurrent_capture;
2006 }
2007 }
2008 free(nModules);
2009 }
2010 mSoundTriggerSupportsConcurrentCapture = soundTriggerSupportsConcurrentCapture;
2011 mHasComputedSoundTriggerSupportsConcurrentCapture = true;
2012 }
2013 return mSoundTriggerSupportsConcurrentCapture;
2014}
2015
Eric Laurentfb66dd92016-01-28 18:32:03 -08002016
Eric Laurent8fc147b2018-07-22 19:13:55 -07002017status_t AudioPolicyManager::startInput(audio_port_handle_t portId,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002018 bool silenced,
Eric Laurentfb66dd92016-01-28 18:32:03 -08002019 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07002020{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002021 *concurrency = API_INPUT_CONCURRENCY_NONE;
2022
2023 ALOGV("%s portId %d", __FUNCTION__, portId);
2024
2025 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2026 if (inputDesc == 0) {
2027 ALOGW("startInput() no input for client %d", portId);
2028 return BAD_VALUE;
2029 }
2030 sp<RecordClientDescriptor> client = inputDesc->clients()[portId];
2031 audio_session_t session = client->session();
2032 audio_io_handle_t input = inputDesc->mIoHandle;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002033
2034 ALOGV("AudioPolicyManager::startInput(input:%d, session:%d, silenced:%d, concurrency:%d)",
2035 input, session, silenced, *concurrency);
2036
Eric Laurent599c7582015-12-07 18:05:55 -08002037 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
2038 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07002039 ALOGW("startInput() unknown session %d on input %d", session, input);
2040 return BAD_VALUE;
2041 }
2042
Eric Laurent74708e72017-04-07 17:13:42 -07002043 if (!is_virtual_input_device(inputDesc->mDevice)) {
2044 if (mCallTxPatch != 0 &&
2045 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
2046 ALOGW("startInput(%d) failed: call in progress", input);
Ray Essick84e84a52018-05-03 18:45:07 -07002047 *concurrency |= API_INPUT_CONCURRENCY_CALL;
Eric Laurent74708e72017-04-07 17:13:42 -07002048 return INVALID_OPERATION;
2049 }
2050
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002051 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002052
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002053 // If a UID is idle and records silence and another not silenced recording starts
2054 // from another UID (idle or active) we stop the current idle UID recording in
2055 // favor of the new one - "There can be only one" TM
2056 if (!silenced) {
2057 for (const auto& activeDesc : activeInputs) {
2058 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
2059 activeDesc->getId() == inputDesc->getId()) {
2060 continue;
2061 }
2062
2063 AudioSessionCollection activeSessions = activeDesc->getAudioSessions(
2064 true /*activeOnly*/);
2065 sp<AudioSession> activeSession = activeSessions.valueAt(0);
2066 if (activeSession->isSilenced()) {
Eric Laurent8fc147b2018-07-22 19:13:55 -07002067 closeSession(activeDesc, activeSession);
2068 ALOGV("startInput() session %d stopping silenced session %d", session, activeSession->session());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002069 activeInputs = mInputs.getActiveInputs();
2070 }
2071 }
2072 }
2073
2074 for (const auto& activeDesc : activeInputs) {
Eric Laurentcb4dae22017-07-01 19:39:32 -07002075 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
2076 activeDesc->getId() == inputDesc->getId()) {
2077 continue;
2078 }
2079
Eric Laurent74708e72017-04-07 17:13:42 -07002080 audio_source_t activeSource = activeDesc->inputSource(true);
2081 if (audioSession->inputSource() == AUDIO_SOURCE_HOTWORD) {
2082 if (activeSource == AUDIO_SOURCE_HOTWORD) {
2083 if (activeDesc->hasPreemptedSession(session)) {
2084 ALOGW("startInput(%d) failed for HOTWORD: "
2085 "other input %d already started for HOTWORD",
2086 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07002087 *concurrency |= API_INPUT_CONCURRENCY_HOTWORD;
Eric Laurent74708e72017-04-07 17:13:42 -07002088 return INVALID_OPERATION;
2089 }
2090 } else {
2091 ALOGV("startInput(%d) failed for HOTWORD: other input %d already started",
2092 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07002093 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07002094 return INVALID_OPERATION;
2095 }
2096 } else {
2097 if (activeSource != AUDIO_SOURCE_HOTWORD) {
2098 ALOGW("startInput(%d) failed: other input %d already started",
2099 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07002100 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07002101 return INVALID_OPERATION;
2102 }
2103 }
2104 }
2105
Chris Thornton2b864642017-06-27 21:26:07 -07002106 // We only need to check if the sound trigger session supports concurrent capture if the
2107 // input is also a sound trigger input. Otherwise, we should preempt any hotword stream
2108 // that's running.
2109 const bool allowConcurrentWithSoundTrigger =
2110 inputDesc->isSoundTrigger() ? soundTriggerSupportsConcurrentCapture() : false;
2111
Eric Laurent74708e72017-04-07 17:13:42 -07002112 // if capture is allowed, preempt currently active HOTWORD captures
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002113 for (const auto& activeDesc : activeInputs) {
Chris Thornton2b864642017-06-27 21:26:07 -07002114 if (allowConcurrentWithSoundTrigger && activeDesc->isSoundTrigger()) {
2115 continue;
2116 }
2117
Eric Laurent74708e72017-04-07 17:13:42 -07002118 audio_source_t activeSource = activeDesc->inputSource(true);
2119 if (activeSource == AUDIO_SOURCE_HOTWORD) {
2120 AudioSessionCollection activeSessions =
2121 activeDesc->getAudioSessions(true /*activeOnly*/);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002122 sp<AudioSession> activeSession = activeSessions[0];
Eric Laurent74708e72017-04-07 17:13:42 -07002123 SortedVector<audio_session_t> sessions = activeDesc->getPreemptedSessions();
Ray Essick84e84a52018-05-03 18:45:07 -07002124 *concurrency |= API_INPUT_CONCURRENCY_PREEMPT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002125 sessions.add(activeSession->session());
Eric Laurent74708e72017-04-07 17:13:42 -07002126 inputDesc->setPreemptedSessions(sessions);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002127 closeSession(inputDesc, activeSession);
Eric Laurent74708e72017-04-07 17:13:42 -07002128 ALOGV("startInput(%d) for HOTWORD preempting HOTWORD input %d",
2129 input, activeDesc->mIoHandle);
2130 }
2131 }
2132 }
Eric Laurente552edb2014-03-10 17:42:56 -07002133
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002134 // Make sure we start with the correct silence state
2135 audioSession->setSilenced(silenced);
2136
Eric Laurent313d1e72016-01-29 09:56:57 -08002137 // increment activity count before calling getNewInputDevice() below as only active sessions
2138 // are considered for device selection
Eric Laurenta18dced2018-07-20 15:14:54 -07002139 inputDesc->changeRefCount(session, 1);
Eric Laurent313d1e72016-01-29 09:56:57 -08002140
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002141 // Routing?
2142 mInputRoutes.incRouteActivity(session);
2143
Eric Laurent2157f5b2018-04-25 18:33:02 -07002144 if (audioSession->activeCount() == 1 || mInputRoutes.getAndClearRouteChanged(session)) {
Eric Laurent271a93e2016-09-29 14:47:06 -07002145 // indicate active capture to sound trigger service if starting capture from a mic on
2146 // primary HW module
Eric Laurentf7c50102016-09-30 15:19:43 -07002147 audio_devices_t device = getNewInputDevice(inputDesc);
Eric Laurent271a93e2016-09-29 14:47:06 -07002148 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002149
Eric Laurent733ce942017-12-07 12:18:25 -08002150 status_t status = inputDesc->start();
2151 if (status != NO_ERROR) {
2152 mInputRoutes.decRouteActivity(session);
Eric Laurenta18dced2018-07-20 15:14:54 -07002153 inputDesc->changeRefCount(session, -1);
Eric Laurent733ce942017-12-07 12:18:25 -08002154 return status;
2155 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002156
Eric Laurent733ce942017-12-07 12:18:25 -08002157 if (inputDesc->getAudioSessionCount(true/*activeOnly*/) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002158 // if input maps to a dynamic policy with an activity listener, notify of state change
2159 if ((inputDesc->mPolicyMix != NULL)
2160 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2161 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2162 MIX_STATE_MIXING);
Eric Laurentc722f302014-12-10 11:21:49 -08002163 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002164
Eric Laurentf7c50102016-09-30 15:19:43 -07002165 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2166 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Eric Laurent05b345e2016-11-18 12:36:27 -08002167 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002168 SoundTrigger::setCaptureState(true);
2169 }
2170
2171 // automatically enable the remote submix output when input is started if not
2172 // used by a policy mix of type MIX_TYPE_RECORDERS
2173 // For remote submix (a virtual device), we open only one input per capture request.
2174 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2175 String8 address = String8("");
2176 if (inputDesc->mPolicyMix == NULL) {
2177 address = String8("0");
2178 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2179 address = inputDesc->mPolicyMix->mDeviceAddress;
2180 }
2181 if (address != "") {
2182 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2183 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2184 address, "remote-submix");
2185 }
Eric Laurentc722f302014-12-10 11:21:49 -08002186 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002187 }
Eric Laurente552edb2014-03-10 17:42:56 -07002188 }
2189
Eric Laurent599c7582015-12-07 18:05:55 -08002190 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
Eric Laurente552edb2014-03-10 17:42:56 -07002191
Eric Laurente552edb2014-03-10 17:42:56 -07002192 return NO_ERROR;
2193}
2194
Eric Laurent8fc147b2018-07-22 19:13:55 -07002195status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002196{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002197 ALOGV("%s portId %d", __FUNCTION__, portId);
2198
2199 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2200 if (inputDesc == 0) {
2201 ALOGW("stopInput() no input for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002202 return BAD_VALUE;
2203 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002204 sp<RecordClientDescriptor> client = inputDesc->clients()[portId];
2205 audio_session_t session = client->session();
2206 audio_io_handle_t input = inputDesc->mIoHandle;
2207
2208 ALOGV("stopInput() input %d", input);
Eric Laurente552edb2014-03-10 17:42:56 -07002209
Eric Laurent599c7582015-12-07 18:05:55 -08002210 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07002211
Eric Laurent599c7582015-12-07 18:05:55 -08002212 if (audioSession->activeCount() == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002213 ALOGW("stopInput() input %d already stopped", input);
2214 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002215 }
2216
Eric Laurenta18dced2018-07-20 15:14:54 -07002217 inputDesc->changeRefCount(session, -1);
Paul McLean466dc8e2015-04-17 13:15:36 -06002218
2219 // Routing?
2220 mInputRoutes.decRouteActivity(session);
2221
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002222 if (audioSession->activeCount() == 0) {
Eric Laurent733ce942017-12-07 12:18:25 -08002223 inputDesc->stop();
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002224 if (inputDesc->isActive()) {
2225 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2226 } else {
2227 // if input maps to a dynamic policy with an activity listener, notify of state change
2228 if ((inputDesc->mPolicyMix != NULL)
2229 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2230 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2231 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002232 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002233
2234 // automatically disable the remote submix output when input is stopped if not
2235 // used by a policy mix of type MIX_TYPE_RECORDERS
2236 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2237 String8 address = String8("");
2238 if (inputDesc->mPolicyMix == NULL) {
2239 address = String8("0");
2240 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2241 address = inputDesc->mPolicyMix->mDeviceAddress;
2242 }
2243 if (address != "") {
2244 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2245 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2246 address, "remote-submix");
2247 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002248 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002249
Eric Laurentf7c50102016-09-30 15:19:43 -07002250 audio_devices_t device = inputDesc->mDevice;
Eric Laurentfb66dd92016-01-28 18:32:03 -08002251 resetInputDevice(input);
Eric Laurent84332aa2016-01-28 22:19:18 +00002252
Eric Laurentf7c50102016-09-30 15:19:43 -07002253 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2254 // primary HW module
2255 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2256 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2257 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08002258 SoundTrigger::setCaptureState(false);
2259 }
2260 inputDesc->clearPreemptedSessions();
Eric Laurent84332aa2016-01-28 22:19:18 +00002261 }
Eric Laurente552edb2014-03-10 17:42:56 -07002262 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002263 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002264}
2265
Eric Laurent8fc147b2018-07-22 19:13:55 -07002266void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002267{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002268 ALOGV("%s portId %d", __FUNCTION__, portId);
2269
2270 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2271 if (inputDesc == 0) {
2272 ALOGW("releaseInput() no input for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002273 return;
2274 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002275 sp<RecordClientDescriptor> client = inputDesc->clients()[portId];
2276 audio_session_t session = client->session();
2277 audio_io_handle_t input = inputDesc->mIoHandle;
2278
2279 ALOGV("releaseInput() %d", input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002280
2281 // Routing
2282 mInputRoutes.removeRoute(session);
2283
Eric Laurent599c7582015-12-07 18:05:55 -08002284 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
vivek mehta587b8df2017-01-31 14:58:44 -08002285 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07002286 ALOGW("releaseInput() unknown session %d on input %d", session, input);
2287 return;
2288 }
Eric Laurent599c7582015-12-07 18:05:55 -08002289
2290 if (audioSession->openCount() == 0) {
2291 ALOGW("releaseInput() invalid open count %d on session %d",
2292 audioSession->openCount(), session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002293 return;
2294 }
Eric Laurent599c7582015-12-07 18:05:55 -08002295
2296 if (audioSession->changeOpenCount(-1) == 0) {
2297 inputDesc->removeAudioSession(session);
2298 }
2299
Jean-Michel Trivi65bfe912015-12-04 15:56:47 -08002300 if (inputDesc->getOpenRefCount() > 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002301 ALOGV("releaseInput() exit > 0");
2302 return;
2303 }
2304
Eric Laurent05b90f82014-08-27 15:32:29 -07002305 closeInput(input);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002306 inputDesc->clients().erase(portId);
Eric Laurentb52c1522014-05-20 11:27:36 -07002307 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002308 ALOGV("releaseInput() exit");
2309}
2310
Eric Laurent8fc147b2018-07-22 19:13:55 -07002311void AudioPolicyManager::closeSessions(const sp<AudioInputDescriptor>& input, bool activeOnly)
2312{
2313 AudioSessionCollection sessions = input->getAudioSessions(activeOnly /*activeOnly*/);
2314 for (size_t i = 0; i < sessions.size(); i++) {
2315 closeSession(input, sessions[i]);
2316 }
2317}
2318
2319void AudioPolicyManager::closeSession(const sp<AudioInputDescriptor>& input,
2320 const sp<AudioSession>& session)
2321{
2322 RecordClientVector clients = input->getClientsForSession(session->session());
2323
2324 for (const auto& client : clients) {
2325 stopInput(client->portId());
2326 releaseInput(client->portId());
2327 }
2328}
2329
2330
Eric Laurentd4692962014-05-05 18:13:44 -07002331void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002332 bool patchRemoved = false;
2333
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002334 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002335 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002336 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002337 if (patch_index >= 0) {
2338 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002339 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002340 mAudioPatches.removeItemsAt(patch_index);
2341 patchRemoved = true;
2342 }
Eric Laurentfe231122017-11-17 17:48:06 -08002343 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002344 }
jiabin829a00b2018-04-04 16:28:32 -07002345 mInputRoutes.clear();
Eric Laurentd4692962014-05-05 18:13:44 -07002346 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002347 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002348 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002349
2350 if (patchRemoved) {
2351 mpClientInterface->onAudioPatchListUpdate();
2352 }
Eric Laurentd4692962014-05-05 18:13:44 -07002353}
2354
Eric Laurente0720872014-03-11 09:30:41 -07002355void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002356 int indexMin,
2357 int indexMax)
2358{
2359 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002360 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002361
2362 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002363 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2364 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002365 continue;
2366 }
2367 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002368 }
Eric Laurente552edb2014-03-10 17:42:56 -07002369}
2370
Eric Laurente0720872014-03-11 09:30:41 -07002371status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002372 int index,
2373 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002374{
2375
Nadav Bar7c605f62017-12-25 00:01:52 +02002376 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2377 // app that has MODIFY_PHONE_STATE permission.
2378 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
2379 !(stream == AUDIO_STREAM_VOICE_CALL && index == 0)) ||
François Gaffied1ab2bd2015-12-02 18:20:06 +01002380 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002381 return BAD_VALUE;
2382 }
2383 if (!audio_is_output_device(device)) {
2384 return BAD_VALUE;
2385 }
2386
2387 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002388 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002389
Eric Laurent1fd372e2016-04-06 14:23:53 -07002390 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002391 stream, device, index);
2392
Eric Laurent28d09f02016-03-08 10:43:05 -08002393 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002394 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2395 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002396 continue;
2397 }
2398 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2399 }
Eric Laurente552edb2014-03-10 17:42:56 -07002400
Eric Laurent1fd372e2016-04-06 14:23:53 -07002401 // update volume on all outputs and streams matching the following:
2402 // - The requested stream (or a stream matching for volume control) is active on the output
2403 // - The device (or devices) selected by the strategy corresponding to this stream includes
2404 // the requested device
2405 // - For non default requested device, currently selected device on the output is either the
2406 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002407 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2408 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002409 status_t status = NO_ERROR;
2410 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002411 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2412 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08002413 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
Eric Laurent3839bc02018-07-10 18:33:34 -07002414 if (!(streamsMatchForvolume(stream, (audio_stream_type_t)curStream))) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002415 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002416 }
Eric Laurentdcd4ab12018-06-29 17:45:13 -07002417 if (!(desc->isStreamActive((audio_stream_type_t)curStream) || isInCall())) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002418 continue;
2419 }
Eric Laurent794fde22016-03-11 09:50:45 -08002420 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002421 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2422 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002423 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2424 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002425 continue;
2426 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002427 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002428 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002429 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07002430 applyVolume = (curDevice & curStreamDevice) != 0;
2431 } else {
2432 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002433 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002434 }
Eric Laurent3839bc02018-07-10 18:33:34 -07002435 // rescale index before applying to curStream as ranges may be different for
2436 // stream and curStream
2437 int idx = rescaleVolumeIndex(index, stream, (audio_stream_type_t)curStream);
Eric Laurente76f29c2016-09-14 17:17:53 -07002438 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002439 //FIXME: workaround for truncated touch sounds
2440 // delayed volume change for system stream to be removed when the problem is
2441 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002442 status_t volStatus =
Eric Laurent3839bc02018-07-10 18:33:34 -07002443 checkAndSetVolume((audio_stream_type_t)curStream, idx, desc, curDevice,
Eric Laurentdc462862016-07-19 12:29:53 -07002444 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002445 if (volStatus != NO_ERROR) {
2446 status = volStatus;
2447 }
2448 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002449 }
Eric Laurente552edb2014-03-10 17:42:56 -07002450 }
2451 return status;
2452}
2453
Eric Laurente0720872014-03-11 09:30:41 -07002454status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002455 int *index,
2456 audio_devices_t device)
2457{
2458 if (index == NULL) {
2459 return BAD_VALUE;
2460 }
2461 if (!audio_is_output_device(device)) {
2462 return BAD_VALUE;
2463 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002464 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002465 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002466 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002467 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2468 }
François Gaffiedfd74092015-03-19 12:10:59 +01002469 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002470
François Gaffied1ab2bd2015-12-02 18:20:06 +01002471 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002472 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2473 return NO_ERROR;
2474}
2475
Eric Laurent36829f92017-04-07 19:04:42 -07002476audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002477{
2478 // select one output among several suitable for global effects.
2479 // The priority is as follows:
2480 // 1: An offloaded output. If the effect ends up not being offloadable,
2481 // AudioFlinger will invalidate the track and the offloaded output
2482 // will be closed causing the effect to be moved to a PCM output.
2483 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002484 // 3: The primary output
2485 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002486
Eric Laurent3b73df72014-03-11 09:06:29 -07002487 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002488 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent36829f92017-04-07 19:04:42 -07002489 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002490
Eric Laurent36829f92017-04-07 19:04:42 -07002491 if (outputs.size() == 0) {
2492 return AUDIO_IO_HANDLE_NONE;
2493 }
Eric Laurente552edb2014-03-10 17:42:56 -07002494
Eric Laurent36829f92017-04-07 19:04:42 -07002495 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2496 bool activeOnly = true;
2497
2498 while (output == AUDIO_IO_HANDLE_NONE) {
2499 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2500 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2501 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2502
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002503 for (audio_io_handle_t output : outputs) {
2504 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002505 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2506 continue;
2507 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002508 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2509 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002510 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002511 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002512 }
2513 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002514 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002515 }
2516 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002517 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002518 }
2519 }
2520 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2521 output = outputOffloaded;
2522 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2523 output = outputDeepBuffer;
2524 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2525 output = outputPrimary;
2526 } else {
2527 output = outputs[0];
2528 }
2529 activeOnly = false;
2530 }
2531
2532 if (output != mMusicEffectOutput) {
2533 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2534 mMusicEffectOutput = output;
2535 }
2536
2537 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002538 return output;
2539}
2540
Eric Laurent36829f92017-04-07 19:04:42 -07002541audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2542{
2543 return selectOutputForMusicEffects();
2544}
2545
Eric Laurente0720872014-03-11 09:30:41 -07002546status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002547 audio_io_handle_t io,
2548 uint32_t strategy,
2549 int session,
2550 int id)
2551{
2552 ssize_t index = mOutputs.indexOfKey(io);
2553 if (index < 0) {
2554 index = mInputs.indexOfKey(io);
2555 if (index < 0) {
2556 ALOGW("registerEffect() unknown io %d", io);
2557 return INVALID_OPERATION;
2558 }
2559 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002560 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002561}
2562
Eric Laurentc75307b2015-03-17 15:29:32 -07002563bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2564{
Eric Laurent28d09f02016-03-08 10:43:05 -08002565 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002566 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2567 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002568 continue;
2569 }
2570 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2571 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002572 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002573}
2574
2575bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2576{
2577 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2578}
2579
Eric Laurente0720872014-03-11 09:30:41 -07002580bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002581{
2582 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002583 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002584 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002585 return true;
2586 }
2587 }
2588 return false;
2589}
2590
Eric Laurent275e8e92014-11-30 15:14:47 -08002591// Register a list of custom mixes with their attributes and format.
2592// When a mix is registered, corresponding input and output profiles are
2593// added to the remote submix hw module. The profile contains only the
2594// parameters (sampling rate, format...) specified by the mix.
2595// The corresponding input remote submix device is also connected.
2596//
2597// When a remote submix device is connected, the address is checked to select the
2598// appropriate profile and the corresponding input or output stream is opened.
2599//
2600// When capture starts, getInputForAttr() will:
2601// - 1 look for a mix matching the address passed in attribtutes tags if any
2602// - 2 if none found, getDeviceForInputSource() will:
2603// - 2.1 look for a mix matching the attributes source
2604// - 2.2 if none found, default to device selection by policy rules
2605// At this time, the corresponding output remote submix device is also connected
2606// and active playback use cases can be transferred to this mix if needed when reconnecting
2607// after AudioTracks are invalidated
2608//
2609// When playback starts, getOutputForAttr() will:
2610// - 1 look for a mix matching the address passed in attribtutes tags if any
2611// - 2 if none found, look for a mix matching the attributes usage
2612// - 3 if none found, default to device and output selection by policy rules.
2613
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002614status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002615{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002616 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2617 status_t res = NO_ERROR;
2618
2619 sp<HwModule> rSubmixModule;
2620 // examine each mix's route type
2621 for (size_t i = 0; i < mixes.size(); i++) {
2622 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
2623 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
2624 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002625 break;
2626 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002627 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002628 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002629 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002630 rSubmixModule = mHwModules.getModuleFromName(
2631 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2632 if (rSubmixModule == 0) {
2633 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2634 i);
2635 res = INVALID_OPERATION;
2636 break;
2637 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002638 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002639
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002640 String8 address = mixes[i].mDeviceAddress;
François Gaffie036e1e92015-03-19 10:16:24 +01002641
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002642 if (mPolicyMixes.registerMix(address, mixes[i], 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002643 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002644 res = INVALID_OPERATION;
2645 break;
2646 }
2647 audio_config_t outputConfig = mixes[i].mFormat;
2648 audio_config_t inputConfig = mixes[i].mFormat;
2649 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2650 // stereo and let audio flinger do the channel conversion if needed.
2651 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2652 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2653 rSubmixModule->addOutputProfile(address, &outputConfig,
2654 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2655 rSubmixModule->addInputProfile(address, &inputConfig,
2656 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002657
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002658 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
2659 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2660 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2661 address.string(), "remote-submix");
2662 } else {
2663 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2664 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2665 address.string(), "remote-submix");
2666 }
2667 } else if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002668 String8 address = mixes[i].mDeviceAddress;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002669 audio_devices_t device = mixes[i].mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002670 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2671 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002672
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002673 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002674 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2675 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2676 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2677 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2678 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2679 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002680 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2681 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002682 if (mPolicyMixes.registerMix(address, mixes[i], desc) != NO_ERROR) {
2683 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002684 } else {
2685 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002686 }
2687 break;
2688 }
2689 }
2690
2691 if (res != NO_ERROR) {
2692 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002693 i, device, address.string());
2694 res = INVALID_OPERATION;
2695 break;
2696 } else if (!foundOutput) {
2697 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2698 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002699 res = INVALID_OPERATION;
2700 break;
2701 }
Eric Laurentc722f302014-12-10 11:21:49 -08002702 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002703 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002704 if (res != NO_ERROR) {
2705 unregisterPolicyMixes(mixes);
2706 }
2707 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002708}
2709
2710status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2711{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002712 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002713 status_t res = NO_ERROR;
2714 sp<HwModule> rSubmixModule;
2715 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002716 for (const auto& mix : mixes) {
2717 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002718
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002719 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002720 rSubmixModule = mHwModules.getModuleFromName(
2721 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2722 if (rSubmixModule == 0) {
2723 res = INVALID_OPERATION;
2724 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002725 }
2726 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002727
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002728 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002729
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002730 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2731 res = INVALID_OPERATION;
2732 continue;
2733 }
2734
2735 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2736 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2737 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2738 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2739 address.string(), "remote-submix");
2740 }
2741 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2742 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2743 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2744 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2745 address.string(), "remote-submix");
2746 }
2747 rSubmixModule->removeOutputProfile(address);
2748 rSubmixModule->removeInputProfile(address);
2749
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002750 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2751 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002752 res = INVALID_OPERATION;
2753 continue;
2754 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002755 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002756 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002757 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002758}
2759
Eric Laurente552edb2014-03-10 17:42:56 -07002760
Eric Laurente0720872014-03-11 09:30:41 -07002761status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002762{
Eric Laurente552edb2014-03-10 17:42:56 -07002763 String8 result;
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002764 result.appendFormat("\nAudioPolicyManager Dump: %p\n", this);
2765 result.appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07002766 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002767 std::string stateLiteral;
2768 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002769 result.appendFormat(" Phone state: %s\n", stateLiteral.c_str());
2770 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
2771 "communications", "media", "record", "dock", "system",
2772 "HDMI system audio", "encoded surround output", "vibrate ringing" };
2773 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
2774 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
2775 result.appendFormat(" Force use for %s: %d\n",
2776 forceUses[i], mEngine->getForceUse(i));
2777 }
2778 result.appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
2779 result.appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
2780 result.appendFormat(" Config source: %s\n", getConfig().getSource().c_str());
François Gaffie2110e042015-03-24 08:41:51 +01002781 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002782
François Gaffie112b0af2015-11-19 16:13:25 +01002783 mAvailableOutputDevices.dump(fd, String8("Available output"));
2784 mAvailableInputDevices.dump(fd, String8("Available input"));
Mikhail Naganovd4120142017-12-06 15:49:22 -08002785 mHwModulesAll.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002786 mOutputs.dump(fd);
2787 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002788 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002789 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002790 mAudioPatches.dump(fd);
Mikhail Naganov44344b02016-12-13 11:21:02 -08002791 mPolicyMixes.dump(fd);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07002792 mAudioSources.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002793
2794 return NO_ERROR;
2795}
2796
2797// This function checks for the parameters which can be offloaded.
2798// This can be enhanced depending on the capability of the DSP and policy
2799// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002800bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002801{
2802 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002803 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002804 offloadInfo.sample_rate, offloadInfo.channel_mask,
2805 offloadInfo.format,
2806 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2807 offloadInfo.has_video);
2808
Andy Hung2ddee192015-12-18 17:34:44 -08002809 if (mMasterMono) {
2810 return false; // no offloading if mono is set.
2811 }
2812
Eric Laurente552edb2014-03-10 17:42:56 -07002813 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07002814 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
2815 ALOGV("offload disabled by audio.offload.disable");
2816 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002817 }
2818
2819 // Check if stream type is music, then only allow offload as of now.
2820 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2821 {
2822 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2823 return false;
2824 }
2825
2826 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002827 const bool allowOffloadWithVideo =
2828 property_get_bool("audio.offload.video", false /* default_value */);
2829 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002830 ALOGV("isOffloadSupported: has_video == true, returning false");
2831 return false;
2832 }
2833
2834 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07002835 const int min_duration_secs = property_get_int32(
2836 "audio.offload.min.duration.secs", -1 /* default_value */);
2837 if (min_duration_secs >= 0) {
2838 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
2839 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%d)",
2840 min_duration_secs);
Eric Laurente552edb2014-03-10 17:42:56 -07002841 return false;
2842 }
2843 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2844 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2845 return false;
2846 }
2847
2848 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2849 // creating an offloaded track and tearing it down immediately after start when audioflinger
2850 // detects there is an active non offloadable effect.
2851 // FIXME: We should check the audio session here but we do not have it in this context.
2852 // This may prevent offloading in rare situations where effects are left active by apps
2853 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002854 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002855 return false;
2856 }
2857
2858 // See if there is a profile to support this.
2859 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002860 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002861 offloadInfo.sample_rate,
2862 offloadInfo.format,
2863 offloadInfo.channel_mask,
2864 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002865 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2866 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002867}
2868
Eric Laurent6a94d692014-05-20 11:18:06 -07002869status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2870 audio_port_type_t type,
2871 unsigned int *num_ports,
2872 struct audio_port *ports,
2873 unsigned int *generation)
2874{
2875 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2876 generation == NULL) {
2877 return BAD_VALUE;
2878 }
2879 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2880 if (ports == NULL) {
2881 *num_ports = 0;
2882 }
2883
2884 size_t portsWritten = 0;
2885 size_t portsMax = *num_ports;
2886 *num_ports = 0;
2887 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002888 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2889 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002890 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002891 for (const auto& dev : mAvailableOutputDevices) {
2892 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002893 continue;
2894 }
2895 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002896 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002897 }
2898 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002899 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002900 }
2901 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002902 for (const auto& dev : mAvailableInputDevices) {
2903 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002904 continue;
2905 }
2906 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002907 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002908 }
2909 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002910 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002911 }
2912 }
2913 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2914 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2915 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2916 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2917 }
2918 *num_ports += mInputs.size();
2919 }
2920 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002921 size_t numOutputs = 0;
2922 for (size_t i = 0; i < mOutputs.size(); i++) {
2923 if (!mOutputs[i]->isDuplicated()) {
2924 numOutputs++;
2925 if (portsWritten < portsMax) {
2926 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2927 }
2928 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002929 }
Eric Laurent84c70242014-06-23 08:46:27 -07002930 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002931 }
2932 }
2933 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002934 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002935 return NO_ERROR;
2936}
2937
Eric Laurent99fcae42018-05-17 16:59:18 -07002938status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07002939{
Eric Laurent99fcae42018-05-17 16:59:18 -07002940 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
2941 return BAD_VALUE;
2942 }
2943 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
2944 if (dev != 0) {
2945 dev->toAudioPort(port);
2946 return NO_ERROR;
2947 }
2948 dev = mAvailableInputDevices.getDeviceFromId(port->id);
2949 if (dev != 0) {
2950 dev->toAudioPort(port);
2951 return NO_ERROR;
2952 }
2953 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
2954 if (out != 0) {
2955 out->toAudioPort(port);
2956 return NO_ERROR;
2957 }
2958 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
2959 if (in != 0) {
2960 in->toAudioPort(port);
2961 return NO_ERROR;
2962 }
2963 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002964}
2965
Eric Laurent6a94d692014-05-20 11:18:06 -07002966status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2967 audio_patch_handle_t *handle,
2968 uid_t uid)
2969{
2970 ALOGV("createAudioPatch()");
2971
2972 if (handle == NULL || patch == NULL) {
2973 return BAD_VALUE;
2974 }
2975 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2976
Mikhail Naganovac9858b2018-06-15 13:12:37 -07002977 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07002978 return BAD_VALUE;
2979 }
2980 // only one source per audio patch supported for now
2981 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002982 return INVALID_OPERATION;
2983 }
Eric Laurent874c42872014-08-08 15:13:39 -07002984
2985 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002986 return INVALID_OPERATION;
2987 }
Eric Laurent874c42872014-08-08 15:13:39 -07002988 for (size_t i = 0; i < patch->num_sinks; i++) {
2989 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2990 return INVALID_OPERATION;
2991 }
2992 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002993
2994 sp<AudioPatch> patchDesc;
2995 ssize_t index = mAudioPatches.indexOfKey(*handle);
2996
Eric Laurent6a94d692014-05-20 11:18:06 -07002997 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2998 patch->sources[0].role,
2999 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003000#if LOG_NDEBUG == 0
3001 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08003002 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07003003 patch->sinks[i].role,
3004 patch->sinks[i].type);
3005 }
3006#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07003007
3008 if (index >= 0) {
3009 patchDesc = mAudioPatches.valueAt(index);
3010 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3011 mUidCached, patchDesc->mUid, uid);
3012 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3013 return INVALID_OPERATION;
3014 }
3015 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07003016 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003017 }
3018
3019 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003020 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003021 if (outputDesc == NULL) {
3022 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
3023 return BAD_VALUE;
3024 }
Eric Laurent84c70242014-06-23 08:46:27 -07003025 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
3026 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003027 if (patchDesc != 0) {
3028 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
3029 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
3030 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
3031 return BAD_VALUE;
3032 }
3033 }
Eric Laurent874c42872014-08-08 15:13:39 -07003034 DeviceVector devices;
3035 for (size_t i = 0; i < patch->num_sinks; i++) {
3036 // Only support mix to devices connection
3037 // TODO add support for mix to mix connection
3038 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3039 ALOGV("createAudioPatch() source mix but sink is not a device");
3040 return INVALID_OPERATION;
3041 }
3042 sp<DeviceDescriptor> devDesc =
3043 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3044 if (devDesc == 0) {
3045 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
3046 return BAD_VALUE;
3047 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003048
François Gaffie53615e22015-03-19 09:24:12 +01003049 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08003050 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07003051 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01003052 NULL, // updatedSamplingRate
3053 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003054 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01003055 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003056 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01003057 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07003058 ALOGV("createAudioPatch() profile not supported for device %08x",
3059 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07003060 return INVALID_OPERATION;
3061 }
3062 devices.add(devDesc);
3063 }
3064 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003065 return INVALID_OPERATION;
3066 }
Eric Laurent874c42872014-08-08 15:13:39 -07003067
Eric Laurent6a94d692014-05-20 11:18:06 -07003068 // TODO: reconfigure output format and channels here
3069 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07003070 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07003071 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003072 index = mAudioPatches.indexOfKey(*handle);
3073 if (index >= 0) {
3074 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3075 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
3076 }
3077 patchDesc = mAudioPatches.valueAt(index);
3078 patchDesc->mUid = uid;
3079 ALOGV("createAudioPatch() success");
3080 } else {
3081 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
3082 return INVALID_OPERATION;
3083 }
3084 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3085 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3086 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003087 // only one sink supported when connecting an input device to a mix
3088 if (patch->num_sinks > 1) {
3089 return INVALID_OPERATION;
3090 }
François Gaffie53615e22015-03-19 09:24:12 +01003091 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003092 if (inputDesc == NULL) {
3093 return BAD_VALUE;
3094 }
3095 if (patchDesc != 0) {
3096 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3097 return BAD_VALUE;
3098 }
3099 }
3100 sp<DeviceDescriptor> devDesc =
3101 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
3102 if (devDesc == 0) {
3103 return BAD_VALUE;
3104 }
3105
François Gaffie53615e22015-03-19 09:24:12 +01003106 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08003107 devDesc->mAddress,
3108 patch->sinks[0].sample_rate,
3109 NULL, /*updatedSampleRate*/
3110 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003111 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003112 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003113 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003114 // FIXME for the parameter type,
3115 // and the NONE
3116 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003117 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003118 return INVALID_OPERATION;
3119 }
3120 // TODO: reconfigure output format and channels here
3121 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01003122 devDesc->type(), inputDesc->mIoHandle);
3123 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003124 index = mAudioPatches.indexOfKey(*handle);
3125 if (index >= 0) {
3126 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3127 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
3128 }
3129 patchDesc = mAudioPatches.valueAt(index);
3130 patchDesc->mUid = uid;
3131 ALOGV("createAudioPatch() success");
3132 } else {
3133 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
3134 return INVALID_OPERATION;
3135 }
3136 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3137 // device to device connection
3138 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003139 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003140 return BAD_VALUE;
3141 }
3142 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003143 sp<DeviceDescriptor> srcDeviceDesc =
3144 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07003145 if (srcDeviceDesc == 0) {
3146 return BAD_VALUE;
3147 }
Eric Laurent874c42872014-08-08 15:13:39 -07003148
Eric Laurent6a94d692014-05-20 11:18:06 -07003149 //update source and sink with our own data as the data passed in the patch may
3150 // be incomplete.
3151 struct audio_patch newPatch = *patch;
3152 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003153
Eric Laurent874c42872014-08-08 15:13:39 -07003154 for (size_t i = 0; i < patch->num_sinks; i++) {
3155 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3156 ALOGV("createAudioPatch() source device but one sink is not a device");
3157 return INVALID_OPERATION;
3158 }
3159
3160 sp<DeviceDescriptor> sinkDeviceDesc =
3161 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3162 if (sinkDeviceDesc == 0) {
3163 return BAD_VALUE;
3164 }
3165 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
3166
Eric Laurent3bcf8592015-04-03 12:13:24 -07003167 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003168 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003169 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08003170 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003171 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003172 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003173 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003174 return INVALID_OPERATION;
3175 }
Eric Laurent874c42872014-08-08 15:13:39 -07003176 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01003177 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003178 // if the sink device is reachable via an opened output stream, request to go via
3179 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07003180 audio_io_handle_t output = selectOutput(outputs,
3181 AUDIO_OUTPUT_FLAG_NONE,
3182 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07003183 if (output != AUDIO_IO_HANDLE_NONE) {
3184 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3185 if (outputDesc->isDuplicated()) {
3186 return INVALID_OPERATION;
3187 }
3188 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003189 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003190 newPatch.num_sources = 2;
3191 }
Eric Laurent83b88082014-06-20 18:31:16 -07003192 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003193 }
3194 // TODO: check from routing capabilities in config file and other conflicting patches
3195
Mikhail Naganovdc769682018-05-04 15:34:08 -07003196 status_t status = installPatch(__func__, index, handle, &newPatch, 0, uid, &patchDesc);
3197 if (status != NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003198 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3199 status);
3200 return INVALID_OPERATION;
3201 }
3202 } else {
3203 return BAD_VALUE;
3204 }
3205 } else {
3206 return BAD_VALUE;
3207 }
3208 return NO_ERROR;
3209}
3210
3211status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3212 uid_t uid)
3213{
3214 ALOGV("releaseAudioPatch() patch %d", handle);
3215
3216 ssize_t index = mAudioPatches.indexOfKey(handle);
3217
3218 if (index < 0) {
3219 return BAD_VALUE;
3220 }
3221 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3222 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3223 mUidCached, patchDesc->mUid, uid);
3224 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3225 return INVALID_OPERATION;
3226 }
3227
3228 struct audio_patch *patch = &patchDesc->mPatch;
3229 patchDesc->mUid = mUidCached;
3230 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003231 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003232 if (outputDesc == NULL) {
3233 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3234 return BAD_VALUE;
3235 }
3236
Eric Laurentc75307b2015-03-17 15:29:32 -07003237 setOutputDevice(outputDesc,
3238 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07003239 true,
3240 0,
3241 NULL);
3242 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3243 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003244 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003245 if (inputDesc == NULL) {
3246 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3247 return BAD_VALUE;
3248 }
3249 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003250 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003251 true,
3252 NULL);
3253 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003254 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3255 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3256 status, patchDesc->mAfPatchHandle);
3257 removeAudioPatch(patchDesc->mHandle);
3258 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003259 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003260 } else {
3261 return BAD_VALUE;
3262 }
3263 } else {
3264 return BAD_VALUE;
3265 }
3266 return NO_ERROR;
3267}
3268
3269status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3270 struct audio_patch *patches,
3271 unsigned int *generation)
3272{
François Gaffie53615e22015-03-19 09:24:12 +01003273 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003274 return BAD_VALUE;
3275 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003276 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003277 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003278}
3279
Eric Laurente1715a42014-05-20 11:30:42 -07003280status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003281{
Eric Laurente1715a42014-05-20 11:30:42 -07003282 ALOGV("setAudioPortConfig()");
3283
3284 if (config == NULL) {
3285 return BAD_VALUE;
3286 }
3287 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3288 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003289 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3290 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003291 }
3292
Eric Laurenta121f902014-06-03 13:32:54 -07003293 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003294 if (config->type == AUDIO_PORT_TYPE_MIX) {
3295 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003296 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003297 if (outputDesc == NULL) {
3298 return BAD_VALUE;
3299 }
Eric Laurent84c70242014-06-23 08:46:27 -07003300 ALOG_ASSERT(!outputDesc->isDuplicated(),
3301 "setAudioPortConfig() called on duplicated output %d",
3302 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003303 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003304 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003305 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003306 if (inputDesc == NULL) {
3307 return BAD_VALUE;
3308 }
Eric Laurenta121f902014-06-03 13:32:54 -07003309 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003310 } else {
3311 return BAD_VALUE;
3312 }
3313 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3314 sp<DeviceDescriptor> deviceDesc;
3315 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3316 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3317 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3318 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3319 } else {
3320 return BAD_VALUE;
3321 }
3322 if (deviceDesc == NULL) {
3323 return BAD_VALUE;
3324 }
Eric Laurenta121f902014-06-03 13:32:54 -07003325 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003326 } else {
3327 return BAD_VALUE;
3328 }
3329
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003330 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003331 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3332 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003333 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003334 audioPortConfig->toAudioPortConfig(&newConfig, config);
3335 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003336 }
Eric Laurenta121f902014-06-03 13:32:54 -07003337 if (status != NO_ERROR) {
3338 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003339 }
Eric Laurente1715a42014-05-20 11:30:42 -07003340
3341 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003342}
3343
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003344void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3345{
Eric Laurentd60560a2015-04-10 11:31:20 -07003346 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003347 clearAudioPatches(uid);
3348 clearSessionRoutes(uid);
3349}
3350
Eric Laurent6a94d692014-05-20 11:18:06 -07003351void AudioPolicyManager::clearAudioPatches(uid_t uid)
3352{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003353 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003354 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3355 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003356 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003357 }
3358 }
3359}
3360
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003361void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3362 audio_io_handle_t ouptutToSkip)
3363{
3364 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3365 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3366 for (size_t j = 0; j < mOutputs.size(); j++) {
3367 if (mOutputs.keyAt(j) == ouptutToSkip) {
3368 continue;
3369 }
3370 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3371 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3372 continue;
3373 }
3374 // If the default device for this strategy is on another output mix,
3375 // invalidate all tracks in this strategy to force re connection.
3376 // Otherwise select new device on the output mix.
3377 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003378 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003379 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3380 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3381 }
3382 }
3383 } else {
3384 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3385 setOutputDevice(outputDesc, newDevice, false);
3386 }
3387 }
3388}
3389
3390void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3391{
3392 // remove output routes associated with this uid
3393 SortedVector<routing_strategy> affectedStrategies;
3394 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
3395 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
3396 if (route->mUid == uid) {
3397 mOutputRoutes.removeItemsAt(i);
3398 if (route->mDeviceDescriptor != 0) {
3399 affectedStrategies.add(getStrategy(route->mStreamType));
3400 }
3401 }
3402 }
3403 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003404 for (const auto& strategy : affectedStrategies) {
3405 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003406 }
3407
3408 // remove input routes associated with this uid
3409 SortedVector<audio_source_t> affectedSources;
3410 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
3411 sp<SessionRoute> route = mInputRoutes.valueAt(i);
3412 if (route->mUid == uid) {
3413 mInputRoutes.removeItemsAt(i);
3414 if (route->mDeviceDescriptor != 0) {
3415 affectedSources.add(route->mSource);
3416 }
3417 }
3418 }
3419 // reroute inputs if necessary
3420 SortedVector<audio_io_handle_t> inputsToClose;
3421 for (size_t i = 0; i < mInputs.size(); i++) {
3422 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003423 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003424 inputsToClose.add(inputDesc->mIoHandle);
3425 }
3426 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003427 for (const auto& input : inputsToClose) {
3428 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003429 }
3430}
3431
Eric Laurentd60560a2015-04-10 11:31:20 -07003432void AudioPolicyManager::clearAudioSources(uid_t uid)
3433{
3434 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003435 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3436 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07003437 stopAudioSource(mAudioSources.keyAt(i));
3438 }
3439 }
3440}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003441
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003442status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3443 audio_io_handle_t *ioHandle,
3444 audio_devices_t *device)
3445{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003446 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3447 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003448 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003449
François Gaffiedf372692015-03-19 10:43:27 +01003450 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003451}
3452
Eric Laurentd60560a2015-04-10 11:31:20 -07003453status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003454 const audio_attributes_t *attributes,
3455 audio_port_handle_t *portId,
3456 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003457{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003458 ALOGV("%s", __FUNCTION__);
3459 *portId = AUDIO_PORT_HANDLE_NONE;
3460
3461 if (source == NULL || attributes == NULL || portId == NULL) {
3462 ALOGW("%s invalid argument: source %p attributes %p handle %p",
3463 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003464 return BAD_VALUE;
3465 }
3466
Eric Laurentd60560a2015-04-10 11:31:20 -07003467 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3468 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003469 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
3470 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003471 return INVALID_OPERATION;
3472 }
3473
3474 sp<DeviceDescriptor> srcDeviceDesc =
3475 mAvailableInputDevices.getDevice(source->ext.device.type,
3476 String8(source->ext.device.address));
3477 if (srcDeviceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003478 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003479 return BAD_VALUE;
3480 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003481
3482 *portId = AudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07003483
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003484 struct audio_patch dummyPatch = {};
Eric Laurentd60560a2015-04-10 11:31:20 -07003485 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003486
3487 sp<SourceClientDescriptor> sourceDesc =
3488 new SourceClientDescriptor(*portId, uid, *attributes, patchDesc, srcDeviceDesc,
3489 streamTypefromAttributesInt(attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07003490
3491 status_t status = connectAudioSource(sourceDesc);
3492 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003493 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003494 }
3495 return status;
3496}
3497
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003498status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003499{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003500 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003501
3502 // make sure we only have one patch per source.
3503 disconnectAudioSource(sourceDesc);
3504
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003505 audio_attributes_t attributes = sourceDesc->attributes();
3506 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
3507 audio_stream_type_t stream = sourceDesc->stream();
3508 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->srcDevice();
Eric Laurentd60560a2015-04-10 11:31:20 -07003509
3510 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3511 sp<DeviceDescriptor> sinkDeviceDesc =
3512 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3513
3514 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003515
3516 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3517 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003518 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003519 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3520 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3521 // create patch between src device and output device
3522 // create Hwoutput and add to mHwOutputs
3523 } else {
3524 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3525 audio_io_handle_t output =
3526 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3527 if (output == AUDIO_IO_HANDLE_NONE) {
3528 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3529 return INVALID_OPERATION;
3530 }
3531 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3532 if (outputDesc->isDuplicated()) {
3533 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3534 return INVALID_OPERATION;
3535 }
Eric Laurent733ce942017-12-07 12:18:25 -08003536 status_t status = outputDesc->start();
3537 if (status != NO_ERROR) {
3538 return status;
3539 }
3540
Eric Laurentd60560a2015-04-10 11:31:20 -07003541 // create a special patch with no sink and two sources:
3542 // - the second source indicates to PatchPanel through which output mix this patch should
3543 // be connected as well as the stream type for volume control
3544 // - the sink is defined by whatever output device is currently selected for the output
3545 // though which this patch is routed.
Mikhail Naganovdc769682018-05-04 15:34:08 -07003546 PatchBuilder patchBuilder;
3547 patchBuilder.addSource(srcDeviceDesc).addSource(outputDesc, { .stream = stream });
3548 status = mpClientInterface->createAudioPatch(patchBuilder.patch(),
Eric Laurentd60560a2015-04-10 11:31:20 -07003549 &afPatchHandle,
3550 0);
3551 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3552 status, afPatchHandle);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003553 sourceDesc->patchDesc()->mPatch = *patchBuilder.patch();
Eric Laurentd60560a2015-04-10 11:31:20 -07003554 if (status != NO_ERROR) {
3555 ALOGW("%s patch panel could not connect device patch, error %d",
3556 __FUNCTION__, status);
3557 return INVALID_OPERATION;
3558 }
3559 uint32_t delayMs = 0;
Eric Laurentc40d9692016-04-13 19:14:13 -07003560 status = startSource(outputDesc, stream, sinkDevice, NULL, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003561
3562 if (status != NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003563 mpClientInterface->releaseAudioPatch(sourceDesc->patchDesc()->mAfPatchHandle, 0);
Eric Laurentd60560a2015-04-10 11:31:20 -07003564 return status;
3565 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003566 sourceDesc->setSwOutput(outputDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003567 if (delayMs != 0) {
3568 usleep(delayMs * 1000);
3569 }
3570 }
3571
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003572 sourceDesc->patchDesc()->mAfPatchHandle = afPatchHandle;
3573 addAudioPatch(sourceDesc->patchDesc()->mHandle, sourceDesc->patchDesc());
Eric Laurentd60560a2015-04-10 11:31:20 -07003574
3575 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003576}
3577
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003578status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07003579{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003580 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
3581 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003582 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003583 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003584 return BAD_VALUE;
3585 }
3586 status_t status = disconnectAudioSource(sourceDesc);
3587
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003588 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003589 return status;
3590}
3591
Andy Hung2ddee192015-12-18 17:34:44 -08003592status_t AudioPolicyManager::setMasterMono(bool mono)
3593{
3594 if (mMasterMono == mono) {
3595 return NO_ERROR;
3596 }
3597 mMasterMono = mono;
3598 // if enabling mono we close all offloaded devices, which will invalidate the
3599 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3600 // for recreating the new AudioTrack as non-offloaded PCM.
3601 //
3602 // If disabling mono, we leave all tracks as is: we don't know which clients
3603 // and tracks are able to be recreated as offloaded. The next "song" should
3604 // play back offloaded.
3605 if (mMasterMono) {
3606 Vector<audio_io_handle_t> offloaded;
3607 for (size_t i = 0; i < mOutputs.size(); ++i) {
3608 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3609 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3610 offloaded.push(desc->mIoHandle);
3611 }
3612 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003613 for (const auto& handle : offloaded) {
3614 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003615 }
3616 }
3617 // update master mono for all remaining outputs
3618 for (size_t i = 0; i < mOutputs.size(); ++i) {
3619 updateMono(mOutputs.keyAt(i));
3620 }
3621 return NO_ERROR;
3622}
3623
3624status_t AudioPolicyManager::getMasterMono(bool *mono)
3625{
3626 *mono = mMasterMono;
3627 return NO_ERROR;
3628}
3629
Eric Laurentac9cef52017-06-09 15:46:26 -07003630float AudioPolicyManager::getStreamVolumeDB(
3631 audio_stream_type_t stream, int index, audio_devices_t device)
3632{
3633 return computeVolume(stream, index, device);
3634}
3635
jiabin81772902018-04-02 17:52:27 -07003636status_t AudioPolicyManager::getSupportedFormats(audio_io_handle_t ioHandle,
3637 FormatVector& formats) {
3638 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
3639 return BAD_VALUE;
3640 }
3641 String8 reply;
3642 reply = mpClientInterface->getParameters(
3643 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
3644 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
3645 AudioParameter repliedParameters(reply);
3646 if (repliedParameters.get(
3647 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
3648 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
3649 return BAD_VALUE;
3650 }
3651 for (auto format : formatsFromString(reply.string())) {
3652 // Only AUDIO_FORMAT_AAC_LC will be used in Settings UI for all AAC formats.
3653 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3654 if (format == AAC_FORMATS[i]) {
3655 format = AUDIO_FORMAT_AAC_LC;
3656 break;
3657 }
3658 }
3659 bool exist = false;
3660 for (size_t i = 0; i < formats.size(); i++) {
3661 if (format == formats[i]) {
3662 exist = true;
3663 break;
3664 }
3665 }
3666 bool isSurroundFormat = false;
3667 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3668 if (SURROUND_FORMATS[i] == format) {
3669 isSurroundFormat = true;
3670 break;
3671 }
3672 }
3673 if (!exist && isSurroundFormat) {
3674 formats.add(format);
3675 }
3676 }
3677 return NO_ERROR;
3678}
3679
3680status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3681 audio_format_t *surroundFormats,
3682 bool *surroundFormatsEnabled,
3683 bool reported)
3684{
3685 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3686 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3687 return BAD_VALUE;
3688 }
3689 ALOGV("getSurroundFormats() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
3690 *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
3691
3692 // Only return value if there is HDMI output.
3693 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3694 return INVALID_OPERATION;
3695 }
3696
3697 size_t formatsWritten = 0;
3698 size_t formatsMax = *numSurroundFormats;
3699 *numSurroundFormats = 0;
3700 FormatVector formats;
3701 if (reported) {
3702 // Only get surround formats which are reported by device.
3703 // First list already open outputs that can be routed to this device
3704 audio_devices_t device = AUDIO_DEVICE_OUT_HDMI;
3705 SortedVector<audio_io_handle_t> outputs;
3706 bool reportedFormatFound = false;
3707 status_t status;
3708 sp<SwAudioOutputDescriptor> desc;
3709 for (size_t i = 0; i < mOutputs.size(); i++) {
3710 desc = mOutputs.valueAt(i);
3711 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
3712 outputs.add(mOutputs.keyAt(i));
3713 }
3714 }
3715 // Open an output to query dynamic parameters.
Mikhail Naganov708e0382018-05-30 09:53:04 -07003716 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003717 AUDIO_DEVICE_OUT_HDMI);
3718 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3719 String8 address = hdmiOutputDevices[i]->mAddress;
3720 for (const auto& hwModule : mHwModules) {
3721 for (size_t i = 0; i < hwModule->getOutputProfiles().size(); i++) {
3722 sp<IOProfile> profile = hwModule->getOutputProfiles()[i];
3723 if (profile->supportDevice(AUDIO_DEVICE_OUT_HDMI) &&
3724 profile->supportDeviceAddress(address)) {
3725 size_t j;
3726 for (j = 0; j < outputs.size(); j++) {
3727 desc = mOutputs.valueFor(outputs.itemAt(j));
3728 if (!desc->isDuplicated() && desc->mProfile == profile) {
3729 break;
3730 }
3731 }
3732 if (j != outputs.size()) {
3733 status = getSupportedFormats(outputs.itemAt(j), formats);
3734 reportedFormatFound |= (status == NO_ERROR);
3735 continue;
3736 }
3737
3738 if (!profile->canOpenNewIo()) {
3739 ALOGW("Max Output number %u already opened for this profile %s",
3740 profile->maxOpenCount, profile->getTagName().c_str());
3741 continue;
3742 }
3743
3744 ALOGV("opening output for device %08x with params %s profile %p name %s",
3745 device, address.string(), profile.get(), profile->getName().string());
3746 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
3747 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3748 status_t status = desc->open(nullptr, device, address,
3749 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE,
3750 &output);
3751
3752 if (status == NO_ERROR) {
3753 status = getSupportedFormats(output, formats);
3754 reportedFormatFound |= (status == NO_ERROR);
3755 desc->close();
3756 output = AUDIO_IO_HANDLE_NONE;
3757 }
3758 }
3759 }
3760 }
3761 }
3762
3763 if (!reportedFormatFound) {
3764 return UNKNOWN_ERROR;
3765 }
3766 } else {
3767 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3768 formats.add(SURROUND_FORMATS[i]);
3769 }
3770 }
3771 for (size_t i = 0; i < formats.size(); i++) {
3772 if (formatsWritten < formatsMax) {
3773 surroundFormats[formatsWritten] = formats[i];
3774 bool formatEnabled = false;
3775 if (formats[i] == AUDIO_FORMAT_AAC_LC) {
3776 for (size_t j = 0; j < ARRAY_SIZE(AAC_FORMATS); j++) {
3777 formatEnabled =
3778 mSurroundFormats.find(AAC_FORMATS[i]) != mSurroundFormats.end();
3779 break;
3780 }
3781 } else {
3782 formatEnabled = mSurroundFormats.find(formats[i]) != mSurroundFormats.end();
3783 }
3784 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3785 }
3786 (*numSurroundFormats)++;
3787 }
3788 return NO_ERROR;
3789}
3790
3791status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3792{
3793 // Check if audio format is a surround formats.
3794 bool isSurroundFormat = false;
3795 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3796 if (audioFormat == SURROUND_FORMATS[i]) {
3797 isSurroundFormat = true;
3798 break;
3799 }
3800 }
3801 if (!isSurroundFormat) {
3802 return BAD_VALUE;
3803 }
3804
3805 // Should only be called when MANUAL.
3806 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3807 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
3808 if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3809 return INVALID_OPERATION;
3810 }
3811
3812 if ((mSurroundFormats.find(audioFormat) != mSurroundFormats.end() && enabled)
3813 || (mSurroundFormats.find(audioFormat) == mSurroundFormats.end() && !enabled)) {
3814 return NO_ERROR;
3815 }
3816
3817 // The operation is valid only when there is HDMI output available.
3818 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3819 return INVALID_OPERATION;
3820 }
3821
3822 if (enabled) {
3823 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3824 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3825 mSurroundFormats.insert(AAC_FORMATS[i]);
3826 }
3827 } else {
3828 mSurroundFormats.insert(audioFormat);
3829 }
3830 } else {
3831 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3832 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3833 mSurroundFormats.erase(AAC_FORMATS[i]);
3834 }
3835 } else {
3836 mSurroundFormats.erase(audioFormat);
3837 }
3838 }
3839
3840 sp<SwAudioOutputDescriptor> outputDesc;
3841 bool profileUpdated = false;
Mikhail Naganov708e0382018-05-30 09:53:04 -07003842 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003843 AUDIO_DEVICE_OUT_HDMI);
3844 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3845 // Simulate reconnection to update enabled surround sound formats.
3846 String8 address = hdmiOutputDevices[i]->mAddress;
3847 String8 name = hdmiOutputDevices[i]->getName();
3848 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3849 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3850 address.c_str(),
3851 name.c_str());
3852 if (status != NO_ERROR) {
3853 continue;
3854 }
3855 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3856 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3857 address.c_str(),
3858 name.c_str());
3859 profileUpdated |= (status == NO_ERROR);
3860 }
Mikhail Naganov708e0382018-05-30 09:53:04 -07003861 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003862 AUDIO_DEVICE_IN_HDMI);
3863 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3864 // Simulate reconnection to update enabled surround sound formats.
3865 String8 address = hdmiInputDevices[i]->mAddress;
3866 String8 name = hdmiInputDevices[i]->getName();
3867 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3868 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3869 address.c_str(),
3870 name.c_str());
3871 if (status != NO_ERROR) {
3872 continue;
3873 }
3874 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3875 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3876 address.c_str(),
3877 name.c_str());
3878 profileUpdated |= (status == NO_ERROR);
3879 }
3880
3881 // Undo the surround formats change due to no audio profiles updated.
3882 if (!profileUpdated) {
3883 if (enabled) {
3884 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3885 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3886 mSurroundFormats.erase(AAC_FORMATS[i]);
3887 }
3888 } else {
3889 mSurroundFormats.erase(audioFormat);
3890 }
3891 } else {
3892 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3893 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3894 mSurroundFormats.insert(AAC_FORMATS[i]);
3895 }
3896 } else {
3897 mSurroundFormats.insert(audioFormat);
3898 }
3899 }
3900 }
3901
3902 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3903}
3904
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003905void AudioPolicyManager::setRecordSilenced(uid_t uid, bool silenced)
3906{
3907 ALOGV("AudioPolicyManager:setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
3908
3909 Vector<sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
3910 for (size_t i = 0; i < activeInputs.size(); i++) {
3911 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
3912 AudioSessionCollection activeSessions = activeDesc->getAudioSessions(true);
3913 for (size_t j = 0; j < activeSessions.size(); j++) {
3914 sp<AudioSession> activeSession = activeSessions.valueAt(j);
3915 if (activeSession->uid() == uid) {
3916 activeSession->setSilenced(silenced);
3917 }
3918 }
3919 }
3920}
3921
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003922status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003923{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003924 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003925
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003926 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003927 if (patchDesc == 0) {
3928 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003929 sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003930 return BAD_VALUE;
3931 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003932 removeAudioPatch(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003933
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003934 audio_stream_type_t stream = sourceDesc->stream();
3935 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003936 if (swOutputDesc != 0) {
Eric Laurent733ce942017-12-07 12:18:25 -08003937 status_t status = stopSource(swOutputDesc, stream, false);
3938 if (status == NO_ERROR) {
3939 swOutputDesc->stop();
3940 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003941 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3942 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003943 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003944 if (hwOutputDesc != 0) {
3945 // release patch between src device and output device
3946 // close Hwoutput and remove from mHwOutputs
3947 } else {
3948 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3949 }
3950 }
3951 return NO_ERROR;
3952}
3953
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003954sp<SourceClientDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
Eric Laurentd60560a2015-04-10 11:31:20 -07003955 audio_io_handle_t output, routing_strategy strategy)
3956{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003957 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07003958 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003959 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3960 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurentd60560a2015-04-10 11:31:20 -07003961 routing_strategy sourceStrategy =
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003962 (routing_strategy) getStrategyForAttr(&attributes);
3963 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003964 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3965 source = sourceDesc;
3966 break;
3967 }
3968 }
3969 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003970}
3971
Eric Laurente552edb2014-03-10 17:42:56 -07003972// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003973// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003974// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003975uint32_t AudioPolicyManager::nextAudioPortGeneration()
3976{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003977 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003978}
3979
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003980#ifdef USE_XML_AUDIO_POLICY_CONF
3981// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3982static const char *kConfigLocationList[] =
3983 {"/odm/etc", "/vendor/etc", "/system/etc"};
3984static const int kConfigLocationListSize =
3985 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3986
3987static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3988 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07003989 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003990 status_t ret;
3991
Petri Gyntherf497f292018-04-17 18:46:10 -07003992 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
3993 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
3994 // A2DP offload supported but disabled: try to use special XML file
3995 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
3996 }
3997 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3998
3999 for (const char* fileName : fileNames) {
4000 for (int i = 0; i < kConfigLocationListSize; i++) {
4001 PolicySerializer serializer;
4002 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
4003 "%s/%s", kConfigLocationList[i], fileName);
4004 ret = serializer.deserialize(audioPolicyXmlConfigFile, config);
4005 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004006 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07004007 return ret;
4008 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004009 }
4010 }
4011 return ret;
4012}
4013#endif
4014
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004015AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
4016 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07004017 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07004018 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004019 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07004020 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07004021 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004022#ifdef USE_XML_AUDIO_POLICY_CONF
4023 mVolumeCurves(new VolumeCurvesCollection()),
4024 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08004025 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004026#else
4027 mVolumeCurves(new StreamDescriptorCollection()),
4028 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
4029 mDefaultOutputDevice),
4030#endif
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004031 mAudioPortGeneration(1),
4032 mBeaconMuteRefCount(0),
4033 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07004034 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08004035 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07004036 mMasterMono(false),
Chris Thornton2b864642017-06-27 21:26:07 -07004037 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE),
4038 mHasComputedSoundTriggerSupportsConcurrentCapture(false)
Eric Laurente552edb2014-03-10 17:42:56 -07004039{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004040}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004041
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004042AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
4043 : AudioPolicyManager(clientInterface, false /*forTesting*/)
4044{
4045 loadConfig();
4046 initialize();
4047}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004048
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004049void AudioPolicyManager::loadConfig() {
François Gaffied1ab2bd2015-12-02 18:20:06 +01004050#ifdef USE_XML_AUDIO_POLICY_CONF
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004051 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01004052#else
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004053 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, getConfig()) != NO_ERROR)
4054 && (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, getConfig()) != NO_ERROR)) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01004055#endif
4056 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004057 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01004058 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004059}
4060
4061status_t AudioPolicyManager::initialize() {
4062 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01004063
4064 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01004065 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
4066 if (!engineInstance) {
4067 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004068 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01004069 }
4070 // Retrieve the Policy Manager Interface
4071 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
4072 if (mEngine == NULL) {
4073 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004074 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01004075 }
4076 mEngine->setObserver(this);
4077 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004078 if (status != NO_ERROR) {
4079 LOG_FATAL("Policy engine not initialized(err=%d)", status);
4080 return status;
4081 }
François Gaffie2110e042015-03-24 08:41:51 +01004082
Eric Laurent3a4311c2014-03-17 12:00:47 -07004083 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07004084 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07004085 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
4086 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Mikhail Naganovd4120142017-12-06 15:49:22 -08004087 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004088 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08004089 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
4090 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07004091 continue;
4092 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08004093 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07004094 // open all output streams needed to access attached devices
4095 // except for direct output streams that are only opened when they are actually
4096 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07004097 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004098 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004099 if (!outProfile->canOpenNewIo()) {
4100 ALOGE("Invalid Output profile max open count %u for profile %s",
4101 outProfile->maxOpenCount, outProfile->getTagName().c_str());
4102 continue;
4103 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004104 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004105 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004106 continue;
4107 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004108 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004109 mTtsOutputAvailable = true;
4110 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004111
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004112 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07004113 continue;
4114 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004115 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01004116 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
4117 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07004118 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004119 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07004120 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004121 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07004122 }
Eric Laurentd78f1532014-09-16 16:38:20 -07004123 if ((profileType & outputDeviceTypes) == 0) {
4124 continue;
4125 }
Eric Laurentc75307b2015-03-17 15:29:32 -07004126 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
4127 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07004128 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov708e0382018-05-30 09:53:04 -07004129 const DeviceVector &devicesForType = supportedDevices.getDevicesFromTypeMask(
4130 profileType);
Eric Laurentc40d9692016-04-13 19:14:13 -07004131 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
4132 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07004133 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004134 status_t status = outputDesc->open(nullptr, profileType, address,
4135 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07004136
4137 if (status != NO_ERROR) {
4138 ALOGW("Cannot open output stream for device %08x on hw module %s",
4139 outputDesc->mDevice,
Mikhail Naganovd4120142017-12-06 15:49:22 -08004140 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07004141 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004142 for (const auto& dev : supportedDevices) {
4143 ssize_t index = mAvailableOutputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07004144 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08004145 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004146 mAvailableOutputDevices[index]->attach(hwModule);
Eric Laurentd78f1532014-09-16 16:38:20 -07004147 }
4148 }
4149 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004150 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004151 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07004152 }
4153 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07004154 setOutputDevice(outputDesc,
Eric Laurentfe231122017-11-17 17:48:06 -08004155 profileType,
Eric Laurentc40d9692016-04-13 19:14:13 -07004156 true,
4157 0,
4158 NULL,
Eric Laurentfe231122017-11-17 17:48:06 -08004159 address);
Eric Laurentd78f1532014-09-16 16:38:20 -07004160 }
Eric Laurente552edb2014-03-10 17:42:56 -07004161 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004162 // open input streams needed to access attached devices to validate
4163 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004164 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004165 if (!inProfile->canOpenNewIo()) {
4166 ALOGE("Invalid Input profile max open count %u for profile %s",
4167 inProfile->maxOpenCount, inProfile->getTagName().c_str());
4168 continue;
4169 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004170 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004171 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004172 continue;
4173 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004174 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07004175 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004176 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
4177
Eric Laurentd78f1532014-09-16 16:38:20 -07004178 if ((profileType & inputDeviceTypes) == 0) {
4179 continue;
4180 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08004181 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08004182 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004183
Mikhail Naganov708e0382018-05-30 09:53:04 -07004184 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(profileType);
Eric Laurent53b810e2017-12-10 17:25:10 -08004185 // the inputs vector must be of size >= 1, but we don't want to crash here
4186 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
4187 : String8("");
4188 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
4189 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
4190
Eric Laurentd78f1532014-09-16 16:38:20 -07004191 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004192 status_t status = inputDesc->open(nullptr,
4193 profileType,
Eric Laurent53b810e2017-12-10 17:25:10 -08004194 address,
Eric Laurentfe231122017-11-17 17:48:06 -08004195 AUDIO_SOURCE_MIC,
4196 AUDIO_INPUT_FLAG_NONE,
4197 &input);
Eric Laurentd78f1532014-09-16 16:38:20 -07004198
4199 if (status == NO_ERROR) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004200 for (const auto& dev : inProfile->getSupportedDevices()) {
4201 ssize_t index = mAvailableInputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07004202 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07004203 if (index >= 0) {
4204 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
4205 if (!devDesc->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004206 devDesc->attach(hwModule);
Eric Laurent83efe1c2017-07-09 16:51:08 -07004207 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07004208 }
Eric Laurentd78f1532014-09-16 16:38:20 -07004209 }
4210 }
Eric Laurentfe231122017-11-17 17:48:06 -08004211 inputDesc->close();
Eric Laurentd78f1532014-09-16 16:38:20 -07004212 } else {
4213 ALOGW("Cannot open input stream for device %08x on hw module %s",
Eric Laurentfe231122017-11-17 17:48:06 -08004214 profileType,
Mikhail Naganovd4120142017-12-06 15:49:22 -08004215 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07004216 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004217 }
4218 }
4219 // make sure all attached devices have been allocated a unique ID
4220 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004221 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004222 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004223 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
4224 continue;
4225 }
François Gaffie2110e042015-03-24 08:41:51 +01004226 // The device is now validated and can be appended to the available devices of the engine
4227 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
4228 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004229 i++;
4230 }
4231 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004232 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01004233 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004234 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
4235 continue;
4236 }
François Gaffie2110e042015-03-24 08:41:51 +01004237 // The device is now validated and can be appended to the available devices of the engine
4238 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
4239 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004240 i++;
4241 }
4242 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004243 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01004244 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004245 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004246 }
jiabin9ff780e2018-03-19 18:19:52 -07004247 // If microphones address is empty, set it according to device type
4248 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
4249 if (mAvailableInputDevices[i]->mAddress.isEmpty()) {
4250 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
4251 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
4252 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
4253 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BACK_MICROPHONE_ADDRESS);
4254 }
4255 }
4256 }
Eric Laurente552edb2014-03-10 17:42:56 -07004257
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004258 if (mPrimaryOutput == 0) {
4259 ALOGE("Failed to open primary output");
4260 status = NO_INIT;
4261 }
Eric Laurente552edb2014-03-10 17:42:56 -07004262
4263 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004264 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004265}
4266
Eric Laurente0720872014-03-11 09:30:41 -07004267AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004268{
Eric Laurente552edb2014-03-10 17:42:56 -07004269 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004270 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004271 }
4272 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004273 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004274 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004275 mAvailableOutputDevices.clear();
4276 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004277 mOutputs.clear();
4278 mInputs.clear();
4279 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004280 mHwModulesAll.clear();
jiabin81772902018-04-02 17:52:27 -07004281 mSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004282}
4283
Eric Laurente0720872014-03-11 09:30:41 -07004284status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004285{
Eric Laurent87ffa392015-05-22 10:32:38 -07004286 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004287}
4288
Eric Laurente552edb2014-03-10 17:42:56 -07004289// ---
4290
Eric Laurent98e38192018-02-15 18:31:53 -08004291void AudioPolicyManager::addOutput(audio_io_handle_t output,
4292 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004293{
Eric Laurent1c333e22014-05-20 10:48:17 -07004294 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08004295 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004296 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004297 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004298 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004299}
4300
François Gaffie53615e22015-03-19 09:24:12 +01004301void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4302{
4303 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004304 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004305}
4306
Eric Laurent98e38192018-02-15 18:31:53 -08004307void AudioPolicyManager::addInput(audio_io_handle_t input,
4308 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004309{
Eric Laurent1c333e22014-05-20 10:48:17 -07004310 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004311 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004312}
Eric Laurente552edb2014-03-10 17:42:56 -07004313
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004314void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08004315 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004316 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004317 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08004318 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004319 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08004320 if (devDesc != 0) {
4321 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
4322 desc->mIoHandle, address.string());
4323 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004324 }
4325}
4326
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004327status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004328 audio_policy_dev_state_t state,
4329 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004330 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07004331{
François Gaffie53615e22015-03-19 09:24:12 +01004332 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07004333 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004334
4335 if (audio_device_is_digital(device)) {
4336 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004337 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004338 }
Eric Laurente552edb2014-03-10 17:42:56 -07004339
Eric Laurent3b73df72014-03-11 09:06:29 -07004340 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004341 // first list already open outputs that can be routed to this device
4342 for (size_t i = 0; i < mOutputs.size(); i++) {
4343 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07004344 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004345 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004346 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
4347 outputs.add(mOutputs.keyAt(i));
4348 } else {
4349 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08004350 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004351 }
Eric Laurente552edb2014-03-10 17:42:56 -07004352 }
4353 }
4354 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004355 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004356 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004357 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4358 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004359 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004360 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004361 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004362 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004363 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4364 j, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004365 }
Eric Laurente552edb2014-03-10 17:42:56 -07004366 }
4367 }
4368 }
4369
Eric Laurent7b279bb2015-12-14 10:18:23 -08004370 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004371
Eric Laurente552edb2014-03-10 17:42:56 -07004372 if (profiles.isEmpty() && outputs.isEmpty()) {
4373 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4374 return BAD_VALUE;
4375 }
4376
4377 // open outputs for matching profiles if needed. Direct outputs are also opened to
4378 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4379 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004380 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004381
4382 // nothing to do if one output is already opened for this profile
4383 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004384 for (j = 0; j < outputs.size(); j++) {
4385 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004386 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004387 // matching profile: save the sample rates, format and channel masks supported
4388 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07004389 if (audio_device_is_digital(device)) {
4390 devDesc->importAudioPort(profile);
4391 }
Eric Laurente552edb2014-03-10 17:42:56 -07004392 break;
4393 }
4394 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004395 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004396 continue;
4397 }
4398
Eric Laurent3974e3b2017-12-07 17:58:43 -08004399 if (!profile->canOpenNewIo()) {
4400 ALOGW("Max Output number %u already opened for this profile %s",
4401 profile->maxOpenCount, profile->getTagName().c_str());
4402 continue;
4403 }
4404
Eric Laurent83efe1c2017-07-09 16:51:08 -07004405 ALOGV("opening output for device %08x with params %s profile %p name %s",
4406 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004407 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004408 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004409 status_t status = desc->open(nullptr, device, address,
4410 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004411
Eric Laurentfe231122017-11-17 17:48:06 -08004412 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004413 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004414 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004415 char *param = audio_device_address_to_parameter(device, address);
4416 mpClientInterface->setParameters(output, String8(param));
4417 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004418 }
Phil Burk00eeb322016-03-31 12:41:00 -07004419 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004420 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004421 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004422 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004423 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004424 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004425 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004426 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004427 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4428 profile->pickAudioProfile(
4429 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004430 config.offload_info.sample_rate = config.sample_rate;
4431 config.offload_info.channel_mask = config.channel_mask;
4432 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004433
4434 status_t status = desc->open(&config, device, address, AUDIO_STREAM_DEFAULT,
4435 AUDIO_OUTPUT_FLAG_NONE, &output);
4436 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004437 output = AUDIO_IO_HANDLE_NONE;
4438 }
Eric Laurentd4692962014-05-05 18:13:44 -07004439 }
4440
Eric Laurentcf2c0212014-07-25 16:20:43 -07004441 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004442 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01004443 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004444 sp<AudioPolicyMix> policyMix;
4445 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004446 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
4447 address.string());
4448 }
François Gaffie036e1e92015-03-19 10:16:24 +01004449 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07004450 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01004451
Eric Laurent87ffa392015-05-22 10:32:38 -07004452 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4453 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004454 // no duplicated output for direct outputs and
4455 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004456 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004457
Eric Laurentd4692962014-05-05 18:13:44 -07004458 //TODO: configure audio effect output stage here
4459
4460 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004461 sp<SwAudioOutputDescriptor> dupOutputDesc =
4462 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4463 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4464 &duplicatedOutput);
4465 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004466 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004467 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004468 } else {
4469 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004470 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004471 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004472 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004473 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004474 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004475 }
Eric Laurente552edb2014-03-10 17:42:56 -07004476 }
4477 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004478 } else {
4479 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004480 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004481 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004482 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004483 profiles.removeAt(profile_index);
4484 profile_index--;
4485 } else {
4486 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004487 // Load digital format info only for digital devices
4488 if (audio_device_is_digital(device)) {
4489 devDesc->importAudioPort(profile);
4490 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004491
François Gaffie53615e22015-03-19 09:24:12 +01004492 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004493 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4494 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004495 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004496 NULL/*patch handle*/, address.string());
4497 }
Eric Laurente552edb2014-03-10 17:42:56 -07004498 ALOGV("checkOutputsForDevice(): adding output %d", output);
4499 }
4500 }
4501
4502 if (profiles.isEmpty()) {
4503 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4504 return BAD_VALUE;
4505 }
Eric Laurentd4692962014-05-05 18:13:44 -07004506 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004507 // check if one opened output is not needed any more after disconnecting one device
4508 for (size_t i = 0; i < mOutputs.size(); i++) {
4509 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004510 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004511 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004512 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004513 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004514 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004515 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004516 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4517 mOutputs.keyAt(i));
4518 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004519 }
Eric Laurente552edb2014-03-10 17:42:56 -07004520 }
4521 }
Eric Laurentd4692962014-05-05 18:13:44 -07004522 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004523 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004524 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4525 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004526 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004527 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004528 "clearing direct output profile %zu on module %s",
4529 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004530 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004531 }
4532 }
4533 }
4534 }
4535 return NO_ERROR;
4536}
4537
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004538status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004539 audio_policy_dev_state_t state,
4540 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004541 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004542{
Paul McLean9080a4c2015-06-18 08:24:02 -07004543 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004544 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004545
4546 if (audio_device_is_digital(device)) {
4547 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004548 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004549 }
4550
Eric Laurentd4692962014-05-05 18:13:44 -07004551 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4552 // first list already open inputs that can be routed to this device
4553 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4554 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004555 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004556 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4557 inputs.add(mInputs.keyAt(input_index));
4558 }
4559 }
4560
4561 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004562 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004563 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004564 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004565 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004566 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004567 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004568
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004569 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004570 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004571 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004572 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004573 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4574 profile_index, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004575 }
Eric Laurentd4692962014-05-05 18:13:44 -07004576 }
4577 }
4578 }
4579
4580 if (profiles.isEmpty() && inputs.isEmpty()) {
4581 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4582 return BAD_VALUE;
4583 }
4584
4585 // open inputs for matching profiles if needed. Direct inputs are also opened to
4586 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4587 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4588
Eric Laurent1c333e22014-05-20 10:48:17 -07004589 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004590
Eric Laurentd4692962014-05-05 18:13:44 -07004591 // nothing to do if one input is already opened for this profile
4592 size_t input_index;
4593 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4594 desc = mInputs.valueAt(input_index);
4595 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004596 if (audio_device_is_digital(device)) {
4597 devDesc->importAudioPort(profile);
4598 }
Eric Laurentd4692962014-05-05 18:13:44 -07004599 break;
4600 }
4601 }
4602 if (input_index != mInputs.size()) {
4603 continue;
4604 }
4605
Eric Laurent3974e3b2017-12-07 17:58:43 -08004606 if (!profile->canOpenNewIo()) {
4607 ALOGW("Max Input number %u already opened for this profile %s",
4608 profile->maxOpenCount, profile->getTagName().c_str());
4609 continue;
4610 }
4611
Eric Laurentfe231122017-11-17 17:48:06 -08004612 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004613 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004614 status_t status = desc->open(nullptr,
4615 device,
4616 address,
4617 AUDIO_SOURCE_MIC,
4618 AUDIO_INPUT_FLAG_NONE,
4619 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004620
Eric Laurentcf2c0212014-07-25 16:20:43 -07004621 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004622 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004623 char *param = audio_device_address_to_parameter(device, address);
4624 mpClientInterface->setParameters(input, String8(param));
4625 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004626 }
Phil Burk00eeb322016-03-31 12:41:00 -07004627 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004628 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004629 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004630 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004631 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004632 }
4633
4634 if (input != 0) {
4635 addInput(input, desc);
4636 }
4637 } // endif input != 0
4638
Eric Laurentcf2c0212014-07-25 16:20:43 -07004639 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004640 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004641 profiles.removeAt(profile_index);
4642 profile_index--;
4643 } else {
4644 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004645 if (audio_device_is_digital(device)) {
4646 devDesc->importAudioPort(profile);
4647 }
Eric Laurentd4692962014-05-05 18:13:44 -07004648 ALOGV("checkInputsForDevice(): adding input %d", input);
4649 }
4650 } // end scan profiles
4651
4652 if (profiles.isEmpty()) {
4653 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4654 return BAD_VALUE;
4655 }
4656 } else {
4657 // Disconnect
4658 // check if one opened input is not needed any more after disconnecting one device
4659 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4660 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004661 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004662 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4663 mInputs.keyAt(input_index));
4664 inputs.add(mInputs.keyAt(input_index));
4665 }
4666 }
4667 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004668 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004669 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004670 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004671 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004672 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004673 if (profile->supportDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004674 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4675 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004676 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004677 }
4678 }
4679 }
4680 } // end disconnect
4681
4682 return NO_ERROR;
4683}
4684
4685
Eric Laurente0720872014-03-11 09:30:41 -07004686void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004687{
4688 ALOGV("closeOutput(%d)", output);
4689
Eric Laurentc75307b2015-03-17 15:29:32 -07004690 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004691 if (outputDesc == NULL) {
4692 ALOGW("closeOutput() unknown output %d", output);
4693 return;
4694 }
François Gaffie036e1e92015-03-19 10:16:24 +01004695 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004696
Eric Laurente552edb2014-03-10 17:42:56 -07004697 // look for duplicated outputs connected to the output being removed.
4698 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004699 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004700 if (dupOutputDesc->isDuplicated() &&
4701 (dupOutputDesc->mOutput1 == outputDesc ||
4702 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004703 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004704 if (dupOutputDesc->mOutput1 == outputDesc) {
4705 outputDesc2 = dupOutputDesc->mOutput2;
4706 } else {
4707 outputDesc2 = dupOutputDesc->mOutput1;
4708 }
4709 // As all active tracks on duplicated output will be deleted,
4710 // and as they were also referenced on the other output, the reference
4711 // count for their stream type must be adjusted accordingly on
4712 // the other output.
Eric Laurent733ce942017-12-07 12:18:25 -08004713 bool wasActive = outputDesc2->isActive();
Eric Laurent3b73df72014-03-11 09:06:29 -07004714 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004715 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07004716 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004717 }
Eric Laurent733ce942017-12-07 12:18:25 -08004718 // stop() will be a no op if the output is still active but is needed in case all
4719 // active streams refcounts where cleared above
4720 if (wasActive) {
4721 outputDesc2->stop();
4722 }
Eric Laurente552edb2014-03-10 17:42:56 -07004723 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4724 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4725
4726 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004727 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004728 }
4729 }
4730
Eric Laurent05b90f82014-08-27 15:32:29 -07004731 nextAudioPortGeneration();
4732
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004733 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004734 if (index >= 0) {
4735 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004736 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004737 mAudioPatches.removeItemsAt(index);
4738 mpClientInterface->onAudioPatchListUpdate();
4739 }
4740
Eric Laurentfe231122017-11-17 17:48:06 -08004741 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004742
François Gaffie53615e22015-03-19 09:24:12 +01004743 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004744 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004745}
4746
4747void AudioPolicyManager::closeInput(audio_io_handle_t input)
4748{
4749 ALOGV("closeInput(%d)", input);
4750
4751 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4752 if (inputDesc == NULL) {
4753 ALOGW("closeInput() unknown input %d", input);
4754 return;
4755 }
4756
Eric Laurent6a94d692014-05-20 11:18:06 -07004757 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004758
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004759 audio_devices_t device = inputDesc->mDevice;
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004760 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004761 if (index >= 0) {
4762 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004763 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004764 mAudioPatches.removeItemsAt(index);
4765 mpClientInterface->onAudioPatchListUpdate();
4766 }
4767
Eric Laurentfe231122017-11-17 17:48:06 -08004768 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004769 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004770
4771 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
4772 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
4773 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
4774 SoundTrigger::setCaptureState(false);
4775 }
Eric Laurente552edb2014-03-10 17:42:56 -07004776}
4777
Eric Laurentc75307b2015-03-17 15:29:32 -07004778SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4779 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004780 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004781{
4782 SortedVector<audio_io_handle_t> outputs;
4783
4784 ALOGVV("getOutputsForDevice() device %04x", device);
4785 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004786 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004787 i, openOutputs.valueAt(i)->isDuplicated(),
4788 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004789 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4790 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4791 outputs.add(openOutputs.keyAt(i));
4792 }
4793 }
4794 return outputs;
4795}
4796
Mikhail Naganov37977152018-07-11 15:54:44 -07004797void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
4798{
4799 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
4800 // output is suspended before any tracks are moved to it
4801 checkA2dpSuspend();
4802 checkOutputForAllStrategies();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004803 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07004804 updateDevicesAndOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004805 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
4806 setMsdPatch();
4807 }
Mikhail Naganov37977152018-07-11 15:54:44 -07004808}
4809
Eric Laurente0720872014-03-11 09:30:41 -07004810void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004811{
4812 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4813 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4814 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4815 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4816
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004817 // also take into account external policy-related changes: add all outputs which are
4818 // associated with policies in the "before" and "after" output vectors
4819 ALOGVV("checkOutputForStrategy(): policy related outputs");
4820 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004821 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004822 if (desc != 0 && desc->mPolicyMix != NULL) {
4823 srcOutputs.add(desc->mIoHandle);
4824 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4825 }
4826 }
4827 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004828 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004829 if (desc != 0 && desc->mPolicyMix != NULL) {
4830 dstOutputs.add(desc->mIoHandle);
4831 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4832 }
4833 }
4834
Mikhail Naganov9de8bd12018-07-23 16:41:31 -07004835 if (srcOutputs != dstOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004836 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4837 // audio from invalidated tracks will be rendered when unmuting
4838 uint32_t maxLatency = 0;
4839 for (audio_io_handle_t srcOut : srcOutputs) {
4840 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4841 if (desc != 0 && maxLatency < desc->latency()) {
4842 maxLatency = desc->latency();
4843 }
4844 }
Eric Laurente552edb2014-03-10 17:42:56 -07004845 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4846 strategy, srcOutputs[0], dstOutputs[0]);
4847 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004848 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004849 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4850 if (desc != 0 && isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004851 setStrategyMute(strategy, true, desc);
Eric Laurentac3a6902018-05-11 16:39:10 -07004852 setStrategyMute(strategy, false, desc, maxLatency * LATENCY_MUTE_FACTOR, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004853 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004854 sp<SourceClientDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004855 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004856 if (source != 0){
4857 connectAudioSource(source);
4858 }
Eric Laurente552edb2014-03-10 17:42:56 -07004859 }
4860
4861 // Move effects associated to this strategy from previous output to new output
4862 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004863 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004864 }
4865 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004866 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004867 if (getStrategy((audio_stream_type_t)i) == strategy) {
4868 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004869 }
4870 }
4871 }
4872}
4873
Eric Laurente0720872014-03-11 09:30:41 -07004874void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004875{
François Gaffie2110e042015-03-24 08:41:51 +01004876 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004877 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004878 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004879 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004880 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004881 checkOutputForStrategy(STRATEGY_SONIFICATION);
4882 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004883 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004884 checkOutputForStrategy(STRATEGY_MEDIA);
4885 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004886 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004887}
4888
Eric Laurente0720872014-03-11 09:30:41 -07004889void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004890{
François Gaffie53615e22015-03-19 09:24:12 +01004891 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004892 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004893 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004894 return;
4895 }
4896
Eric Laurent3a4311c2014-03-17 12:00:47 -07004897 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004898 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4899 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4900 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004901
4902 // if suspended, restore A2DP output if:
4903 // ((SCO device is NOT connected) ||
4904 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4905 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004906 //
Eric Laurentf732e072016-08-03 19:30:28 -07004907 // if not suspended, suspend A2DP output if:
4908 // (SCO device is connected) &&
4909 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4910 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004911 //
4912 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004913 if (!isScoConnected ||
4914 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4915 AUDIO_POLICY_FORCE_BT_SCO) &&
4916 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4917 AUDIO_POLICY_FORCE_BT_SCO) &&
4918 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004919 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004920
4921 mpClientInterface->restoreOutput(a2dpOutput);
4922 mA2dpSuspended = false;
4923 }
4924 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004925 if (isScoConnected &&
4926 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4927 AUDIO_POLICY_FORCE_BT_SCO) ||
4928 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4929 AUDIO_POLICY_FORCE_BT_SCO) ||
4930 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004931 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004932
4933 mpClientInterface->suspendOutput(a2dpOutput);
4934 mA2dpSuspended = true;
4935 }
4936 }
4937}
4938
Eric Laurentc75307b2015-03-17 15:29:32 -07004939audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4940 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004941{
4942 audio_devices_t device = AUDIO_DEVICE_NONE;
4943
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004944 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004945 if (index >= 0) {
4946 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4947 if (patchDesc->mUid != mUidCached) {
4948 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004949 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004950 return outputDesc->device();
4951 }
4952 }
4953
Eric Laurentf3a5a602018-05-22 18:42:55 -07004954 // Check if an explicit routing request exists for an active stream on this output and
4955 // use it in priority before any other rule
4956 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
4957 if (outputDesc->isStreamActive((audio_stream_type_t)stream)) {
4958 audio_devices_t forcedDevice =
4959 mOutputRoutes.getActiveDeviceForStream(
4960 (audio_stream_type_t)stream, mAvailableOutputDevices);
4961
4962 if (forcedDevice != AUDIO_DEVICE_NONE) {
4963 return forcedDevice;
4964 }
4965 }
4966 }
4967
Eric Laurente552edb2014-03-10 17:42:56 -07004968 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004969 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004970 // use device for strategy enforced audible
4971 // 2: we are in call or the strategy phone is active on the output:
4972 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004973 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004974 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004975 // 4: the strategy for enforced audible is active but not enforced on the output:
4976 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004977 // 5: the strategy accessibility is active on the output:
4978 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004979 // 6: the strategy "respectful" sonification is active on the output:
4980 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004981 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004982 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004983 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004984 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004985 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004986 // use device for strategy t-t-s
Eric Laurent484e9272018-06-07 17:29:23 -07004987
4988 // FIXME: extend use of isStrategyActiveOnSameModule() to all strategies
4989 // with a refined rule considering mutually exclusive devices (using same backend)
4990 // as opposed to all streams on the same audio HAL module.
François Gaffiead3183e2015-03-18 16:55:35 +01004991 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004992 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004993 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4994 } else if (isInCall() ||
Eric Laurent484e9272018-06-07 17:29:23 -07004995 isStrategyActiveOnSameModule(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004996 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
Yung Ti Su3e7eb5e2018-06-13 11:48:42 +08004997 } else if (isStrategyActiveOnSameModule(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004998 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004999 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
5000 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08005001 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
5002 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01005003 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005004 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01005005 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005006 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01005007 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005008 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01005009 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005010 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01005011 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005012 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07005013 }
5014
Eric Laurent1c333e22014-05-20 10:48:17 -07005015 ALOGV("getNewOutputDevice() selected device %x", device);
5016 return device;
5017}
5018
Eric Laurentfb66dd92016-01-28 18:32:03 -08005019audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07005020{
Eric Laurentfb66dd92016-01-28 18:32:03 -08005021 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005022
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005023 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005024 if (index >= 0) {
5025 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5026 if (patchDesc->mUid != mUidCached) {
5027 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005028 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005029 return inputDesc->mDevice;
5030 }
5031 }
5032
Eric Laurentdc95a252018-04-12 12:46:56 -07005033 // If we are not in call and no client is active on this input, this methods returns
5034 // AUDIO_DEVICE_NONE, causing the patch on the input stream to be released.
Eric Laurentfb66dd92016-01-28 18:32:03 -08005035 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
Eric Laurentdc95a252018-04-12 12:46:56 -07005036 if (source == AUDIO_SOURCE_DEFAULT && isInCall()) {
5037 source = AUDIO_SOURCE_VOICE_COMMUNICATION;
5038 }
5039 if (source != AUDIO_SOURCE_DEFAULT) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08005040 device = getDeviceAndMixForInputSource(source);
5041 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005042
Eric Laurente552edb2014-03-10 17:42:56 -07005043 return device;
5044}
5045
Eric Laurent794fde22016-03-11 09:50:45 -08005046bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
5047 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08005048 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08005049}
5050
Eric Laurente0720872014-03-11 09:30:41 -07005051uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005052 return (uint32_t)getStrategy(stream);
5053}
5054
Eric Laurente0720872014-03-11 09:30:41 -07005055audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005056 // By checking the range of stream before calling getStrategy, we avoid
5057 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
5058 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08005059 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005060 return AUDIO_DEVICE_NONE;
5061 }
Eric Laurent28d09f02016-03-08 10:43:05 -08005062 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08005063 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
5064 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08005065 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07005066 }
Eric Laurent794fde22016-03-11 09:50:45 -08005067 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08005068 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07005069 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005070 for (audio_io_handle_t output : getOutputsForDevice(curDevices, mOutputs)) {
5071 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08005072 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08005073 curDevices |= outputDesc->device();
5074 }
5075 }
5076 devices |= curDevices;
Eric Laurente552edb2014-03-10 17:42:56 -07005077 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005078
5079 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
5080 and doesn't really need to.*/
5081 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
5082 devices |= AUDIO_DEVICE_OUT_SPEAKER;
5083 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
5084 }
Eric Laurente552edb2014-03-10 17:42:56 -07005085 return devices;
5086}
5087
François Gaffie2110e042015-03-24 08:41:51 +01005088routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
5089{
Eric Laurent223fd5c2014-11-11 13:43:36 -08005090 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01005091 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005092}
5093
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005094uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
5095 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005096 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5097 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
5098 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005099 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5100 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
5101 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005102 // usage to strategy mapping
François Gaffie2110e042015-03-24 08:41:51 +01005103 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005104}
5105
Eric Laurente0720872014-03-11 09:30:41 -07005106void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005107 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005108 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07005109 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
5110 updateDevicesAndOutputs();
5111 break;
5112 default:
5113 break;
5114 }
5115}
5116
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005117uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07005118
5119 // skip beacon mute management if a dedicated TTS output is available
5120 if (mTtsOutputAvailable) {
5121 return 0;
5122 }
5123
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005124 switch(event) {
5125 case STARTING_OUTPUT:
5126 mBeaconMuteRefCount++;
5127 break;
5128 case STOPPING_OUTPUT:
5129 if (mBeaconMuteRefCount > 0) {
5130 mBeaconMuteRefCount--;
5131 }
5132 break;
5133 case STARTING_BEACON:
5134 mBeaconPlayingRefCount++;
5135 break;
5136 case STOPPING_BEACON:
5137 if (mBeaconPlayingRefCount > 0) {
5138 mBeaconPlayingRefCount--;
5139 }
5140 break;
5141 }
5142
5143 if (mBeaconMuteRefCount > 0) {
5144 // any playback causes beacon to be muted
5145 return setBeaconMute(true);
5146 } else {
5147 // no other playback: unmute when beacon starts playing, mute when it stops
5148 return setBeaconMute(mBeaconPlayingRefCount == 0);
5149 }
5150}
5151
5152uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5153 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5154 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5155 // keep track of muted state to avoid repeating mute/unmute operations
5156 if (mBeaconMuted != mute) {
5157 // mute/unmute AUDIO_STREAM_TTS on all outputs
5158 ALOGV("\t muting %d", mute);
5159 uint32_t maxLatency = 0;
5160 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005161 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005162 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07005163 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005164 0 /*delay*/, AUDIO_DEVICE_NONE);
5165 const uint32_t latency = desc->latency() * 2;
5166 if (latency > maxLatency) {
5167 maxLatency = latency;
5168 }
5169 }
5170 mBeaconMuted = mute;
5171 return maxLatency;
5172 }
5173 return 0;
5174}
5175
Eric Laurente0720872014-03-11 09:30:41 -07005176audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01005177 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005178{
Eric Laurentf3a5a602018-05-22 18:42:55 -07005179 // Check if an explicit routing request exists for a stream type corresponding to the
5180 // specified strategy and use it in priority over default routing rules.
5181 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
5182 if (getStrategy((audio_stream_type_t)stream) == strategy) {
5183 audio_devices_t forcedDevice =
5184 mOutputRoutes.getActiveDeviceForStream(
5185 (audio_stream_type_t)stream, mAvailableOutputDevices);
5186 if (forcedDevice != AUDIO_DEVICE_NONE) {
5187 return forcedDevice;
5188 }
Paul McLeanaa981192015-03-21 09:55:15 -07005189 }
5190 }
5191
Eric Laurente552edb2014-03-10 17:42:56 -07005192 if (fromCache) {
5193 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
5194 strategy, mDeviceForStrategy[strategy]);
5195 return mDeviceForStrategy[strategy];
5196 }
François Gaffie2110e042015-03-24 08:41:51 +01005197 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07005198}
5199
Eric Laurente0720872014-03-11 09:30:41 -07005200void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005201{
5202 for (int i = 0; i < NUM_STRATEGIES; i++) {
5203 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
5204 }
5205 mPreviousOutputs = mOutputs;
5206}
5207
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005208uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005209 audio_devices_t prevDevice,
5210 uint32_t delayMs)
5211{
5212 // mute/unmute strategies using an incompatible device combination
5213 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5214 // if unmuting, unmute only after the specified delay
5215 if (outputDesc->isDuplicated()) {
5216 return 0;
5217 }
5218
5219 uint32_t muteWaitMs = 0;
5220 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07005221 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005222
5223 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
5224 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07005225 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07005226 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
5227 bool doMute = false;
5228
5229 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
5230 doMute = true;
5231 outputDesc->mStrategyMutedByDevice[i] = true;
5232 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
5233 doMute = true;
5234 outputDesc->mStrategyMutedByDevice[i] = false;
5235 }
Eric Laurent99401132014-05-07 19:48:15 -07005236 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005237 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005238 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005239 // skip output if it does not share any device with current output
5240 if ((desc->supportedDevices() & outputDesc->supportedDevices())
5241 == AUDIO_DEVICE_NONE) {
5242 continue;
5243 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005244 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07005245 mute ? "muting" : "unmuting", i, curDevice);
5246 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005247 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005248 if (mute) {
5249 // FIXME: should not need to double latency if volume could be applied
5250 // immediately by the audioflinger mixer. We must account for the delay
5251 // between now and the next time the audioflinger thread for this output
5252 // will process a buffer (which corresponds to one buffer size,
5253 // usually 1/2 or 1/4 of the latency).
5254 if (muteWaitMs < desc->latency() * 2) {
5255 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005256 }
5257 }
5258 }
5259 }
5260 }
5261 }
5262
Eric Laurent99401132014-05-07 19:48:15 -07005263 // temporary mute output if device selection changes to avoid volume bursts due to
5264 // different per device volumes
5265 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005266 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5267 // temporary mute duration is conservatively set to 4 times the reported latency
5268 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5269 if (muteWaitMs < tempMuteWaitMs) {
5270 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005271 }
Eric Laurentdc462862016-07-19 12:29:53 -07005272
Eric Laurent99401132014-05-07 19:48:15 -07005273 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005274 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005275 // make sure that we do not start the temporary mute period too early in case of
5276 // delayed device change
5277 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005278 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07005279 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07005280 }
5281 }
5282 }
5283
Eric Laurente552edb2014-03-10 17:42:56 -07005284 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5285 if (muteWaitMs > delayMs) {
5286 muteWaitMs -= delayMs;
5287 usleep(muteWaitMs * 1000);
5288 return muteWaitMs;
5289 }
5290 return 0;
5291}
5292
Eric Laurentc75307b2015-03-17 15:29:32 -07005293uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005294 audio_devices_t device,
5295 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07005296 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005297 audio_patch_handle_t *patchHandle,
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005298 const char *address,
5299 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005300{
Eric Laurentc75307b2015-03-17 15:29:32 -07005301 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005302 AudioParameter param;
5303 uint32_t muteWaitMs;
5304
5305 if (outputDesc->isDuplicated()) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005306 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs,
5307 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
5308 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs,
5309 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005310 return muteWaitMs;
5311 }
5312 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5313 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07005314 if ((device != AUDIO_DEVICE_NONE) &&
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005315 ((device & outputDesc->supportedDevices()) == AUDIO_DEVICE_NONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005316 return 0;
5317 }
5318
5319 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07005320 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07005321
5322 audio_devices_t prevDevice = outputDesc->mDevice;
5323
Paul McLeanaa981192015-03-21 09:55:15 -07005324 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005325
5326 if (device != AUDIO_DEVICE_NONE) {
5327 outputDesc->mDevice = device;
5328 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005329
5330 // if the outputs are not materially active, there is no need to mute.
5331 if (requiresMuteCheck) {
5332 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
5333 } else {
5334 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5335 muteWaitMs = 0;
5336 }
Eric Laurente552edb2014-03-10 17:42:56 -07005337
5338 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005339 // the requested device is AUDIO_DEVICE_NONE
5340 // OR the requested device is the same as current device
5341 // AND force is not specified
5342 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07005343 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07005344 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
5345 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005346 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005347 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005348 return muteWaitMs;
5349 }
5350
5351 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07005352
Eric Laurente552edb2014-03-10 17:42:56 -07005353 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07005354 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005355 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005356 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07005357 DeviceVector deviceList;
5358 if ((address == NULL) || (strlen(address) == 0)) {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005359 deviceList = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurentc40d9692016-04-13 19:14:13 -07005360 } else {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005361 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
5362 device, String8(address));
5363 if (deviceDesc) deviceList.add(deviceDesc);
Eric Laurentc40d9692016-04-13 19:14:13 -07005364 }
5365
Eric Laurent1c333e22014-05-20 10:48:17 -07005366 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005367 PatchBuilder patchBuilder;
5368 patchBuilder.addSource(outputDesc);
Eric Laurent1c333e22014-05-20 10:48:17 -07005369 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005370 patchBuilder.addSink(deviceList.itemAt(i));
Eric Laurent1c333e22014-05-20 10:48:17 -07005371 }
Mikhail Naganovdc769682018-05-04 15:34:08 -07005372 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005373 }
bryant_liuf5e7e792014-08-19 20:07:05 +08005374
5375 // inform all input as well
5376 for (size_t i = 0; i < mInputs.size(); i++) {
5377 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01005378 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08005379 AudioParameter inputCmd = AudioParameter();
5380 ALOGV("%s: inform input %d of device:%d", __func__,
5381 inputDescriptor->mIoHandle, device);
5382 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
5383 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
5384 inputCmd.toString(),
5385 delayMs);
5386 }
5387 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005388 }
Eric Laurente552edb2014-03-10 17:42:56 -07005389
5390 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07005391 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005392
5393 return muteWaitMs;
5394}
5395
Eric Laurentc75307b2015-03-17 15:29:32 -07005396status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005397 int delayMs,
5398 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005399{
Eric Laurent6a94d692014-05-20 11:18:06 -07005400 ssize_t index;
5401 if (patchHandle) {
5402 index = mAudioPatches.indexOfKey(*patchHandle);
5403 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005404 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005405 }
5406 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005407 return INVALID_OPERATION;
5408 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005409 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5410 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005411 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005412 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005413 removeAudioPatch(patchDesc->mHandle);
5414 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005415 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005416 return status;
5417}
5418
5419status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5420 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005421 bool force,
5422 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005423{
5424 status_t status = NO_ERROR;
5425
Eric Laurent1f2f2232014-06-02 12:01:23 -07005426 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005427 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5428 inputDesc->mDevice = device;
5429
Mikhail Naganov708e0382018-05-30 09:53:04 -07005430 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005431 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005432 PatchBuilder patchBuilder;
5433 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005434 // AUDIO_SOURCE_HOTWORD is for internal use only:
5435 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07005436 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5437 auto result = usecase;
5438 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5439 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5440 }
5441 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07005442 //only one input device for now
Mikhail Naganovdc769682018-05-04 15:34:08 -07005443 addSource(deviceList.itemAt(0));
5444 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005445 }
5446 }
5447 return status;
5448}
5449
Eric Laurent6a94d692014-05-20 11:18:06 -07005450status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5451 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005452{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005453 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005454 ssize_t index;
5455 if (patchHandle) {
5456 index = mAudioPatches.indexOfKey(*patchHandle);
5457 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005458 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005459 }
5460 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005461 return INVALID_OPERATION;
5462 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005463 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5464 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005465 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005466 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005467 removeAudioPatch(patchDesc->mHandle);
5468 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005469 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005470 return status;
5471}
5472
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005473sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005474 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005475 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005476 audio_format_t& format,
5477 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005478 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005479{
5480 // Choose an input profile based on the requested capture parameters: select the first available
5481 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005482 //
5483 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5484 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005485
Glenn Kasten730b9262018-03-29 15:01:26 -07005486 sp<IOProfile> firstInexact;
5487 uint32_t updatedSamplingRate = 0;
5488 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5489 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005490 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005491 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005492 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005493 //updatedFormat = format;
Eric Laurent275e8e92014-11-30 15:14:47 -08005494 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005495 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005496 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005497 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005498 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005499 &channelMask /*updatedChannelMask*/,
5500 // FIXME ugly cast
5501 (audio_output_flags_t) flags,
5502 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005503 return profile;
5504 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005505 if (firstInexact == nullptr && profile->isCompatibleProfile(device, address,
5506 samplingRate,
5507 &updatedSamplingRate,
5508 format,
5509 &updatedFormat,
5510 channelMask,
5511 &updatedChannelMask,
5512 // FIXME ugly cast
5513 (audio_output_flags_t) flags,
5514 false /*exactMatchRequiredForInputFlags*/)) {
5515 firstInexact = profile;
5516 }
5517
Eric Laurente552edb2014-03-10 17:42:56 -07005518 }
5519 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005520 if (firstInexact != nullptr) {
5521 samplingRate = updatedSamplingRate;
5522 format = updatedFormat;
5523 channelMask = updatedChannelMask;
5524 return firstInexact;
5525 }
Eric Laurente552edb2014-03-10 17:42:56 -07005526 return NULL;
5527}
5528
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005529
5530audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005531 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005532{
François Gaffie036e1e92015-03-19 10:16:24 +01005533 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5534 audio_devices_t selectedDeviceFromMix =
5535 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005536
François Gaffie036e1e92015-03-19 10:16:24 +01005537 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5538 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005539 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005540 return getDeviceForInputSource(inputSource);
5541}
5542
5543audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5544{
Eric Laurentad2e7b92017-09-14 20:06:42 -07005545 // Routing
5546 // Scan the whole RouteMap to see if we have an explicit route:
5547 // if the input source in the RouteMap is the same as the argument above,
5548 // and activity count is non-zero and the device in the route descriptor is available
5549 // then select this device.
Paul McLean466dc8e2015-04-17 13:15:36 -06005550 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
5551 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
Eric Laurent2157f5b2018-04-25 18:33:02 -07005552 if ((inputSource == route->mSource) && route->isActiveOrChanged() &&
Eric Laurentad2e7b92017-09-14 20:06:42 -07005553 (mAvailableInputDevices.indexOf(route->mDeviceDescriptor) >= 0)) {
Paul McLean466dc8e2015-04-17 13:15:36 -06005554 return route->mDeviceDescriptor->type();
5555 }
5556 }
5557
5558 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005559}
5560
Eric Laurente0720872014-03-11 09:30:41 -07005561float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005562 int index,
5563 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005564{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005565 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005566
5567 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5568 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5569 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5570 // the ringtone volume
5571 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5572 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5573 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5574 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5575 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5576 }
5577
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005578 // in-call: always cap volume by voice volume + some low headroom
5579 if ((stream != AUDIO_STREAM_VOICE_CALL) &&
Eric Laurent7731b5a2018-04-06 15:47:22 -07005580 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005581 switch (stream) {
5582 case AUDIO_STREAM_SYSTEM:
5583 case AUDIO_STREAM_RING:
5584 case AUDIO_STREAM_MUSIC:
5585 case AUDIO_STREAM_ALARM:
5586 case AUDIO_STREAM_NOTIFICATION:
5587 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5588 case AUDIO_STREAM_DTMF:
5589 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005590 int voiceVolumeIndex =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005591 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, device);
Eric Laurent7731b5a2018-04-06 15:47:22 -07005592 const float maxVoiceVolDb =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005593 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, device)
Eric Laurent7731b5a2018-04-06 15:47:22 -07005594 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005595 if (volumeDB > maxVoiceVolDb) {
5596 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5597 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5598 volumeDB = maxVoiceVolDb;
5599 }
5600 } break;
5601 default:
5602 break;
5603 }
5604 }
5605
Eric Laurente552edb2014-03-10 17:42:56 -07005606 // if a headset is connected, apply the following rules to ring tones and notifications
5607 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005608 // - always attenuate notifications volume by 6dB
5609 // - attenuate ring tones volume by 6dB unless music is not playing and
5610 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005611 // - if music is playing, always limit the volume to current music volume,
5612 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005613 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005614 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5615 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5616 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005617 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005618 AUDIO_DEVICE_OUT_USB_HEADSET |
5619 AUDIO_DEVICE_OUT_HEARING_AID)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005620 ((stream_strategy == STRATEGY_SONIFICATION)
5621 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005622 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005623 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005624 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005625 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005626 // when the phone is ringing we must consider that music could have been paused just before
5627 // by the music application and behave as if music was active if the last music track was
5628 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005629 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005630 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005631 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005632 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005633 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005634 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5635 musicDevice),
5636 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005637 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5638 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005639 if (volumeDB > minVolDB) {
5640 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005641 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005642 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005643 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5644 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5645 // on A2DP, also ensure notification volume is not too low compared to media when
5646 // intended to be played
5647 if ((volumeDB > -96.0f) &&
5648 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5649 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5650 stream, device,
5651 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5652 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5653 }
5654 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005655 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5656 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005657 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005658 }
5659 }
5660
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005661 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005662}
5663
Eric Laurent3839bc02018-07-10 18:33:34 -07005664int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
5665 audio_stream_type_t srcStream,
5666 audio_stream_type_t dstStream)
5667{
5668 if (srcStream == dstStream) {
5669 return srcIndex;
5670 }
5671 float minSrc = (float)mVolumeCurves->getVolumeIndexMin(srcStream);
5672 float maxSrc = (float)mVolumeCurves->getVolumeIndexMax(srcStream);
5673 float minDst = (float)mVolumeCurves->getVolumeIndexMin(dstStream);
5674 float maxDst = (float)mVolumeCurves->getVolumeIndexMax(dstStream);
5675
5676 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
5677}
5678
Eric Laurente0720872014-03-11 09:30:41 -07005679status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005680 int index,
5681 const sp<AudioOutputDescriptor>& outputDesc,
5682 audio_devices_t device,
5683 int delayMs,
5684 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005685{
Eric Laurente552edb2014-03-10 17:42:56 -07005686 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005687 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005688 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005689 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005690 return NO_ERROR;
5691 }
François Gaffie2110e042015-03-24 08:41:51 +01005692 audio_policy_forced_cfg_t forceUseForComm =
5693 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005694 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005695 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5696 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005697 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005698 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005699 return INVALID_OPERATION;
5700 }
5701
Eric Laurentc75307b2015-03-17 15:29:32 -07005702 if (device == AUDIO_DEVICE_NONE) {
5703 device = outputDesc->device();
5704 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005705
Eric Laurentffbc80f2015-03-18 18:30:19 -07005706 float volumeDb = computeVolume(stream, index, device);
HW Leeda7581e2018-05-22 18:31:34 +08005707 if (outputDesc->isFixedVolume(device) ||
5708 // Force VoIP volume to max for bluetooth SCO
5709 ((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
5710 (device & AUDIO_DEVICE_OUT_ALL_SCO) != 0)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005711 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005712 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005713
Eric Laurentffbc80f2015-03-18 18:30:19 -07005714 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005715
Eric Laurent3b73df72014-03-11 09:06:29 -07005716 if (stream == AUDIO_STREAM_VOICE_CALL ||
5717 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005718 float voiceVolume;
5719 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005720 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurent3839bc02018-07-10 18:33:34 -07005721 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005722 } else {
5723 voiceVolume = 1.0;
5724 }
5725
Eric Laurent18fba842016-03-31 14:41:26 -07005726 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005727 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5728 mLastVoiceVolume = voiceVolume;
5729 }
5730 }
5731
5732 return NO_ERROR;
5733}
5734
Eric Laurentc75307b2015-03-17 15:29:32 -07005735void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5736 audio_devices_t device,
5737 int delayMs,
5738 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005739{
Eric Laurentc75307b2015-03-17 15:29:32 -07005740 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005741
Eric Laurent794fde22016-03-11 09:50:45 -08005742 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005743 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005744 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005745 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005746 device,
5747 delayMs,
5748 force);
5749 }
5750}
5751
Eric Laurente0720872014-03-11 09:30:41 -07005752void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005753 bool on,
5754 const sp<AudioOutputDescriptor>& outputDesc,
5755 int delayMs,
5756 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005757{
Eric Laurent72249d52015-06-08 11:12:15 -07005758 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5759 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005760 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005761 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005762 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005763 }
5764 }
5765}
5766
Eric Laurente0720872014-03-11 09:30:41 -07005767void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005768 bool on,
5769 const sp<AudioOutputDescriptor>& outputDesc,
5770 int delayMs,
5771 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005772{
Eric Laurente552edb2014-03-10 17:42:56 -07005773 if (device == AUDIO_DEVICE_NONE) {
5774 device = outputDesc->device();
5775 }
5776
Eric Laurentc75307b2015-03-17 15:29:32 -07005777 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5778 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005779
5780 if (on) {
5781 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005782 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005783 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005784 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005785 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005786 }
5787 }
5788 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5789 outputDesc->mMuteCount[stream]++;
5790 } else {
5791 if (outputDesc->mMuteCount[stream] == 0) {
5792 ALOGV("setStreamMute() unmuting non muted stream!");
5793 return;
5794 }
5795 if (--outputDesc->mMuteCount[stream] == 0) {
5796 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005797 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005798 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005799 device,
5800 delayMs);
5801 }
5802 }
5803}
5804
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005805audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5806{
5807 // flags to stream type mapping
5808 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5809 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5810 }
5811 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5812 return AUDIO_STREAM_BLUETOOTH_SCO;
5813 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005814 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5815 return AUDIO_STREAM_TTS;
5816 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005817
Ari Hausman-Cohen5c00d012018-06-26 17:09:11 -07005818 return audio_usage_to_stream_type(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005819}
Eric Laurente83b55d2014-11-14 10:06:21 -08005820
François Gaffie53615e22015-03-19 09:24:12 +01005821bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5822{
Eric Laurente83b55d2014-11-14 10:06:21 -08005823 // has flags that map to a strategy?
5824 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5825 return true;
5826 }
5827
5828 // has known usage?
5829 switch (paa->usage) {
5830 case AUDIO_USAGE_UNKNOWN:
5831 case AUDIO_USAGE_MEDIA:
5832 case AUDIO_USAGE_VOICE_COMMUNICATION:
5833 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5834 case AUDIO_USAGE_ALARM:
5835 case AUDIO_USAGE_NOTIFICATION:
5836 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5837 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5838 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5839 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5840 case AUDIO_USAGE_NOTIFICATION_EVENT:
5841 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5842 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5843 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5844 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005845 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005846 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005847 break;
5848 default:
5849 return false;
5850 }
5851 return true;
5852}
5853
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005854bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005855 routing_strategy strategy, uint32_t inPastMs,
5856 nsecs_t sysTime) const
5857{
5858 if ((sysTime == 0) && (inPastMs != 0)) {
5859 sysTime = systemTime();
5860 }
Eric Laurent794fde22016-03-11 09:50:45 -08005861 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005862 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5863 (NUM_STRATEGIES == strategy)) &&
5864 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5865 return true;
5866 }
5867 }
5868 return false;
5869}
5870
Eric Laurent484e9272018-06-07 17:29:23 -07005871bool AudioPolicyManager::isStrategyActiveOnSameModule(const sp<AudioOutputDescriptor>& outputDesc,
5872 routing_strategy strategy, uint32_t inPastMs,
5873 nsecs_t sysTime) const
5874{
5875 for (size_t i = 0; i < mOutputs.size(); i++) {
5876 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5877 if (outputDesc->sharesHwModuleWith(desc)
5878 && isStrategyActive(desc, strategy, inPastMs, sysTime)) {
5879 return true;
5880 }
5881 }
5882 return false;
5883}
5884
François Gaffie2110e042015-03-24 08:41:51 +01005885audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5886{
5887 return mEngine->getForceUse(usage);
5888}
5889
5890bool AudioPolicyManager::isInCall()
5891{
5892 return isStateInCall(mEngine->getPhoneState());
5893}
5894
5895bool AudioPolicyManager::isStateInCall(int state)
5896{
5897 return is_state_in_call(state);
5898}
5899
Eric Laurentd60560a2015-04-10 11:31:20 -07005900void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5901{
5902 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005903 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5904 if (sourceDesc->srcDevice()->equals(deviceDesc)) {
5905 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->portId());
5906 stopAudioSource(sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005907 }
5908 }
5909
5910 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5911 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5912 bool release = false;
5913 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5914 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5915 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5916 source->ext.device.type == deviceDesc->type()) {
5917 release = true;
5918 }
5919 }
5920 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5921 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5922 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5923 sink->ext.device.type == deviceDesc->type()) {
5924 release = true;
5925 }
5926 }
5927 if (release) {
5928 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5929 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5930 }
5931 }
5932}
5933
Phil Burk09bc4612016-02-24 15:58:15 -08005934// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005935void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5936 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005937 // TODO Set this based on Config properties.
5938 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005939
5940 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5941 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005942 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005943
jiabin81772902018-04-02 17:52:27 -07005944 // If MANUAL, keep the supported surround sound formats as current enabled ones.
5945 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
5946 formats.clear();
5947 for (auto it = mSurroundFormats.begin(); it != mSurroundFormats.end(); it++) {
5948 formats.add(*it);
Phil Burk09bc4612016-02-24 15:58:15 -08005949 }
jiabin81772902018-04-02 17:52:27 -07005950 // Always enable IEC61937 when in MANUAL mode.
5951 formats.add(AUDIO_FORMAT_IEC61937);
5952 } else { // NEVER, AUTO or ALWAYS
5953 // Analyze original support for various formats.
5954 bool supportsAC3 = false;
5955 bool supportsOtherSurround = false;
5956 bool supportsIEC61937 = false;
5957 mSurroundFormats.clear();
5958 for (ssize_t formatIndex = 0; formatIndex < (ssize_t)formats.size(); formatIndex++) {
5959 audio_format_t format = formats[formatIndex];
5960 switch (format) {
5961 case AUDIO_FORMAT_AC3:
5962 supportsAC3 = true;
5963 break;
5964 case AUDIO_FORMAT_E_AC3:
5965 case AUDIO_FORMAT_DTS:
5966 case AUDIO_FORMAT_DTS_HD:
5967 // If ALWAYS, remove all other surround formats here
5968 // since we will add them later.
5969 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5970 formats.removeAt(formatIndex);
5971 formatIndex--;
5972 }
5973 supportsOtherSurround = true;
5974 break;
5975 case AUDIO_FORMAT_IEC61937:
5976 supportsIEC61937 = true;
5977 break;
5978 default:
5979 break;
5980 }
5981 }
Phil Burk09bc4612016-02-24 15:58:15 -08005982
jiabin81772902018-04-02 17:52:27 -07005983 // Modify formats based on surround preferences.
5984 // If NEVER, remove support for surround formats.
5985 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5986 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5987 // Remove surround sound related formats.
5988 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5989 audio_format_t format = formats[formatIndex];
5990 switch(format) {
5991 case AUDIO_FORMAT_AC3:
5992 case AUDIO_FORMAT_E_AC3:
5993 case AUDIO_FORMAT_DTS:
5994 case AUDIO_FORMAT_DTS_HD:
5995 case AUDIO_FORMAT_IEC61937:
5996 formats.removeAt(formatIndex);
5997 break;
5998 default:
5999 formatIndex++; // keep it
6000 break;
6001 }
6002 }
6003 supportsAC3 = false;
6004 supportsOtherSurround = false;
6005 supportsIEC61937 = false;
6006 }
6007 } else { // AUTO or ALWAYS
6008 // Most TVs support AC3 even if they do not report it in the EDID.
6009 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
6010 && !supportsAC3) {
6011 formats.add(AUDIO_FORMAT_AC3);
6012 supportsAC3 = true;
6013 }
6014
6015 // If ALWAYS, add support for raw surround formats if all are missing.
6016 // This assumes that if any of these formats are reported by the HAL
6017 // then the report is valid and should not be modified.
6018 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
6019 formats.add(AUDIO_FORMAT_E_AC3);
6020 formats.add(AUDIO_FORMAT_DTS);
6021 formats.add(AUDIO_FORMAT_DTS_HD);
6022 supportsOtherSurround = true;
6023 }
6024
6025 // Add support for IEC61937 if any raw surround supported.
6026 // The HAL could do this but add it here, just in case.
6027 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
6028 formats.add(AUDIO_FORMAT_IEC61937);
6029 supportsIEC61937 = true;
6030 }
6031
6032 // Add reported surround sound formats to enabled surround formats.
6033 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
Phil Burk07ac1142016-03-25 13:39:29 -07006034 audio_format_t format = formats[formatIndex];
6035 switch(format) {
6036 case AUDIO_FORMAT_AC3:
6037 case AUDIO_FORMAT_E_AC3:
6038 case AUDIO_FORMAT_DTS:
6039 case AUDIO_FORMAT_DTS_HD:
jiabin81772902018-04-02 17:52:27 -07006040 case AUDIO_FORMAT_AAC_LC:
6041 case AUDIO_FORMAT_DOLBY_TRUEHD:
6042 case AUDIO_FORMAT_E_AC3_JOC:
6043 mSurroundFormats.insert(format);
Phil Burk07ac1142016-03-25 13:39:29 -07006044 default:
Phil Burk07ac1142016-03-25 13:39:29 -07006045 break;
6046 }
Phil Burk09bc4612016-02-24 15:58:15 -08006047 }
Phil Burk07ac1142016-03-25 13:39:29 -07006048 }
Phil Burk09bc4612016-02-24 15:58:15 -08006049 }
Phil Burk0709b0a2016-03-31 12:54:57 -07006050}
6051
6052// Modify the list of channel masks supported.
6053void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
6054 ChannelsVector &channelMasks = *channelMasksPtr;
6055 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6056 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
6057
6058 // If NEVER, then remove support for channelMasks > stereo.
6059 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
6060 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
6061 audio_channel_mask_t channelMask = channelMasks[maskIndex];
6062 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
6063 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
6064 channelMasks.removeAt(maskIndex);
6065 } else {
6066 maskIndex++;
6067 }
6068 }
jiabin81772902018-04-02 17:52:27 -07006069 // If ALWAYS or MANUAL, then make sure we at least support 5.1
6070 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
6071 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006072 bool supports5dot1 = false;
6073 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006074 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006075 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
6076 supports5dot1 = true;
6077 break;
6078 }
6079 }
6080 // If not then add 5.1 support.
6081 if (!supports5dot1) {
6082 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
6083 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
6084 }
Phil Burk09bc4612016-02-24 15:58:15 -08006085 }
6086}
6087
Phil Burk00eeb322016-03-31 12:41:00 -07006088void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
6089 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01006090 AudioProfileVector &profiles)
6091{
6092 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07006093
François Gaffie112b0af2015-11-19 16:13:25 +01006094 // Format MUST be checked first to update the list of AudioProfile
6095 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006096 reply = mpClientInterface->getParameters(
6097 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07006098 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006099 AudioParameter repliedParameters(reply);
6100 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006101 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01006102 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
6103 return;
6104 }
Phil Burk09bc4612016-02-24 15:58:15 -08006105 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07006106 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006107 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07006108 }
Phil Burk09bc4612016-02-24 15:58:15 -08006109 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01006110 }
François Gaffie112b0af2015-11-19 16:13:25 +01006111
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006112 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08006113 ChannelsVector channelMasks;
6114 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01006115 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07006116 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01006117
6118 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006119 reply = mpClientInterface->getParameters(
6120 ioHandle,
6121 requestedParameters.toString() + ";" +
6122 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01006123 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006124 AudioParameter repliedParameters(reply);
6125 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006126 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006127 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01006128 }
6129 }
6130 if (profiles.hasDynamicChannelsFor(format)) {
6131 reply = mpClientInterface->getParameters(ioHandle,
6132 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07006133 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01006134 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006135 AudioParameter repliedParameters(reply);
6136 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006137 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006138 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07006139 if (device == AUDIO_DEVICE_OUT_HDMI) {
6140 filterSurroundChannelMasks(&channelMasks);
6141 }
François Gaffie112b0af2015-11-19 16:13:25 +01006142 }
6143 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08006144 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006145 }
6146}
Eric Laurentd60560a2015-04-10 11:31:20 -07006147
Mikhail Naganovdc769682018-05-04 15:34:08 -07006148status_t AudioPolicyManager::installPatch(const char *caller,
6149 audio_patch_handle_t *patchHandle,
6150 AudioIODescriptorInterface *ioDescriptor,
6151 const struct audio_patch *patch,
6152 int delayMs)
6153{
6154 ssize_t index = mAudioPatches.indexOfKey(
6155 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6156 *patchHandle : ioDescriptor->getPatchHandle());
6157 sp<AudioPatch> patchDesc;
6158 status_t status = installPatch(
6159 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6160 if (status == NO_ERROR) {
6161 ioDescriptor->setPatchHandle(patchDesc->mHandle);
6162 }
6163 return status;
6164}
6165
6166status_t AudioPolicyManager::installPatch(const char *caller,
6167 ssize_t index,
6168 audio_patch_handle_t *patchHandle,
6169 const struct audio_patch *patch,
6170 int delayMs,
6171 uid_t uid,
6172 sp<AudioPatch> *patchDescPtr)
6173{
6174 sp<AudioPatch> patchDesc;
6175 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6176 if (index >= 0) {
6177 patchDesc = mAudioPatches.valueAt(index);
6178 afPatchHandle = patchDesc->mAfPatchHandle;
6179 }
6180
6181 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6182 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6183 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6184 if (status == NO_ERROR) {
6185 if (index < 0) {
6186 patchDesc = new AudioPatch(patch, uid);
6187 addAudioPatch(patchDesc->mHandle, patchDesc);
6188 } else {
6189 patchDesc->mPatch = *patch;
6190 }
6191 patchDesc->mAfPatchHandle = afPatchHandle;
6192 if (patchHandle) {
6193 *patchHandle = patchDesc->mHandle;
6194 }
6195 nextAudioPortGeneration();
6196 mpClientInterface->onAudioPatchListUpdate();
6197 }
6198 if (patchDescPtr) *patchDescPtr = patchDesc;
6199 return status;
6200}
6201
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006202} // namespace android