blob: 2335135eef60098c02b6f504dbce97a92f6393d8 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070017#define LOG_TAG "APM_AudioPolicyManager"
Eric Laurente552edb2014-03-10 17:42:56 -070018//#define LOG_NDEBUG 0
19
20//#define VERY_VERBOSE_LOGGING
21#ifdef VERY_VERBOSE_LOGGING
22#define ALOGVV ALOGV
23#else
24#define ALOGVV(a...) do { } while(0)
25#endif
26
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +090027#define AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH 128
28#define AUDIO_POLICY_XML_CONFIG_FILE_NAME "audio_policy_configuration.xml"
Petri Gyntherf497f292018-04-17 18:46:10 -070029#define AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME \
30 "audio_policy_configuration_a2dp_offload_disabled.xml"
François Gaffief4ad6e52015-11-19 16:59:57 +010031
Eric Laurentd4692962014-05-05 18:13:44 -070032#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070033#include <math.h>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110034#include <vector>
Eric Laurentd4692962014-05-05 18:13:44 -070035
François Gaffie2110e042015-03-24 08:41:51 +010036#include <AudioPolicyManagerInterface.h>
37#include <AudioPolicyEngineInstance.h>
Eric Laurente552edb2014-03-10 17:42:56 -070038#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070039#include <utils/Log.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070040#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080041#include <media/AudioPolicyHelper.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070042#include <private/android_filesystem_config.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070043#include <soundtrigger/SoundTrigger.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070044#include <system/audio.h>
Mikhail Naganov9ee05402016-10-13 15:58:17 -070045#include <audio_policy_conf.h>
Eric Laurentd4692962014-05-05 18:13:44 -070046#include "AudioPolicyManager.h"
François Gaffied1ab2bd2015-12-02 18:20:06 +010047#ifndef USE_XML_AUDIO_POLICY_CONF
François Gaffie53615e22015-03-19 09:24:12 +010048#include <ConfigParsingUtils.h>
François Gaffied1ab2bd2015-12-02 18:20:06 +010049#include <StreamDescriptor.h>
François Gaffief4ad6e52015-11-19 16:59:57 +010050#endif
François Gaffied1ab2bd2015-12-02 18:20:06 +010051#include <Serializer.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010052#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010053#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070054
Eric Laurent3b73df72014-03-11 09:06:29 -070055namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070056
Eric Laurentdc462862016-07-19 12:29:53 -070057//FIXME: workaround for truncated touch sounds
58// to be removed when the problem is handled by system UI
59#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070060
61// Largest difference in dB on earpiece in call between the voice volume and another
62// media / notification / system volume.
63constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
64
jiabin81772902018-04-02 17:52:27 -070065#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
66// Array of all surround formats.
67static const audio_format_t SURROUND_FORMATS[] = {
68 AUDIO_FORMAT_AC3,
69 AUDIO_FORMAT_E_AC3,
70 AUDIO_FORMAT_DTS,
71 AUDIO_FORMAT_DTS_HD,
72 AUDIO_FORMAT_AAC_LC,
73 AUDIO_FORMAT_DOLBY_TRUEHD,
74 AUDIO_FORMAT_E_AC3_JOC,
75};
76// Array of all AAC formats. When AAC is enabled by users, all AAC formats should be enabled.
77static const audio_format_t AAC_FORMATS[] = {
78 AUDIO_FORMAT_AAC_LC,
79 AUDIO_FORMAT_AAC_HE_V1,
80 AUDIO_FORMAT_AAC_HE_V2,
81 AUDIO_FORMAT_AAC_ELD,
82 AUDIO_FORMAT_AAC_XHE,
83};
84
Mikhail Naganov15be9d22017-11-08 14:18:13 +110085// Compressed formats for MSD module, ordered from most preferred to least preferred.
86static const std::vector<audio_format_t> compressedFormatsOrder = {{
87 AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
88 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
89// Channel masks for MSD module, 3D > 2D > 1D ordering (most preferred to least preferred).
90static const std::vector<audio_channel_mask_t> surroundChannelMasksOrder = {{
91 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
92 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
93 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
94
Eric Laurente552edb2014-03-10 17:42:56 -070095// ----------------------------------------------------------------------------
96// AudioPolicyInterface implementation
97// ----------------------------------------------------------------------------
98
Eric Laurente0720872014-03-11 09:30:41 -070099status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -0800100 audio_policy_dev_state_t state,
101 const char *device_address,
102 const char *device_name)
Eric Laurente552edb2014-03-10 17:42:56 -0700103{
jiabina7b43792018-02-15 16:04:46 -0800104 status_t status = setDeviceConnectionStateInt(device, state, device_address, device_name);
105 nextAudioPortGeneration();
106 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800107}
108
François Gaffie44481e72016-04-20 07:49:57 +0200109void AudioPolicyManager::broadcastDeviceConnectionState(audio_devices_t device,
110 audio_policy_dev_state_t state,
111 const String8 &device_address)
112{
113 AudioParameter param(device_address);
114 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganov388360c2016-10-17 17:09:41 -0700115 AudioParameter::keyStreamConnect : AudioParameter::keyStreamDisconnect);
François Gaffie44481e72016-04-20 07:49:57 +0200116 param.addInt(key, device);
117 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
118}
119
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800120status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800121 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -0800122 const char *device_address,
123 const char *device_name)
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800124{
Paul McLeane743a472015-01-28 11:07:31 -0800125 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s",
Mikhail Naganov7e22e942017-12-07 10:04:29 -0800126 device, state, device_address, device_name);
Eric Laurente552edb2014-03-10 17:42:56 -0700127
128 // connect/disconnect only 1 device at a time
129 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
130
François Gaffie53615e22015-03-19 09:24:12 +0100131 sp<DeviceDescriptor> devDesc =
132 mHwModules.getDeviceDescriptor(device, device_address, device_name);
Paul McLeane743a472015-01-28 11:07:31 -0800133
Eric Laurente552edb2014-03-10 17:42:56 -0700134 // handle output devices
135 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700136 SortedVector <audio_io_handle_t> outputs;
137
Eric Laurent3a4311c2014-03-17 12:00:47 -0700138 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
139
Eric Laurente552edb2014-03-10 17:42:56 -0700140 // save a copy of the opened output descriptors before any output is opened or closed
141 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
142 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700143 switch (state)
144 {
145 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800146 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700147 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700148 ALOGW("setDeviceConnectionState() device already connected: %x", device);
149 return INVALID_OPERATION;
150 }
151 ALOGV("setDeviceConnectionState() connecting device %x", device);
152
Eric Laurente552edb2014-03-10 17:42:56 -0700153 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700154 index = mAvailableOutputDevices.add(devDesc);
155 if (index >= 0) {
François Gaffie53615e22015-03-19 09:24:12 +0100156 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700157 if (module == 0) {
158 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
159 device);
160 mAvailableOutputDevices.remove(devDesc);
161 return INVALID_OPERATION;
162 }
Paul McLeane743a472015-01-28 11:07:31 -0800163 mAvailableOutputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700164 } else {
165 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700166 }
167
François Gaffie44481e72016-04-20 07:49:57 +0200168 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
169 // parameters on newly connected devices (instead of opening the outputs...)
170 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
171
Eric Laurenta1d525f2015-01-29 13:36:45 -0800172 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700173 mAvailableOutputDevices.remove(devDesc);
François Gaffie44481e72016-04-20 07:49:57 +0200174
175 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
176 devDesc->mAddress);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700177 return INVALID_OPERATION;
178 }
François Gaffie2110e042015-03-24 08:41:51 +0100179 // Propagate device availability to Engine
180 mEngine->setDeviceConnectionState(devDesc, state);
181
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700182 // outputs should never be empty here
183 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
184 "checkOutputsForDevice() returned no outputs but status OK");
185 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
186 outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800187
Eric Laurent3ae5f312015-02-03 17:12:08 -0800188 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700189 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700190 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700191 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700192 ALOGW("setDeviceConnectionState() device not connected: %x", device);
193 return INVALID_OPERATION;
194 }
195
Paul McLean5c477aa2014-08-20 16:47:57 -0700196 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
197
Paul McLeane743a472015-01-28 11:07:31 -0800198 // Send Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200199 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700200
Eric Laurente552edb2014-03-10 17:42:56 -0700201 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700202 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700203
Eric Laurenta1d525f2015-01-29 13:36:45 -0800204 checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress);
François Gaffie2110e042015-03-24 08:41:51 +0100205
206 // Propagate device availability to Engine
207 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700208 } break;
209
210 default:
211 ALOGE("setDeviceConnectionState() invalid state: %x", state);
212 return BAD_VALUE;
213 }
214
Mikhail Naganov37977152018-07-11 15:54:44 -0700215 checkForDeviceAndOutputChanges([&]() {
216 // outputs must be closed after checkOutputForAllStrategies() is executed
217 if (!outputs.isEmpty()) {
218 for (audio_io_handle_t output : outputs) {
219 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
220 // close unused outputs after device disconnection or direct outputs that have been
221 // opened by checkOutputsForDevice() to query dynamic parameters
222 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
223 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
224 (desc->mDirectOpenCount == 0))) {
225 closeOutput(output);
226 }
Eric Laurente552edb2014-03-10 17:42:56 -0700227 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700228 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
229 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700230 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700231 return false;
232 });
Eric Laurente552edb2014-03-10 17:42:56 -0700233
Eric Laurent87ffa392015-05-22 10:32:38 -0700234 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700235 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
236 updateCallRouting(newDevice);
237 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100238 const audio_devices_t msdOutDevice = getMsdAudioOutDeviceTypes();
Eric Laurente552edb2014-03-10 17:42:56 -0700239 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700240 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
241 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
242 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700243 // do not force device change on duplicated output because if device is 0, it will
244 // also force a device 0 for the two outputs it is duplicated to which may override
245 // a valid device selection on those outputs.
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100246 bool force = (msdOutDevice == AUDIO_DEVICE_NONE || msdOutDevice != desc->device())
247 && !desc->isDuplicated()
François Gaffie53615e22015-03-19 09:24:12 +0100248 && (!device_distinguishes_on_address(device)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700249 // always force when disconnecting (a non-duplicated device)
250 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
Eric Laurentc75307b2015-03-17 15:29:32 -0700251 setOutputDevice(desc, newDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700252 }
Eric Laurente552edb2014-03-10 17:42:56 -0700253 }
254
Eric Laurentd60560a2015-04-10 11:31:20 -0700255 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
256 cleanUpForDevice(devDesc);
257 }
258
Eric Laurent72aa32f2014-05-30 18:51:48 -0700259 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700260 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700261 } // end if is output device
262
Eric Laurente552edb2014-03-10 17:42:56 -0700263 // handle input devices
264 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700265 SortedVector <audio_io_handle_t> inputs;
266
Eric Laurent3a4311c2014-03-17 12:00:47 -0700267 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700268 switch (state)
269 {
270 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700271 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700272 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700273 ALOGW("setDeviceConnectionState() device already connected: %d", device);
274 return INVALID_OPERATION;
275 }
François Gaffie53615e22015-03-19 09:24:12 +0100276 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700277 if (module == NULL) {
278 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
279 device);
280 return INVALID_OPERATION;
281 }
François Gaffie44481e72016-04-20 07:49:57 +0200282
283 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
284 // parameters on newly connected devices (instead of opening the inputs...)
285 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
286
Paul McLean9080a4c2015-06-18 08:24:02 -0700287 if (checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress) != NO_ERROR) {
François Gaffie44481e72016-04-20 07:49:57 +0200288 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
289 devDesc->mAddress);
Eric Laurentd4692962014-05-05 18:13:44 -0700290 return INVALID_OPERATION;
291 }
292
Eric Laurent3a4311c2014-03-17 12:00:47 -0700293 index = mAvailableInputDevices.add(devDesc);
294 if (index >= 0) {
Paul McLeane743a472015-01-28 11:07:31 -0800295 mAvailableInputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700296 } else {
297 return NO_MEMORY;
298 }
Eric Laurent3ae5f312015-02-03 17:12:08 -0800299
François Gaffie2110e042015-03-24 08:41:51 +0100300 // Propagate device availability to Engine
301 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700302 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700303
304 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700305 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700306 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700307 ALOGW("setDeviceConnectionState() device not connected: %d", device);
308 return INVALID_OPERATION;
309 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700310
311 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
312
313 // Set Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200314 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700315
Paul McLean9080a4c2015-06-18 08:24:02 -0700316 checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700317 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700318
François Gaffie2110e042015-03-24 08:41:51 +0100319 // Propagate device availability to Engine
320 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700321 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700322
323 default:
324 ALOGE("setDeviceConnectionState() invalid state: %x", state);
325 return BAD_VALUE;
326 }
327
Eric Laurentd4692962014-05-05 18:13:44 -0700328 closeAllInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700329 // As the input device list can impact the output device selection, update
330 // getDeviceForStrategy() cache
331 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700332
Eric Laurent87ffa392015-05-22 10:32:38 -0700333 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700334 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
335 updateCallRouting(newDevice);
336 }
337
Eric Laurentd60560a2015-04-10 11:31:20 -0700338 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
339 cleanUpForDevice(devDesc);
340 }
341
Eric Laurentb52c1522014-05-20 11:27:36 -0700342 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700343 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700344 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700345
346 ALOGW("setDeviceConnectionState() invalid device: %x", device);
347 return BAD_VALUE;
348}
349
Eric Laurente0720872014-03-11 09:30:41 -0700350audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100351 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700352{
Eric Laurent634b7142016-04-20 13:48:02 -0700353 sp<DeviceDescriptor> devDesc =
354 mHwModules.getDeviceDescriptor(device, device_address, "",
355 (strlen(device_address) != 0)/*matchAddress*/);
356
357 if (devDesc == 0) {
358 ALOGW("getDeviceConnectionState() undeclared device, type %08x, address: %s",
359 device, device_address);
360 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
361 }
François Gaffie53615e22015-03-19 09:24:12 +0100362
Eric Laurent3a4311c2014-03-17 12:00:47 -0700363 DeviceVector *deviceVector;
364
Eric Laurente552edb2014-03-10 17:42:56 -0700365 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700366 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700367 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700368 deviceVector = &mAvailableInputDevices;
369 } else {
370 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
371 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700372 }
Eric Laurent634b7142016-04-20 13:48:02 -0700373
374 return (deviceVector->getDevice(device, String8(device_address)) != 0) ?
375 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800376}
377
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800378status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
379 const char *device_address,
380 const char *device_name)
381{
382 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700383 String8 reply;
384 AudioParameter param;
385 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800386
387 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s",
388 device, device_address, device_name);
389
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800390 // connect/disconnect only 1 device at a time
391 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
392
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800393 // Check if the device is currently connected
394 sp<DeviceDescriptor> devDesc =
395 mHwModules.getDeviceDescriptor(device, device_address, device_name);
396 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
397 if (index < 0) {
398 // Nothing to do: device is not connected
399 return NO_ERROR;
400 }
401
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700402 // For offloaded A2DP, Hw modules may have the capability to
403 // configure codecs. Check if any of the loaded hw modules
404 // supports this.
405 // If supported, send a set parameter to configure A2DP codecs
406 // and return. No need to toggle device state.
407 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
408 reply = mpClientInterface->getParameters(
409 AUDIO_IO_HANDLE_NONE,
410 String8(AudioParameter::keyReconfigA2dpSupported));
411 AudioParameter repliedParameters(reply);
412 repliedParameters.getInt(
413 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
414 if (isReconfigA2dpSupported) {
415 const String8 key(AudioParameter::keyReconfigA2dp);
416 param.add(key, String8("true"));
417 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
418 return NO_ERROR;
419 }
420 }
421
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800422 // Toggle the device state: UNAVAILABLE -> AVAILABLE
423 // This will force reading again the device configuration
424 status = setDeviceConnectionState(device,
425 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
426 device_address, device_name);
427 if (status != NO_ERROR) {
428 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
429 status);
430 return status;
431 }
432
433 status = setDeviceConnectionState(device,
434 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
435 device_address, device_name);
436 if (status != NO_ERROR) {
437 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
438 status);
439 return status;
440 }
441
442 return NO_ERROR;
443}
444
Eric Laurentdc462862016-07-19 12:29:53 -0700445uint32_t AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700446{
447 bool createTxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700448 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700449
Andy Hunga76c7de2016-12-13 19:14:31 -0800450 if(!hasPrimaryOutput() || mPrimaryOutput->device() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurentdc462862016-07-19 12:29:53 -0700451 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700452 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800453 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700454 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
455
456 // release existing RX patch if any
457 if (mCallRxPatch != 0) {
458 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
459 mCallRxPatch.clear();
460 }
461 // release TX patch if any
462 if (mCallTxPatch != 0) {
463 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
464 mCallTxPatch.clear();
465 }
466
467 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
468 // via setOutputDevice() on primary output.
469 // Otherwise, create two audio patches for TX and RX path.
470 if (availablePrimaryOutputDevices() & rxDevice) {
Eric Laurentdc462862016-07-19 12:29:53 -0700471 muteWaitMs = setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700472 // If the TX device is also on the primary HW module, setOutputDevice() will take care
473 // of it due to legacy implementation. If not, create a patch.
474 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
475 == AUDIO_DEVICE_NONE) {
476 createTxPatch = true;
477 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700478 } else { // create RX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800479 mCallRxPatch = createTelephonyPatch(true /*isRx*/, rxDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700480 createTxPatch = true;
481 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700482 if (createTxPatch) { // create TX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800483 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txDevice, delayMs);
484 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700485
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800486 return muteWaitMs;
487}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700488
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800489sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
490 bool isRx, audio_devices_t device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700491 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700492
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800493 sp<DeviceDescriptor> txSourceDeviceDesc;
494 if (isRx) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700495 patchBuilder.addSink(findDevice(mAvailableOutputDevices, device)).
496 addSource(findDevice(mAvailableInputDevices, AUDIO_DEVICE_IN_TELEPHONY_RX));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800497 } else {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700498 patchBuilder.addSource(txSourceDeviceDesc = findDevice(mAvailableInputDevices, device)).
499 addSink(findDevice(mAvailableOutputDevices, AUDIO_DEVICE_OUT_TELEPHONY_TX));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800500 }
501
502 audio_devices_t outputDevice = isRx ? device : AUDIO_DEVICE_OUT_TELEPHONY_TX;
503 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(outputDevice, mOutputs);
504 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
505 // request to reuse existing output stream if one is already opened to reach the target device
506 if (output != AUDIO_IO_HANDLE_NONE) {
507 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
508 ALOG_ASSERT(!outputDesc->isDuplicated(),
509 "%s() %#x device output %d is duplicated", __func__, outputDevice, output);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700510 patchBuilder.addSource(outputDesc, { .stream = AUDIO_STREAM_PATCH });
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800511 }
512
513 if (!isRx) {
Eric Laurentc0a889f2015-10-14 14:36:34 -0700514 // terminate active capture if on the same HW module as the call TX source device
515 // FIXME: would be better to refine to only inputs whose profile connects to the
516 // call TX device but this information is not in the audio patch and logic here must be
517 // symmetric to the one in startInput()
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800518 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800519 if (activeDesc->hasSameHwModuleAs(txSourceDeviceDesc)) {
Eric Laurent8f42ea12018-08-08 09:08:25 -0700520 closeActiveClients(activeDesc);
Eric Laurentc0a889f2015-10-14 14:36:34 -0700521 }
522 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700523 }
Eric Laurentdc462862016-07-19 12:29:53 -0700524
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800525 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Mikhail Naganovdc769682018-05-04 15:34:08 -0700526 status_t status = mpClientInterface->createAudioPatch(
527 patchBuilder.patch(), &afPatchHandle, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800528 ALOGW_IF(status != NO_ERROR,
529 "%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
530 sp<AudioPatch> audioPatch;
531 if (status == NO_ERROR) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700532 audioPatch = new AudioPatch(patchBuilder.patch(), mUidCached);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800533 audioPatch->mAfPatchHandle = afPatchHandle;
534 audioPatch->mUid = mUidCached;
535 }
536 return audioPatch;
537}
538
Mikhail Naganovdc769682018-05-04 15:34:08 -0700539sp<DeviceDescriptor> AudioPolicyManager::findDevice(
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100540 const DeviceVector& devices, audio_devices_t device) const {
Mikhail Naganov708e0382018-05-30 09:53:04 -0700541 DeviceVector deviceList = devices.getDevicesFromTypeMask(device);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800542 ALOG_ASSERT(!deviceList.isEmpty(),
543 "%s() selected device type %#x is not in devices list", __func__, device);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700544 return deviceList.itemAt(0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700545}
546
Eric Laurente0720872014-03-11 09:30:41 -0700547void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700548{
549 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100550 // store previous phone state for management of sonification strategy below
551 int oldState = mEngine->getPhoneState();
552
553 if (mEngine->setPhoneState(state) != NO_ERROR) {
554 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700555 return;
556 }
François Gaffie2110e042015-03-24 08:41:51 +0100557 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700558 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700559 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700560 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800561 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700562 }
563
François Gaffie2110e042015-03-24 08:41:51 +0100564 /**
565 * Switching to or from incall state or switching between telephony and VoIP lead to force
566 * routing command.
567 */
568 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
569 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700570
571 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700572 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700573
Eric Laurente552edb2014-03-10 17:42:56 -0700574 int delayMs = 0;
575 if (isStateInCall(state)) {
576 nsecs_t sysTime = systemTime();
577 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700578 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700579 // mute media and sonification strategies and delay device switch by the largest
580 // latency of any output where either strategy is active.
581 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100582 if ((isStrategyActive(desc, STRATEGY_MEDIA,
583 SONIFICATION_HEADSET_MUSIC_DELAY,
584 sysTime) ||
585 isStrategyActive(desc, STRATEGY_SONIFICATION,
586 SONIFICATION_HEADSET_MUSIC_DELAY,
587 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700588 (delayMs < (int)desc->latency()*2)) {
589 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700590 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700591 setStrategyMute(STRATEGY_MEDIA, true, desc);
592 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700593 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700594 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
595 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700596 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
597 }
598 }
599
Eric Laurent87ffa392015-05-22 10:32:38 -0700600 if (hasPrimaryOutput()) {
601 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
602 // the device returned is not necessarily reachable via this output
603 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
604 // force routing command to audio hardware when ending call
605 // even if no device change is needed
606 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
607 rxDevice = mPrimaryOutput->device();
608 }
Eric Laurente552edb2014-03-10 17:42:56 -0700609
Eric Laurent87ffa392015-05-22 10:32:38 -0700610 if (state == AUDIO_MODE_IN_CALL) {
611 updateCallRouting(rxDevice, delayMs);
612 } else if (oldState == AUDIO_MODE_IN_CALL) {
613 if (mCallRxPatch != 0) {
614 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
615 mCallRxPatch.clear();
616 }
617 if (mCallTxPatch != 0) {
618 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
619 mCallTxPatch.clear();
620 }
621 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
622 } else {
623 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700624 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700625 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700626
627 // reevaluate routing on all outputs in case tracks have been started during the call
628 for (size_t i = 0; i < mOutputs.size(); i++) {
629 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
630 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
631 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
Yung Ti Suf60c8242018-05-10 18:07:26 +0800632 setOutputDevice(desc, newDevice, (newDevice != AUDIO_DEVICE_NONE), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700633 }
634 }
635
Eric Laurente552edb2014-03-10 17:42:56 -0700636 if (isStateInCall(state)) {
637 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700638 // force reevaluating accessibility routing when call starts
639 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700640 }
641
642 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700643 if (state == AUDIO_MODE_RINGTONE &&
644 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700645 mLimitRingtoneVolume = true;
646 } else {
647 mLimitRingtoneVolume = false;
648 }
649}
650
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700651audio_mode_t AudioPolicyManager::getPhoneState() {
652 return mEngine->getPhoneState();
653}
654
Eric Laurente0720872014-03-11 09:30:41 -0700655void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700656 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700657{
François Gaffie2110e042015-03-24 08:41:51 +0100658 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700659 if (config == mEngine->getForceUse(usage)) {
660 return;
661 }
Eric Laurente552edb2014-03-10 17:42:56 -0700662
François Gaffie2110e042015-03-24 08:41:51 +0100663 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
664 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
665 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700666 }
François Gaffie2110e042015-03-24 08:41:51 +0100667 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
668 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
669 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700670
671 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700672 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800673
Eric Laurentdc462862016-07-19 12:29:53 -0700674 //FIXME: workaround for truncated touch sounds
675 // to be removed when the problem is handled by system UI
676 uint32_t delayMs = 0;
677 uint32_t waitMs = 0;
678 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
679 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
680 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700681 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700682 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
Eric Laurentdc462862016-07-19 12:29:53 -0700683 waitMs = updateCallRouting(newDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700684 }
Eric Laurente552edb2014-03-10 17:42:56 -0700685 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700686 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
687 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
688 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700689 waitMs = setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE),
690 delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700691 }
Eric Laurente552edb2014-03-10 17:42:56 -0700692 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700693 applyStreamVolumes(outputDesc, newDevice, waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700694 }
695 }
696
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800697 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800698 audio_devices_t newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700699 // Force new input selection if the new device can not be reached via current input
Eric Laurentfb66dd92016-01-28 18:32:03 -0800700 if (activeDesc->mProfile->getSupportedDevices().types() &
701 (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
702 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700703 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800704 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700705 }
Eric Laurente552edb2014-03-10 17:42:56 -0700706 }
Eric Laurente552edb2014-03-10 17:42:56 -0700707}
708
Eric Laurente0720872014-03-11 09:30:41 -0700709void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700710{
711 ALOGV("setSystemProperty() property %s, value %s", property, value);
712}
713
714// Find a direct output profile compatible with the parameters passed, even if the input flags do
715// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800716sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700717 audio_devices_t device,
718 uint32_t samplingRate,
719 audio_format_t format,
720 audio_channel_mask_t channelMask,
721 audio_output_flags_t flags)
722{
Eric Laurent861a6282015-05-18 15:40:16 -0700723 // only retain flags that will drive the direct output profile selection
724 // if explicitly requested
725 static const uint32_t kRelevantFlags =
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700726 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
727 AUDIO_OUTPUT_FLAG_VOIP_RX);
Eric Laurent861a6282015-05-18 15:40:16 -0700728 flags =
729 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
730
731 sp<IOProfile> profile;
732
Mikhail Naganovd4120142017-12-06 15:49:22 -0800733 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800734 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent861a6282015-05-18 15:40:16 -0700735 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700736 samplingRate, NULL /*updatedSamplingRate*/,
737 format, NULL /*updatedFormat*/,
738 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700739 flags)) {
740 continue;
741 }
742 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100743 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700744 continue;
745 }
746 // if several profiles are compatible, give priority to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100747 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700748 continue;
749 }
750 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100751 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700752 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700753 }
Eric Laurente552edb2014-03-10 17:42:56 -0700754 }
755 }
Eric Laurent861a6282015-05-18 15:40:16 -0700756 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700757}
758
Eric Laurentf4e63452017-11-06 19:31:46 +0000759audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700760{
Eric Laurent3b73df72014-03-11 09:06:29 -0700761 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700762 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800763
764 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
765 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
766 // format, flags, etc. This may result in some discrepancy for functions that utilize
767 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
768 // and AudioSystem::getOutputSamplingRate().
769
Eric Laurentf4e63452017-11-06 19:31:46 +0000770 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
771 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
Eric Laurente552edb2014-03-10 17:42:56 -0700772
Eric Laurentf4e63452017-11-06 19:31:46 +0000773 ALOGV("getOutput() stream %d selected device %08x, output %d", stream, device, output);
774 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700775}
776
Eric Laurente83b55d2014-11-14 10:06:21 -0800777status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
778 audio_io_handle_t *output,
779 audio_session_t session,
780 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700781 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800782 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200783 audio_output_flags_t *flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700784 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800785 audio_port_handle_t *portId)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700786{
Eric Laurente83b55d2014-11-14 10:06:21 -0800787 audio_attributes_t attributes;
Eric Laurent8fc147b2018-07-22 19:13:55 -0700788 DeviceVector outputDevices;
789 routing_strategy strategy;
790 audio_devices_t device;
Eric Laurent97ac8712018-07-27 18:59:02 -0700791 const audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100792 audio_devices_t msdDevice = getMsdAudioOutDeviceTypes();
Eric Laurent8fc147b2018-07-22 19:13:55 -0700793
Eric Laurent8f42ea12018-08-08 09:08:25 -0700794 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
795 if (*portId != AUDIO_PORT_HANDLE_NONE) {
796 return INVALID_OPERATION;
797 }
798
Eric Laurente83b55d2014-11-14 10:06:21 -0800799 if (attr != NULL) {
800 if (!isValidAttributes(attr)) {
801 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
802 attr->usage, attr->content_type, attr->flags,
803 attr->tags);
804 return BAD_VALUE;
805 }
806 attributes = *attr;
807 } else {
808 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
809 ALOGE("getOutputForAttr(): invalid stream type");
810 return BAD_VALUE;
811 }
812 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700813 }
Eric Laurent20b9ef02016-12-05 11:03:16 -0800814
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700815 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
Eric Laurent97ac8712018-07-27 18:59:02 -0700816 " session %d selectedDeviceId %d",
817 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
818 session, requestedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700819
Eric Laurent97ac8712018-07-27 18:59:02 -0700820 *stream = streamTypefromAttributesInt(&attributes);
821
822 strategy = getStrategyForAttr(&attributes);
823
Scott Randolph7b1fd232018-06-18 15:33:03 -0700824 // First check for explicit routing (eg. setPreferredDevice)
Eric Laurent97ac8712018-07-27 18:59:02 -0700825 if (requestedDeviceId != AUDIO_PORT_HANDLE_NONE) {
826 sp<DeviceDescriptor> deviceDesc =
827 mAvailableOutputDevices.getDeviceFromId(requestedDeviceId);
828 device = deviceDesc->type();
Scott Randolph7b1fd232018-06-18 15:33:03 -0700829 } else {
830 // If no explict route, is there a matching dynamic policy that applies?
831 sp<SwAudioOutputDescriptor> desc;
832 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
833 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
834 if (!audio_has_proportional_frames(config->format)) {
835 return BAD_VALUE;
836 }
837 *stream = streamTypefromAttributesInt(&attributes);
838 *output = desc->mIoHandle;
Eric Laurent97ac8712018-07-27 18:59:02 -0700839 AudioMix *mix = desc->mPolicyMix;
840 sp<DeviceDescriptor> deviceDesc =
841 mAvailableOutputDevices.getDevice(mix->mDeviceType, mix->mDeviceAddress);
842 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Scott Randolph7b1fd232018-06-18 15:33:03 -0700843 ALOGV("getOutputForAttr() returns output %d", *output);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700844 goto exit;
Scott Randolph7b1fd232018-06-18 15:33:03 -0700845 }
846
847 // Virtual sources must always be dynamicaly or explicitly routed
848 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
849 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
850 return BAD_VALUE;
851 }
Eric Laurent97ac8712018-07-27 18:59:02 -0700852 device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700853 }
Scott Randolph7b1fd232018-06-18 15:33:03 -0700854
Eric Laurente83b55d2014-11-14 10:06:21 -0800855 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200856 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -0700857 }
858
Nadav Barb2f18162018-07-18 13:01:53 +0300859 // Set incall music only if device was explicitly set, and fallback to the device which is
860 // chosen by the engine if not.
861 // FIXME: provide a more generic approach which is not device specific and move this back
862 // to getOutputForDevice.
863 if (device == AUDIO_DEVICE_OUT_TELEPHONY_TX &&
864 *stream == AUDIO_STREAM_MUSIC &&
865 audio_is_linear_pcm(config->format) &&
866 isInCall()) {
Eric Laurent97ac8712018-07-27 18:59:02 -0700867 if (requestedDeviceId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +0300868 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
869 } else {
Eric Laurent97ac8712018-07-27 18:59:02 -0700870 // Get the devce type directly from the engine to bypass preferred route logic
Nadav Barb2f18162018-07-18 13:01:53 +0300871 device = mEngine->getDeviceForStrategy(strategy);
872 }
873 }
874
Glenn Kasten49f36ba2017-12-06 13:02:02 -0800875 ALOGV("getOutputForAttr() device 0x%x, sampling rate %d, format %#x, channel mask %#x, "
876 "flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +0200877 device, config->sample_rate, config->format, config->channel_mask, *flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700878
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100879 *output = AUDIO_IO_HANDLE_NONE;
880 if (msdDevice != AUDIO_DEVICE_NONE) {
881 *output = getOutputForDevice(msdDevice, session, *stream, config, flags);
882 if (*output != AUDIO_IO_HANDLE_NONE && setMsdPatch(device) == NO_ERROR) {
883 ALOGV("%s() Using MSD device 0x%x instead of device 0x%x",
884 __func__, msdDevice, device);
885 device = msdDevice;
886 } else {
887 *output = AUDIO_IO_HANDLE_NONE;
888 }
889 }
890 if (*output == AUDIO_IO_HANDLE_NONE) {
891 *output = getOutputForDevice(device, session, *stream, config, flags);
892 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800893 if (*output == AUDIO_IO_HANDLE_NONE) {
894 return INVALID_OPERATION;
895 }
Paul McLeanaa981192015-03-21 09:55:15 -0700896
Eric Laurent8fc147b2018-07-22 19:13:55 -0700897 outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -0700898 *selectedDeviceId = outputDevices.size() > 0 ? outputDevices.itemAt(0)->getId()
899 : AUDIO_PORT_HANDLE_NONE;
900
Eric Laurent8fc147b2018-07-22 19:13:55 -0700901exit:
902 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
903 .format = config->format,
904 .channel_mask = config->channel_mask };
Eric Laurent8f42ea12018-08-08 09:08:25 -0700905 *portId = AudioPort::getNextUniqueId();
906
Eric Laurent8fc147b2018-07-22 19:13:55 -0700907 sp<TrackClientDescriptor> clientDesc =
Eric Laurent97ac8712018-07-27 18:59:02 -0700908 new TrackClientDescriptor(*portId, uid, session, attributes, clientConfig,
909 requestedDeviceId, *stream,
910 getStrategyForAttr(&attributes),
911 *flags);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700912 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent97ac8712018-07-27 18:59:02 -0700913 outputDesc->clientsMap().emplace(*portId, clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700914
915 ALOGV(" getOutputForAttr() returns output %d selectedDeviceId %d for port ID %d",
916 *output, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -0700917
Eric Laurente83b55d2014-11-14 10:06:21 -0800918 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700919}
920
921audio_io_handle_t AudioPolicyManager::getOutputForDevice(
922 audio_devices_t device,
Kevin Rocard169753c2017-03-06 14:18:23 -0800923 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700924 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -0800925 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200926 audio_output_flags_t *flags)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700927{
Andy Hungc88b0642018-04-27 15:42:35 -0700928 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700929 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700930
Eric Laurente552edb2014-03-10 17:42:56 -0700931 // open a direct output if required by specified parameters
932 //force direct flag if offload flag is set: offloading implies a direct output stream
933 // and all common behaviors are driven by checking only the direct flag
934 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +0200935 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
936 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700937 }
Nadav Bar766fb022018-01-07 12:18:03 +0200938 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
939 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -0700940 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800941 // only allow deep buffering for music stream type
942 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +0200943 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700944 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +0200945 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700946 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
947 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +0200948 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800949 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700950 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +0200951 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700952 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Eric Laurentfe231122017-11-17 17:48:06 -0800953 audio_is_linear_pcm(config->format)) {
Nadav Bar766fb022018-01-07 12:18:03 +0200954 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700955 AUDIO_OUTPUT_FLAG_DIRECT);
956 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700957 }
Eric Laurente552edb2014-03-10 17:42:56 -0700958
Nadav Bar766fb022018-01-07 12:18:03 +0200959
Eric Laurentb732cf52014-09-24 19:08:21 -0700960 sp<IOProfile> profile;
961
962 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700963 // and not explicitly requested
Nadav Bar766fb022018-01-07 12:18:03 +0200964 if (((*flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Eric Laurentfe231122017-11-17 17:48:06 -0800965 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
966 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
Eric Laurentb732cf52014-09-24 19:08:21 -0700967 goto non_direct_output;
968 }
969
Andy Hung2ddee192015-12-18 17:34:44 -0800970 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
971 // This prevents creating an offloaded track and tearing it down immediately after start
972 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700973 // FIXME: We should check the audio session here but we do not have it in this context.
974 // This may prevent offloading in rare situations where effects are left active by apps
975 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700976
Nadav Bar766fb022018-01-07 12:18:03 +0200977 if (((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800978 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700979 profile = getProfileForDirectOutput(device,
Eric Laurentfe231122017-11-17 17:48:06 -0800980 config->sample_rate,
981 config->format,
982 config->channel_mask,
Nadav Bar766fb022018-01-07 12:18:03 +0200983 (audio_output_flags_t)*flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700984 }
985
Eric Laurent1c333e22014-05-20 10:48:17 -0700986 if (profile != 0) {
Andy Hungc88b0642018-04-27 15:42:35 -0700987 // exclusive outputs for MMAP and Offload are enforced by different session ids.
988 for (size_t i = 0; i < mOutputs.size(); i++) {
989 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
990 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
991 // reuse direct output if currently open by the same client
992 // and configured with same parameters
993 if ((config->sample_rate == desc->mSamplingRate) &&
Andy Hung5659ed52018-04-30 10:31:26 -0700994 (config->format == desc->mFormat) &&
Andy Hungc88b0642018-04-27 15:42:35 -0700995 (config->channel_mask == desc->mChannelMask) &&
996 (session == desc->mDirectClientSession)) {
997 desc->mDirectOpenCount++;
998 ALOGI("getOutputForDevice() reusing direct output %d for session %d",
999 mOutputs.keyAt(i), session);
1000 return mOutputs.keyAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001001 }
1002 }
1003 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08001004
1005 if (!profile->canOpenNewIo()) {
1006 goto non_direct_output;
Eric Laurente552edb2014-03-10 17:42:56 -07001007 }
Eric Laurent861a6282015-05-18 15:40:16 -07001008
Eric Laurent3974e3b2017-12-07 17:58:43 -08001009 sp<SwAudioOutputDescriptor> outputDesc =
1010 new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurent53b810e2017-12-10 17:25:10 -08001011
Mikhail Naganov708e0382018-05-30 09:53:04 -07001012 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -08001013 String8 address = outputDevices.size() > 0 ? outputDevices.itemAt(0)->mAddress
1014 : String8("");
1015
Nadav Bar766fb022018-01-07 12:18:03 +02001016 status = outputDesc->open(config, device, address, stream, *flags, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07001017
1018 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001019 if (status != NO_ERROR ||
Eric Laurentfe231122017-11-17 17:48:06 -08001020 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
Andy Hung5659ed52018-04-30 10:31:26 -07001021 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->mFormat) ||
Eric Laurentfe231122017-11-17 17:48:06 -08001022 (config->channel_mask != 0 && config->channel_mask != outputDesc->mChannelMask)) {
1023 ALOGV("getOutputForDevice() failed opening direct output: output %d sample rate %d %d,"
1024 "format %d %d, channel mask %04x %04x", output, config->sample_rate,
1025 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
1026 config->channel_mask, outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001027 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001028 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07001029 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001030 // fall back to mixer output if possible when the direct output could not be open
Eric Laurentfe231122017-11-17 17:48:06 -08001031 if (audio_is_linear_pcm(config->format) &&
1032 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -08001033 goto non_direct_output;
1034 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001035 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001036 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001037 outputDesc->mRefCount[stream] = 0;
1038 outputDesc->mStopTime[stream] = 0;
1039 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -08001040 outputDesc->mDirectClientSession = session;
1041
Eric Laurente552edb2014-03-10 17:42:56 -07001042 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001043 mPreviousOutputs = mOutputs;
Eric Laurentf4e63452017-11-06 19:31:46 +00001044 ALOGV("getOutputForDevice() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001045 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001046 return output;
1047 }
1048
Eric Laurentb732cf52014-09-24 19:08:21 -07001049non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001050
1051 // A request for HW A/V sync cannot fallback to a mixed output because time
1052 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001053 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001054 return AUDIO_IO_HANDLE_NONE;
1055 }
1056
Eric Laurente552edb2014-03-10 17:42:56 -07001057 // ignoring channel mask due to downmix capability in mixer
1058
1059 // open a non direct output
1060
1061 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001062 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001063 // get which output is suitable for the specified stream. The actual
1064 // routing change will happen when startOutput() will be called
1065 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1066
Eric Laurent8838a382014-09-08 16:44:28 -07001067 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001068 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1069 output = selectOutput(outputs, *flags, config->format);
Eric Laurente552edb2014-03-10 17:42:56 -07001070 }
Eric Laurentf4e63452017-11-06 19:31:46 +00001071 ALOGW_IF((output == 0), "getOutputForDevice() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001072 "sampling rate %d, format %#x, channels %#x, flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +02001073 stream, config->sample_rate, config->format, config->channel_mask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001074
Eric Laurente552edb2014-03-10 17:42:56 -07001075 return output;
1076}
1077
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001078sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
1079 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1080 if (msdModule != 0) {
1081 DeviceVector msdInputDevices = mAvailableInputDevices.getDevicesFromHwModule(
1082 msdModule->getHandle());
1083 if (!msdInputDevices.isEmpty()) return msdInputDevices.itemAt(0);
1084 }
1085 return 0;
1086}
1087
1088audio_devices_t AudioPolicyManager::getMsdAudioOutDeviceTypes() const {
1089 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1090 if (msdModule != 0) {
1091 return mAvailableOutputDevices.getDeviceTypesFromHwModule(msdModule->getHandle());
1092 }
1093 return AUDIO_DEVICE_NONE;
1094}
1095
1096const AudioPatchCollection AudioPolicyManager::getMsdPatches() const {
1097 AudioPatchCollection msdPatches;
1098 audio_module_handle_t msdModuleHandle = mHwModules.getModuleFromName(
1099 AUDIO_HARDWARE_MODULE_ID_MSD)->getHandle();
1100 if (msdModuleHandle == AUDIO_MODULE_HANDLE_NONE) return msdPatches;
1101 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1102 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1103 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1104 const struct audio_port_config *source = &patch->mPatch.sources[j];
1105 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1106 source->ext.device.hw_module == msdModuleHandle) {
1107 msdPatches.addAudioPatch(patch->mHandle, patch);
1108 }
1109 }
1110 }
1111 return msdPatches;
1112}
1113
1114status_t AudioPolicyManager::getBestMsdAudioProfileFor(audio_devices_t outputDevice,
1115 bool hwAvSync, audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1116{
1117 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1118 if (msdModule == nullptr) {
1119 ALOGE("%s() unable to get MSD module", __func__);
1120 return NO_INIT;
1121 }
1122 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(outputDevice);
1123 if (deviceModule == nullptr) {
1124 ALOGE("%s() unable to get module for %#x", __func__, outputDevice);
1125 return NO_INIT;
1126 }
1127 const InputProfileCollection &inputProfiles = msdModule->getInputProfiles();
1128 if (inputProfiles.isEmpty()) {
1129 ALOGE("%s() no input profiles for MSD module", __func__);
1130 return NO_INIT;
1131 }
1132 const OutputProfileCollection &outputProfiles = deviceModule->getOutputProfiles();
1133 if (outputProfiles.isEmpty()) {
1134 ALOGE("%s() no output profiles for device %#x", __func__, outputDevice);
1135 return NO_INIT;
1136 }
1137 AudioProfileVector msdProfiles;
1138 // Each IOProfile represents a MixPort from audio_policy_configuration.xml
1139 for (const auto &inProfile : inputProfiles) {
1140 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0)) {
1141 msdProfiles.appendVector(inProfile->getAudioProfiles());
1142 }
1143 }
1144 AudioProfileVector deviceProfiles;
1145 for (const auto &outProfile : outputProfiles) {
1146 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0)) {
1147 deviceProfiles.appendVector(outProfile->getAudioProfiles());
1148 }
1149 }
1150 struct audio_config_base bestSinkConfig;
1151 status_t result = msdProfiles.findBestMatchingOutputConfig(deviceProfiles,
1152 compressedFormatsOrder, surroundChannelMasksOrder, true /*preferHigherSamplingRates*/,
1153 &bestSinkConfig);
1154 if (result != NO_ERROR) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001155 ALOGD("%s() no matching profiles found for device: %#x, hwAvSync: %d",
1156 __func__, outputDevice, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001157 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001158 }
1159 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1160 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1161 sinkConfig->format = bestSinkConfig.format;
1162 // For encoded streams force direct flag to prevent downstream mixing.
1163 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1164 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
1165 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1166 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1167 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1168 sourceConfig->format = bestSinkConfig.format;
1169 // Copy input stream directly without any processing (e.g. resampling).
1170 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1171 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1172 if (hwAvSync) {
1173 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1174 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1175 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1176 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1177 }
1178 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1179 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1180 sinkConfig->config_mask |= config_mask;
1181 sourceConfig->config_mask |= config_mask;
1182 return NO_ERROR;
1183}
1184
1185PatchBuilder AudioPolicyManager::buildMsdPatch(audio_devices_t outputDevice) const
1186{
1187 PatchBuilder patchBuilder;
1188 patchBuilder.addSource(getMsdAudioInDevice()).
1189 addSink(findDevice(mAvailableOutputDevices, outputDevice));
1190 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1191 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
1192 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1193 // For now, we just forcefully try with HwAvSync first.
1194 status_t res = getBestMsdAudioProfileFor(outputDevice, true /*hwAvSync*/,
1195 &sourceConfig, &sinkConfig) == NO_ERROR ? NO_ERROR :
1196 getBestMsdAudioProfileFor(
1197 outputDevice, false /*hwAvSync*/, &sourceConfig, &sinkConfig);
1198 if (res == NO_ERROR) {
1199 // Found a matching profile for encoded audio. Re-create PatchBuilder with this config.
1200 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1201 }
1202 ALOGV("%s() no matching profile found. Fall through to default PCM patch"
1203 " supporting PCM format conversion.", __func__);
1204 return patchBuilder;
1205}
1206
1207status_t AudioPolicyManager::setMsdPatch(audio_devices_t outputDevice) {
1208 ALOGV("%s() for outputDevice %#x", __func__, outputDevice);
1209 if (outputDevice == AUDIO_DEVICE_NONE) {
1210 // Use media strategy for unspecified output device. This should only
1211 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1212 // therefore invalidate explicit routing requests.
1213 outputDevice = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
1214 }
1215 PatchBuilder patchBuilder = buildMsdPatch(outputDevice);
1216 const struct audio_patch* patch = patchBuilder.patch();
1217 const AudioPatchCollection msdPatches = getMsdPatches();
1218 if (!msdPatches.isEmpty()) {
1219 LOG_ALWAYS_FATAL_IF(msdPatches.size() > 1,
1220 "The current MSD prototype only supports one output patch");
1221 sp<AudioPatch> currentPatch = msdPatches.valueAt(0);
1222 if (audio_patches_are_equal(&currentPatch->mPatch, patch)) {
1223 return NO_ERROR;
1224 }
1225 releaseAudioPatch(currentPatch->mHandle, mUidCached);
1226 }
1227 status_t status = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1228 patch, 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1229 ALOGE_IF(status != NO_ERROR, "%s() error %d creating MSD audio patch", __func__, status);
1230 ALOGI_IF(status == NO_ERROR, "%s() Patch created from MSD_IN to "
1231 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__, outputDevice,
1232 patch->sources[0].format, patch->sources[0].channel_mask, patch->sources[0].sample_rate);
1233 return status;
1234}
1235
Eric Laurente0720872014-03-11 09:30:41 -07001236audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001237 audio_output_flags_t flags,
1238 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001239{
1240 // select one output among several that provide a path to a particular device or set of
1241 // devices (the list was previously build by getOutputsForDevice()).
1242 // The priority is as follows:
1243 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001244 // 2: the output with the bit depth the closest to the requested one
1245 // 3: the primary output
1246 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001247
1248 if (outputs.size() == 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001249 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001250 }
1251 if (outputs.size() == 1) {
1252 return outputs[0];
1253 }
1254
1255 int maxCommonFlags = 0;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001256 audio_io_handle_t outputForFlags = AUDIO_IO_HANDLE_NONE;
1257 audio_io_handle_t outputForPrimary = AUDIO_IO_HANDLE_NONE;
1258 audio_io_handle_t outputForFormat = AUDIO_IO_HANDLE_NONE;
Eric Laurente6930022016-02-11 10:20:40 -08001259 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1260 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001261
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001262 for (audio_io_handle_t output : outputs) {
1263 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001264 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001265 // if a valid format is specified, skip output if not compatible
1266 if (format != AUDIO_FORMAT_INVALID) {
1267 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Andy Hung5659ed52018-04-30 10:31:26 -07001268 if (format != outputDesc->mFormat) {
Eric Laurent8838a382014-09-08 16:44:28 -07001269 continue;
1270 }
1271 } else if (!audio_is_linear_pcm(format)) {
1272 continue;
1273 }
Eric Laurente6930022016-02-11 10:20:40 -08001274 if (AudioPort::isBetterFormatMatch(
1275 outputDesc->mFormat, bestFormat, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001276 outputForFormat = output;
Eric Laurente6930022016-02-11 10:20:40 -08001277 bestFormat = outputDesc->mFormat;
1278 }
Eric Laurent8838a382014-09-08 16:44:28 -07001279 }
1280
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001281 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001282 if (commonFlags >= maxCommonFlags) {
1283 if (commonFlags == maxCommonFlags) {
Andy Hungc9901522017-11-10 20:07:54 -08001284 if (format != AUDIO_FORMAT_INVALID
1285 && AudioPort::isBetterFormatMatch(
1286 outputDesc->mFormat, bestFormatForFlags, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001287 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001288 bestFormatForFlags = outputDesc->mFormat;
1289 }
1290 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001291 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001292 maxCommonFlags = commonFlags;
1293 bestFormatForFlags = outputDesc->mFormat;
1294 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001295 ALOGV("selectOutput() commonFlags for output %d, %04x", output, commonFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001296 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001297 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001298 outputForPrimary = output;
Eric Laurente552edb2014-03-10 17:42:56 -07001299 }
1300 }
1301 }
1302
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001303 if (outputForFlags != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001304 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001305 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001306 if (outputForFormat != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001307 return outputForFormat;
1308 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001309 if (outputForPrimary != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001310 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001311 }
1312
1313 return outputs[0];
1314}
1315
Eric Laurent8fc147b2018-07-22 19:13:55 -07001316status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001317{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001318 ALOGV("%s portId %d", __FUNCTION__, portId);
1319
1320 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1321 if (outputDesc == 0) {
1322 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001323 return BAD_VALUE;
1324 }
Eric Laurent97ac8712018-07-27 18:59:02 -07001325 sp<TrackClientDescriptor> client = outputDesc->clientsMap()[portId];
Eric Laurente552edb2014-03-10 17:42:56 -07001326
Eric Laurent8fc147b2018-07-22 19:13:55 -07001327 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001328 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001329
Eric Laurent733ce942017-12-07 12:18:25 -08001330 status_t status = outputDesc->start();
1331 if (status != NO_ERROR) {
1332 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001333 }
1334
Eric Laurent97ac8712018-07-27 18:59:02 -07001335 uint32_t delayMs;
1336 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001337
1338 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001339 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001340 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001341 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001342 if (delayMs != 0) {
1343 usleep(delayMs * 1000);
1344 }
1345
1346 return status;
1347}
1348
Eric Laurent97ac8712018-07-27 18:59:02 -07001349status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1350 const sp<TrackClientDescriptor>& client,
1351 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001352{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001353 // cannot start playback of STREAM_TTS if any other output is being used
1354 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001355
1356 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001357 audio_stream_type_t stream = client->stream();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001358 if (stream == AUDIO_STREAM_TTS) {
1359 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001360 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001361 return INVALID_OPERATION;
1362 } else {
1363 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1364 }
1365 } else {
1366 // some playback other than beacon starts
1367 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1368 }
1369
Eric Laurent77305a62016-07-25 16:39:22 -07001370 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001371 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001372 bool force = !outputDesc->isActive() &&
1373 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001374
Eric Laurent97ac8712018-07-27 18:59:02 -07001375 audio_devices_t device = AUDIO_DEVICE_NONE;
1376 AudioMix *policyMix = NULL;
1377 const char *address = NULL;
1378 if (outputDesc->mPolicyMix != NULL) {
1379 policyMix = outputDesc->mPolicyMix;
1380 address = policyMix->mDeviceAddress.string();
1381 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1382 device = policyMix->mDeviceType;
1383 } else {
1384 device = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1385 }
1386 }
1387
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001388 // requiresMuteCheck is false when we can bypass mute strategy.
1389 // It covers a common case when there is no materially active audio
1390 // and muting would result in unnecessary delay and dropped audio.
1391 const uint32_t outputLatencyMs = outputDesc->latency();
1392 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1393
Eric Laurente552edb2014-03-10 17:42:56 -07001394 // increment usage count for this stream on the requested output:
1395 // NOTE that the usage count is the same for duplicated output and hardware output which is
1396 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1397 outputDesc->changeRefCount(stream, 1);
Eric Laurent97ac8712018-07-27 18:59:02 -07001398 client->setActive(true);
1399
1400 if (client->hasPreferredDevice(true)) {
1401 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
1402 if (device != outputDesc->device()) {
1403 checkStrategyRoute(getStrategy(stream), outputDesc->mIoHandle);
1404 }
1405 }
Eric Laurente552edb2014-03-10 17:42:56 -07001406
Eric Laurent36829f92017-04-07 19:04:42 -07001407 if (stream == AUDIO_STREAM_MUSIC) {
1408 selectOutputForMusicEffects();
1409 }
1410
Eric Laurent493404d2015-04-21 15:07:36 -07001411 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001412 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001413 if (device == AUDIO_DEVICE_NONE) {
1414 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001415 }
Eric Laurent36829f92017-04-07 19:04:42 -07001416
Eric Laurente552edb2014-03-10 17:42:56 -07001417 routing_strategy strategy = getStrategy(stream);
1418 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001419 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1420 (beaconMuteLatency > 0);
1421 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001422 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001423 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001424 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001425 // An output has a shared device if
1426 // - managed by the same hw module
1427 // - supports the currently selected device
1428 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
1429 && (desc->supportedDevices() & device) != AUDIO_DEVICE_NONE;
1430
Eric Laurent77305a62016-07-25 16:39:22 -07001431 // force a device change if any other output is:
1432 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001433 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001434 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001435 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001436 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001437 // change the device currently selected by the other output.
1438 if (sharedDevice &&
Eric Laurent77305a62016-07-25 16:39:22 -07001439 desc->device() != device &&
Eric Laurent77305a62016-07-25 16:39:22 -07001440 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001441 force = true;
1442 }
1443 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001444 // a notification so that audio focus effect can propagate, or that a mute/unmute
1445 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001446 const uint32_t latencyMs = desc->latency();
1447 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1448
1449 if (shouldWait && isActive && (waitMs < latencyMs)) {
1450 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001451 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001452
1453 // Require mute check if another output is on a shared device
1454 // and currently active to have proper drain and avoid pops.
1455 // Note restoring AudioTracks onto this output needs to invoke
1456 // a volume ramp if there is no mute.
1457 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001458 }
1459 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001460
1461 const uint32_t muteWaitMs =
1462 setOutputDevice(outputDesc, device, force, 0, NULL, address, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001463
Eric Laurente552edb2014-03-10 17:42:56 -07001464 // apply volume rules for current stream and device if necessary
1465 checkAndSetVolume(stream,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001466 mVolumeCurves->getVolumeIndex(stream, outputDesc->device()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001467 outputDesc,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001468 outputDesc->device());
Eric Laurente552edb2014-03-10 17:42:56 -07001469
1470 // update the outputs if starting an output with a stream that can affect notification
1471 // routing
1472 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001473
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001474 // force reevaluating accessibility routing when ringtone or alarm starts
1475 if (strategy == STRATEGY_SONIFICATION) {
1476 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1477 }
Eric Laurentdc462862016-07-19 12:29:53 -07001478
1479 if (waitMs > muteWaitMs) {
1480 *delayMs = waitMs - muteWaitMs;
1481 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001482
1483 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1484 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1485 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1486 // change occurs after the MixerThread starts and causes a stream volume
1487 // glitch.
1488 //
1489 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001490 }
Eric Laurentdc462862016-07-19 12:29:53 -07001491
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001492 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1493 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1494 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1495 }
1496
Eric Laurent97ac8712018-07-27 18:59:02 -07001497 // Automatically enable the remote submix input when output is started on a re routing mix
1498 // of type MIX_TYPE_RECORDERS
1499 if (audio_is_remote_submix_device(device) && policyMix != NULL &&
1500 policyMix->mMixType == MIX_TYPE_RECORDERS) {
1501 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1502 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1503 address,
1504 "remote-submix");
1505 }
1506
Eric Laurente552edb2014-03-10 17:42:56 -07001507 return NO_ERROR;
1508}
1509
Eric Laurent8fc147b2018-07-22 19:13:55 -07001510status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001511{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001512 ALOGV("%s portId %d", __FUNCTION__, portId);
1513
1514 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1515 if (outputDesc == 0) {
1516 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001517 return BAD_VALUE;
1518 }
Eric Laurent97ac8712018-07-27 18:59:02 -07001519 sp<TrackClientDescriptor> client = outputDesc->clientsMap()[portId];
Eric Laurente552edb2014-03-10 17:42:56 -07001520
Eric Laurent97ac8712018-07-27 18:59:02 -07001521 ALOGV("stopOutput() output %d, stream %d, session %d",
1522 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07001523
Eric Laurent97ac8712018-07-27 18:59:02 -07001524 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08001525
Eric Laurent733ce942017-12-07 12:18:25 -08001526 if (status == NO_ERROR ) {
1527 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001528 }
1529 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001530}
1531
Eric Laurent97ac8712018-07-27 18:59:02 -07001532status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1533 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07001534{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001535 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07001536 audio_stream_type_t stream = client->stream();
1537
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001538 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1539
Eric Laurente552edb2014-03-10 17:42:56 -07001540 if (outputDesc->mRefCount[stream] > 0) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001541 if (outputDesc->mRefCount[stream] == 1) {
1542 // Automatically disable the remote submix input when output is stopped on a
1543 // re routing mix of type MIX_TYPE_RECORDERS
1544 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1545 outputDesc->mPolicyMix != NULL &&
1546 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1547 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1548 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1549 outputDesc->mPolicyMix->mDeviceAddress,
1550 "remote-submix");
1551 }
1552 }
1553 bool forceDeviceUpdate = false;
1554 if (client->hasPreferredDevice(true)) {
1555 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1556 forceDeviceUpdate = true;
1557 }
1558
Eric Laurente552edb2014-03-10 17:42:56 -07001559 // decrement usage count of this stream on the output
1560 outputDesc->changeRefCount(stream, -1);
Eric Laurent97ac8712018-07-27 18:59:02 -07001561 client->setActive(false);
Paul McLeanaa981192015-03-21 09:55:15 -07001562
Eric Laurente552edb2014-03-10 17:42:56 -07001563 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001564 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001565 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001566 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001567 // delay the device switch by twice the latency because stopOutput() is executed when
1568 // the track stop() command is received and at that time the audio track buffer can
1569 // still contain data that needs to be drained. The latency only covers the audio HAL
1570 // and kernel buffers. Also the latency does not always include additional delay in the
1571 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001572 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001573
1574 // force restoring the device selection on other active outputs if it differs from the
1575 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001576 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001577 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001578 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001579 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001580 desc->isActive() &&
1581 outputDesc->sharesHwModuleWith(desc) &&
1582 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001583 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1584 bool force = desc->device() != newDevice2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001585
Eric Laurentc75307b2015-03-17 15:29:32 -07001586 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001587 newDevice2,
1588 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001589 delayMs);
1590 // re-apply device specific volume if not done by setOutputDevice()
1591 if (!force) {
1592 applyStreamVolumes(desc, newDevice2, delayMs);
1593 }
Eric Laurente552edb2014-03-10 17:42:56 -07001594 }
1595 }
1596 // update the outputs if stopping one with a stream that can affect notification routing
1597 handleNotificationRoutingForStream(stream);
1598 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001599
1600 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1601 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1602 setStrategyMute(STRATEGY_SONIFICATION, false, outputDesc);
1603 }
1604
Eric Laurent36829f92017-04-07 19:04:42 -07001605 if (stream == AUDIO_STREAM_MUSIC) {
1606 selectOutputForMusicEffects();
1607 }
Eric Laurente552edb2014-03-10 17:42:56 -07001608 return NO_ERROR;
1609 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001610 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001611 return INVALID_OPERATION;
1612 }
1613}
1614
Eric Laurent8fc147b2018-07-22 19:13:55 -07001615void AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001616{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001617 ALOGV("%s portId %d", __FUNCTION__, portId);
1618
1619 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1620 if (outputDesc == 0) {
1621 ALOGW("releaseOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001622 return;
1623 }
Eric Laurent97ac8712018-07-27 18:59:02 -07001624 sp<TrackClientDescriptor> client = outputDesc->clientsMap()[portId];
Eric Laurent8fc147b2018-07-22 19:13:55 -07001625
1626 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001627
Eric Laurent8fc147b2018-07-22 19:13:55 -07001628 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1629 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001630 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07001631 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001632 return;
1633 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001634 if (--outputDesc->mDirectOpenCount == 0) {
1635 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07001636 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001637 }
1638 }
Eric Laurent97ac8712018-07-27 18:59:02 -07001639 outputDesc->clientsMap().erase(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001640}
1641
1642
Eric Laurentcaf7f482014-11-25 17:50:47 -08001643status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1644 audio_io_handle_t *input,
1645 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001646 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001647 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001648 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001649 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001650 input_type_t *inputType,
1651 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001652{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001653 ALOGV("getInputForAttr() source %d, sampling rate %d, format %#x, channel mask %#x,"
Eric Laurentcaf7f482014-11-25 17:50:47 -08001654 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001655 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001656
Eric Laurentad2e7b92017-09-14 20:06:42 -07001657 status_t status = NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -08001658 // handle legacy remote submix case where the address was not always specified
1659 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001660 audio_source_t halInputSource;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001661 audio_source_t inputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001662 AudioMix *policyMix = NULL;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001663 DeviceVector inputDevices;
Eric Laurent8fc147b2018-07-22 19:13:55 -07001664 sp<AudioInputDescriptor> inputDesc;
1665 sp<RecordClientDescriptor> clientDesc;
1666 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001667 bool isSoundTrigger;
1668 audio_devices_t device;
1669
1670 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1671 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1672 return INVALID_OPERATION;
1673 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001674
Eric Laurentfe231122017-11-17 17:48:06 -08001675 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1676 inputSource = AUDIO_SOURCE_MIC;
1677 }
1678
Paul McLean466dc8e2015-04-17 13:15:36 -06001679 // Explicit routing?
1680 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -07001681 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
jiabinc0c831a2018-01-29 17:55:15 -08001682 deviceDesc = mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001683 }
Paul McLean466dc8e2015-04-17 13:15:36 -06001684
Eric Laurentad2e7b92017-09-14 20:06:42 -07001685 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1686 // possible
1687 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1688 *input != AUDIO_IO_HANDLE_NONE) {
1689 ssize_t index = mInputs.indexOfKey(*input);
1690 if (index < 0) {
1691 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1692 status = BAD_VALUE;
1693 goto error;
1694 }
1695 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001696 RecordClientVector clients = inputDesc->getClientsForSession(session);
1697 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001698 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1699 status = BAD_VALUE;
1700 goto error;
1701 }
1702 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1703 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001704 // corresponds to a new client and is only permitted from the same UID.
1705 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07001706 if (clients.size() > 1) {
1707 for (const auto& client : clients) {
1708 // The client map is ordered by key values (portId) and portIds are allocated
1709 // incrementaly. So the first client in this list is the one opened by audio flinger
1710 // when the mmap stream is created and should be ignored as it does not correspond
1711 // to an actual client
1712 if (client == *clients.cbegin()) {
1713 continue;
1714 }
1715 if (uid != client->uid() && !client->isSilenced()) {
1716 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
1717 uid, client->portId(), client->uid());
1718 status = INVALID_OPERATION;
1719 goto error;
1720 }
Eric Laurent331679c2018-04-16 17:03:16 -07001721 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001722 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001723 *inputType = API_INPUT_LEGACY;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001724 device = inputDesc->mDevice;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001725
Eric Laurent8f42ea12018-08-08 09:08:25 -07001726 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001727 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001728 }
1729
1730 *input = AUDIO_IO_HANDLE_NONE;
1731 *inputType = API_INPUT_INVALID;
1732
Eric Laurentad2e7b92017-09-14 20:06:42 -07001733 halInputSource = inputSource;
1734
Eric Laurentc447ded2015-01-06 08:47:05 -08001735 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001736 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001737 status = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
1738 if (status != NO_ERROR) {
1739 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001740 }
1741 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001742 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1743 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001744 } else {
Eric Laurent97ac8712018-07-27 18:59:02 -07001745 if (deviceDesc != 0) {
1746 device = deviceDesc->type();
1747 } else {
1748 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
1749 }
Eric Laurent275e8e92014-11-30 15:14:47 -08001750 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001751 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001752 status = BAD_VALUE;
1753 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001754 }
Eric Laurentc722f302014-12-10 11:21:49 -08001755 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001756 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001757 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1758 // there is an external policy, but this input is attached to a mix of recorders,
1759 // meaning it receives audio injected into the framework, so the recorder doesn't
1760 // know about it and is therefore considered "legacy"
1761 *inputType = API_INPUT_LEGACY;
1762 } else {
1763 // recording a mix of players defined by an external policy, we're rerouting for
1764 // an external policy
1765 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1766 }
Eric Laurentc722f302014-12-10 11:21:49 -08001767 } else if (audio_is_remote_submix_device(device)) {
1768 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001769 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001770 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1771 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001772 } else {
1773 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001774 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001775
Eric Laurent599c7582015-12-07 18:05:55 -08001776 }
1777
Eric Laurent8f42ea12018-08-08 09:08:25 -07001778 *input = getInputForDevice(device, address, session, inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001779 config, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001780 policyMix);
1781 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001782 status = INVALID_OPERATION;
1783 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001784 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001785
Eric Laurent8f42ea12018-08-08 09:08:25 -07001786exit:
1787
Mikhail Naganov708e0382018-05-30 09:53:04 -07001788 inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -07001789 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
Eric Laurent8f42ea12018-08-08 09:08:25 -07001790 : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07001791
Eric Laurent8f42ea12018-08-08 09:08:25 -07001792 isSoundTrigger = inputSource == AUDIO_SOURCE_HOTWORD &&
1793 mSoundTriggerSessions.indexOfKey(session) > 0;
1794 *portId = AudioPort::getNextUniqueId();
1795
Eric Laurent8fc147b2018-07-22 19:13:55 -07001796 clientDesc = new RecordClientDescriptor(*portId, uid, session,
Eric Laurent8f42ea12018-08-08 09:08:25 -07001797 *attr, *config, requestedDeviceId,
1798 inputSource,flags, isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001799 inputDesc = mInputs.valueFor(*input);
Eric Laurent97ac8712018-07-27 18:59:02 -07001800 inputDesc->clientsMap().emplace(*portId, clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001801
1802 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
1803 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001804
Eric Laurent599c7582015-12-07 18:05:55 -08001805 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001806
1807error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07001808 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001809}
1810
1811
1812audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1813 String8 address,
1814 audio_session_t session,
Eric Laurent599c7582015-12-07 18:05:55 -08001815 audio_source_t inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001816 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08001817 audio_input_flags_t flags,
1818 AudioMix *policyMix)
1819{
1820 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1821 audio_source_t halInputSource = inputSource;
1822 bool isSoundTrigger = false;
1823
1824 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1825 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1826 if (index >= 0) {
1827 input = mSoundTriggerSessions.valueFor(session);
1828 isSoundTrigger = true;
1829 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1830 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1831 } else {
1832 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001833 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001834 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08001835 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001836 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001837 }
1838
Andy Hungf129b032015-04-07 13:45:50 -07001839 // find a compatible input profile (not necessarily identical in parameters)
1840 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08001841 // sampling rate and flags may be updated by getInputProfile
1842 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
1843 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07001844 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08001845 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07001846 audio_input_flags_t profileFlags = flags;
1847 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07001848 profileFormat = config->format; // reset each time through loop, in case it is updated
Eric Laurent275e8e92014-11-30 15:14:47 -08001849 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001850 profileSamplingRate, profileFormat, profileChannelMask,
1851 profileFlags);
1852 if (profile != 0) {
1853 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001854 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1855 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001856 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1857 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1858 } else { // fail
Glenn Kastenfaa10a62017-05-25 15:52:05 -07001859 ALOGW("getInputForDevice() could not find profile for device 0x%X, "
Eric Laurentfe231122017-11-17 17:48:06 -08001860 "sampling rate %u, format %#x, channel mask 0x%X, flags %#x",
1861 device, config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001862 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001863 }
Eric Laurente552edb2014-03-10 17:42:56 -07001864 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001865 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08001866 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08001867 if (samplingRate == 0) {
1868 samplingRate = profileSamplingRate;
1869 }
Eric Laurente552edb2014-03-10 17:42:56 -07001870
Eric Laurent322b4d22015-04-03 15:57:54 -07001871 if (profile->getModuleHandle() == 0) {
1872 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001873 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001874 }
1875
Eric Laurent3974e3b2017-12-07 17:58:43 -08001876 if (!profile->canOpenNewIo()) {
1877 return AUDIO_IO_HANDLE_NONE;
1878 }
1879
Eric Laurentfe231122017-11-17 17:48:06 -08001880 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001881
Eric Laurentfe231122017-11-17 17:48:06 -08001882 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
1883 lConfig.sample_rate = profileSamplingRate;
1884 lConfig.channel_mask = profileChannelMask;
1885 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07001886
Eric Laurent53b810e2017-12-10 17:25:10 -08001887 if (address == "") {
Mikhail Naganov708e0382018-05-30 09:53:04 -07001888 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -08001889 // the inputs vector must be of size >= 1, but we don't want to crash here
1890 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress : String8("");
1891 }
1892
Eric Laurentfe231122017-11-17 17:48:06 -08001893 status_t status = inputDesc->open(&lConfig, device, address,
1894 halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001895
1896 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001897 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08001898 (profileSamplingRate != lConfig.sample_rate) ||
1899 !audio_formats_match(profileFormat, lConfig.format) ||
1900 (profileChannelMask != lConfig.channel_mask)) {
1901 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001902 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08001903 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001904 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001905 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07001906 }
Eric Laurent599c7582015-12-07 18:05:55 -08001907 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001908 }
1909
Eric Laurentc722f302014-12-10 11:21:49 -08001910 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001911
Eric Laurent599c7582015-12-07 18:05:55 -08001912 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001913 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001914
Eric Laurent599c7582015-12-07 18:05:55 -08001915 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001916}
1917
Eric Laurentbb948092017-01-23 18:33:30 -08001918//static
1919bool AudioPolicyManager::isConcurrentSource(audio_source_t source)
1920{
1921 return (source == AUDIO_SOURCE_HOTWORD) ||
1922 (source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
1923 (source == AUDIO_SOURCE_FM_TUNER);
1924}
1925
Chris Thornton2b864642017-06-27 21:26:07 -07001926// FIXME: remove when concurrent capture is ready. This is a hack to work around bug b/63083537.
1927bool AudioPolicyManager::soundTriggerSupportsConcurrentCapture() {
1928 if (!mHasComputedSoundTriggerSupportsConcurrentCapture) {
1929 bool soundTriggerSupportsConcurrentCapture = false;
1930 unsigned int numModules = 0;
1931 struct sound_trigger_module_descriptor* nModules = NULL;
1932
1933 status_t status = SoundTrigger::listModules(nModules, &numModules);
1934 if (status == NO_ERROR && numModules != 0) {
1935 nModules = (struct sound_trigger_module_descriptor*) calloc(
1936 numModules, sizeof(struct sound_trigger_module_descriptor));
1937 if (nModules == NULL) {
1938 // We failed to malloc the buffer, so just say no for now, and hope that we have more
1939 // ram the next time this function is called.
1940 ALOGE("Failed to allocate buffer for module descriptors");
1941 return false;
1942 }
1943
1944 status = SoundTrigger::listModules(nModules, &numModules);
1945 if (status == NO_ERROR) {
1946 soundTriggerSupportsConcurrentCapture = true;
1947 for (size_t i = 0; i < numModules; ++i) {
1948 soundTriggerSupportsConcurrentCapture &=
1949 nModules[i].properties.concurrent_capture;
1950 }
1951 }
1952 free(nModules);
1953 }
1954 mSoundTriggerSupportsConcurrentCapture = soundTriggerSupportsConcurrentCapture;
1955 mHasComputedSoundTriggerSupportsConcurrentCapture = true;
1956 }
1957 return mSoundTriggerSupportsConcurrentCapture;
1958}
1959
Eric Laurentfb66dd92016-01-28 18:32:03 -08001960
Eric Laurent8fc147b2018-07-22 19:13:55 -07001961status_t AudioPolicyManager::startInput(audio_port_handle_t portId,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001962 bool silenced,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001963 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07001964{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001965 *concurrency = API_INPUT_CONCURRENCY_NONE;
1966
1967 ALOGV("%s portId %d", __FUNCTION__, portId);
1968
1969 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
1970 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07001971 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001972 return BAD_VALUE;
1973 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001974 audio_io_handle_t input = inputDesc->mIoHandle;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001975 sp<RecordClientDescriptor> client = inputDesc->clientsMap()[portId];
1976 if (client->active()) {
1977 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
1978 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07001979 }
1980
Eric Laurent8f42ea12018-08-08 09:08:25 -07001981 audio_session_t session = client->session();
1982
1983 ALOGV("%s input:%d, session:%d, silenced:%d, concurrency:%d)",
1984 __FUNCTION__, input, session, silenced, *concurrency);
1985
Eric Laurent74708e72017-04-07 17:13:42 -07001986 if (!is_virtual_input_device(inputDesc->mDevice)) {
1987 if (mCallTxPatch != 0 &&
1988 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1989 ALOGW("startInput(%d) failed: call in progress", input);
Ray Essick84e84a52018-05-03 18:45:07 -07001990 *concurrency |= API_INPUT_CONCURRENCY_CALL;
Eric Laurent74708e72017-04-07 17:13:42 -07001991 return INVALID_OPERATION;
1992 }
1993
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001994 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07001995
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001996 // If a UID is idle and records silence and another not silenced recording starts
1997 // from another UID (idle or active) we stop the current idle UID recording in
1998 // favor of the new one - "There can be only one" TM
1999 if (!silenced) {
2000 for (const auto& activeDesc : activeInputs) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002001 if ((activeDesc->getAudioPort()->getFlags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002002 activeDesc->getId() == inputDesc->getId()) {
2003 continue;
2004 }
2005
Eric Laurent8f42ea12018-08-08 09:08:25 -07002006 RecordClientVector activeClients = activeDesc->clientsList(true /*activeOnly*/);
2007 for (const auto& activeClient : activeClients) {
2008 if (activeClient->isSilenced()) {
2009 closeClient(activeClient->portId());
2010 ALOGV("%s client %d stopping silenced client %d", __FUNCTION__,
2011 portId, activeClient->portId());
2012 activeInputs = mInputs.getActiveInputs();
2013 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002014 }
2015 }
2016 }
2017
2018 for (const auto& activeDesc : activeInputs) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002019 if ((client->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
Eric Laurentcb4dae22017-07-01 19:39:32 -07002020 activeDesc->getId() == inputDesc->getId()) {
2021 continue;
2022 }
2023
Eric Laurent74708e72017-04-07 17:13:42 -07002024 audio_source_t activeSource = activeDesc->inputSource(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002025 if (client->source() == AUDIO_SOURCE_HOTWORD) {
Eric Laurent74708e72017-04-07 17:13:42 -07002026 if (activeSource == AUDIO_SOURCE_HOTWORD) {
2027 if (activeDesc->hasPreemptedSession(session)) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002028 ALOGW("%s input %d failed for HOTWORD: "
2029 "other input %d already started for HOTWORD", __FUNCTION__,
Eric Laurent74708e72017-04-07 17:13:42 -07002030 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07002031 *concurrency |= API_INPUT_CONCURRENCY_HOTWORD;
Eric Laurent74708e72017-04-07 17:13:42 -07002032 return INVALID_OPERATION;
2033 }
2034 } else {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002035 ALOGV("%s input %d failed for HOTWORD: other input %d already started",
2036 __FUNCTION__, input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07002037 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07002038 return INVALID_OPERATION;
2039 }
2040 } else {
2041 if (activeSource != AUDIO_SOURCE_HOTWORD) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002042 ALOGW("%s input %d failed: other input %d already started", __FUNCTION__,
Eric Laurent74708e72017-04-07 17:13:42 -07002043 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07002044 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07002045 return INVALID_OPERATION;
2046 }
2047 }
2048 }
2049
Chris Thornton2b864642017-06-27 21:26:07 -07002050 // We only need to check if the sound trigger session supports concurrent capture if the
2051 // input is also a sound trigger input. Otherwise, we should preempt any hotword stream
2052 // that's running.
2053 const bool allowConcurrentWithSoundTrigger =
2054 inputDesc->isSoundTrigger() ? soundTriggerSupportsConcurrentCapture() : false;
2055
Eric Laurent74708e72017-04-07 17:13:42 -07002056 // if capture is allowed, preempt currently active HOTWORD captures
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002057 for (const auto& activeDesc : activeInputs) {
Chris Thornton2b864642017-06-27 21:26:07 -07002058 if (allowConcurrentWithSoundTrigger && activeDesc->isSoundTrigger()) {
2059 continue;
2060 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002061 RecordClientVector activeHotwordClients =
2062 activeDesc->clientsList(true, AUDIO_SOURCE_HOTWORD);
2063 if (activeHotwordClients.size() > 0) {
Eric Laurent74708e72017-04-07 17:13:42 -07002064 SortedVector<audio_session_t> sessions = activeDesc->getPreemptedSessions();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002065
2066 for (const auto& activeClient : activeHotwordClients) {
2067 *concurrency |= API_INPUT_CONCURRENCY_PREEMPT;
2068 sessions.add(activeClient->session());
2069 closeClient(activeClient->portId());
2070 ALOGV("%s input %d for HOTWORD preempting HOTWORD input %d", __FUNCTION__,
2071 input, activeDesc->mIoHandle);
2072 }
2073
Eric Laurent74708e72017-04-07 17:13:42 -07002074 inputDesc->setPreemptedSessions(sessions);
Eric Laurent74708e72017-04-07 17:13:42 -07002075 }
2076 }
2077 }
Eric Laurente552edb2014-03-10 17:42:56 -07002078
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002079 // Make sure we start with the correct silence state
Eric Laurent8f42ea12018-08-08 09:08:25 -07002080 client->setSilenced(silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002081
Eric Laurent313d1e72016-01-29 09:56:57 -08002082 // increment activity count before calling getNewInputDevice() below as only active sessions
2083 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002084 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002085
Eric Laurent8f42ea12018-08-08 09:08:25 -07002086 // indicate active capture to sound trigger service if starting capture from a mic on
2087 // primary HW module
2088 audio_devices_t device = getNewInputDevice(inputDesc);
2089 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002090
Eric Laurent8f42ea12018-08-08 09:08:25 -07002091 status_t status = inputDesc->start();
2092 if (status != NO_ERROR) {
2093 inputDesc->setClientActive(client, false);
2094 return status;
2095 }
2096
2097 if (inputDesc->activeCount() == 1) {
2098 // if input maps to a dynamic policy with an activity listener, notify of state change
2099 if ((inputDesc->mPolicyMix != NULL)
2100 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2101 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2102 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002103 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002104
Eric Laurent8f42ea12018-08-08 09:08:25 -07002105 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2106 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2107 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
2108 SoundTrigger::setCaptureState(true);
2109 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002110
Eric Laurent8f42ea12018-08-08 09:08:25 -07002111 // automatically enable the remote submix output when input is started if not
2112 // used by a policy mix of type MIX_TYPE_RECORDERS
2113 // For remote submix (a virtual device), we open only one input per capture request.
2114 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2115 String8 address = String8("");
2116 if (inputDesc->mPolicyMix == NULL) {
2117 address = String8("0");
2118 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2119 address = inputDesc->mPolicyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002120 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002121 if (address != "") {
2122 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2123 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2124 address, "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08002125 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002126 }
Eric Laurente552edb2014-03-10 17:42:56 -07002127 }
2128
Eric Laurent8f42ea12018-08-08 09:08:25 -07002129 ALOGV("%s input %d source = %d exit", __FUNCTION__, input, client->source());
Eric Laurente552edb2014-03-10 17:42:56 -07002130
Eric Laurente552edb2014-03-10 17:42:56 -07002131 return NO_ERROR;
2132}
2133
Eric Laurent8fc147b2018-07-22 19:13:55 -07002134status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002135{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002136 ALOGV("%s portId %d", __FUNCTION__, portId);
2137
2138 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2139 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002140 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002141 return BAD_VALUE;
2142 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002143 audio_io_handle_t input = inputDesc->mIoHandle;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002144 sp<RecordClientDescriptor> client = inputDesc->clientsMap()[portId];
2145 if (!client->active()) {
2146 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002147 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002148 }
2149
Eric Laurent8f42ea12018-08-08 09:08:25 -07002150 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002151
Eric Laurent8f42ea12018-08-08 09:08:25 -07002152 inputDesc->stop();
2153 if (inputDesc->isActive()) {
2154 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2155 } else {
2156 // if input maps to a dynamic policy with an activity listener, notify of state change
2157 if ((inputDesc->mPolicyMix != NULL)
2158 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2159 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2160 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002161 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002162
2163 // automatically disable the remote submix output when input is stopped if not
2164 // used by a policy mix of type MIX_TYPE_RECORDERS
2165 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2166 String8 address = String8("");
2167 if (inputDesc->mPolicyMix == NULL) {
2168 address = String8("0");
2169 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2170 address = inputDesc->mPolicyMix->mDeviceAddress;
2171 }
2172 if (address != "") {
2173 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2174 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2175 address, "remote-submix");
2176 }
2177 }
2178
2179 audio_devices_t device = inputDesc->mDevice;
2180 resetInputDevice(input);
2181
2182 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2183 // primary HW module
2184 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2185 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2186 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
2187 SoundTrigger::setCaptureState(false);
2188 }
2189 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002190 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002191 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002192}
2193
Eric Laurent8fc147b2018-07-22 19:13:55 -07002194void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002195{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002196 ALOGV("%s portId %d", __FUNCTION__, portId);
2197
2198 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2199 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002200 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002201 return;
2202 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002203 sp<RecordClientDescriptor> client = inputDesc->clientsMap()[portId];
Eric Laurent8fc147b2018-07-22 19:13:55 -07002204 audio_io_handle_t input = inputDesc->mIoHandle;
2205
Eric Laurent8f42ea12018-08-08 09:08:25 -07002206 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002207
Eric Laurent8f42ea12018-08-08 09:08:25 -07002208 inputDesc->clientsMap().erase(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002209
Eric Laurent8f42ea12018-08-08 09:08:25 -07002210 if (inputDesc->clientsMap().size() > 0) {
2211 ALOGV("%s %zu clients remaining", __FUNCTION__, inputDesc->clientsMap().size());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002212 return;
2213 }
2214
Eric Laurent05b90f82014-08-27 15:32:29 -07002215 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002216 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002217 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002218}
2219
Eric Laurent8f42ea12018-08-08 09:08:25 -07002220void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002221{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002222 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002223
2224 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002225 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002226 }
2227}
2228
Eric Laurent8f42ea12018-08-08 09:08:25 -07002229void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2230{
2231 stopInput(portId);
2232 releaseInput(portId);
2233}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002234
Eric Laurentd4692962014-05-05 18:13:44 -07002235void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002236 bool patchRemoved = false;
2237
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002238 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002239 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002240 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002241 if (patch_index >= 0) {
2242 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002243 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002244 mAudioPatches.removeItemsAt(patch_index);
2245 patchRemoved = true;
2246 }
Eric Laurentfe231122017-11-17 17:48:06 -08002247 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002248 }
2249 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002250 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002251 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002252
2253 if (patchRemoved) {
2254 mpClientInterface->onAudioPatchListUpdate();
2255 }
Eric Laurentd4692962014-05-05 18:13:44 -07002256}
2257
Eric Laurente0720872014-03-11 09:30:41 -07002258void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002259 int indexMin,
2260 int indexMax)
2261{
2262 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002263 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002264
2265 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002266 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2267 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002268 continue;
2269 }
2270 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002271 }
Eric Laurente552edb2014-03-10 17:42:56 -07002272}
2273
Eric Laurente0720872014-03-11 09:30:41 -07002274status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002275 int index,
2276 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002277{
2278
Nadav Bar7c605f62017-12-25 00:01:52 +02002279 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2280 // app that has MODIFY_PHONE_STATE permission.
2281 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
2282 !(stream == AUDIO_STREAM_VOICE_CALL && index == 0)) ||
François Gaffied1ab2bd2015-12-02 18:20:06 +01002283 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002284 return BAD_VALUE;
2285 }
2286 if (!audio_is_output_device(device)) {
2287 return BAD_VALUE;
2288 }
2289
2290 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002291 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002292
Eric Laurent1fd372e2016-04-06 14:23:53 -07002293 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002294 stream, device, index);
2295
Eric Laurent28d09f02016-03-08 10:43:05 -08002296 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002297 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2298 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002299 continue;
2300 }
2301 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2302 }
Eric Laurente552edb2014-03-10 17:42:56 -07002303
Eric Laurent1fd372e2016-04-06 14:23:53 -07002304 // update volume on all outputs and streams matching the following:
2305 // - The requested stream (or a stream matching for volume control) is active on the output
2306 // - The device (or devices) selected by the strategy corresponding to this stream includes
2307 // the requested device
2308 // - For non default requested device, currently selected device on the output is either the
2309 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002310 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2311 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002312 status_t status = NO_ERROR;
2313 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002314 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2315 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08002316 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
Eric Laurent3839bc02018-07-10 18:33:34 -07002317 if (!(streamsMatchForvolume(stream, (audio_stream_type_t)curStream))) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002318 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002319 }
Eric Laurentdcd4ab12018-06-29 17:45:13 -07002320 if (!(desc->isStreamActive((audio_stream_type_t)curStream) || isInCall())) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002321 continue;
2322 }
Eric Laurent794fde22016-03-11 09:50:45 -08002323 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002324 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2325 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002326 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2327 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002328 continue;
2329 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002330 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002331 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002332 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07002333 applyVolume = (curDevice & curStreamDevice) != 0;
2334 } else {
2335 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002336 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002337 }
Eric Laurent3839bc02018-07-10 18:33:34 -07002338 // rescale index before applying to curStream as ranges may be different for
2339 // stream and curStream
2340 int idx = rescaleVolumeIndex(index, stream, (audio_stream_type_t)curStream);
Eric Laurente76f29c2016-09-14 17:17:53 -07002341 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002342 //FIXME: workaround for truncated touch sounds
2343 // delayed volume change for system stream to be removed when the problem is
2344 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002345 status_t volStatus =
Eric Laurent3839bc02018-07-10 18:33:34 -07002346 checkAndSetVolume((audio_stream_type_t)curStream, idx, desc, curDevice,
Eric Laurentdc462862016-07-19 12:29:53 -07002347 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002348 if (volStatus != NO_ERROR) {
2349 status = volStatus;
2350 }
2351 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002352 }
Eric Laurente552edb2014-03-10 17:42:56 -07002353 }
2354 return status;
2355}
2356
Eric Laurente0720872014-03-11 09:30:41 -07002357status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002358 int *index,
2359 audio_devices_t device)
2360{
2361 if (index == NULL) {
2362 return BAD_VALUE;
2363 }
2364 if (!audio_is_output_device(device)) {
2365 return BAD_VALUE;
2366 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002367 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002368 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002369 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002370 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2371 }
François Gaffiedfd74092015-03-19 12:10:59 +01002372 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002373
François Gaffied1ab2bd2015-12-02 18:20:06 +01002374 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002375 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2376 return NO_ERROR;
2377}
2378
Eric Laurent36829f92017-04-07 19:04:42 -07002379audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002380{
2381 // select one output among several suitable for global effects.
2382 // The priority is as follows:
2383 // 1: An offloaded output. If the effect ends up not being offloadable,
2384 // AudioFlinger will invalidate the track and the offloaded output
2385 // will be closed causing the effect to be moved to a PCM output.
2386 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002387 // 3: The primary output
2388 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002389
Eric Laurent3b73df72014-03-11 09:06:29 -07002390 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002391 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent36829f92017-04-07 19:04:42 -07002392 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002393
Eric Laurent36829f92017-04-07 19:04:42 -07002394 if (outputs.size() == 0) {
2395 return AUDIO_IO_HANDLE_NONE;
2396 }
Eric Laurente552edb2014-03-10 17:42:56 -07002397
Eric Laurent36829f92017-04-07 19:04:42 -07002398 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2399 bool activeOnly = true;
2400
2401 while (output == AUDIO_IO_HANDLE_NONE) {
2402 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2403 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2404 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2405
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002406 for (audio_io_handle_t output : outputs) {
2407 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002408 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2409 continue;
2410 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002411 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2412 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002413 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002414 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002415 }
2416 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002417 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002418 }
2419 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002420 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002421 }
2422 }
2423 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2424 output = outputOffloaded;
2425 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2426 output = outputDeepBuffer;
2427 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2428 output = outputPrimary;
2429 } else {
2430 output = outputs[0];
2431 }
2432 activeOnly = false;
2433 }
2434
2435 if (output != mMusicEffectOutput) {
2436 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2437 mMusicEffectOutput = output;
2438 }
2439
2440 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002441 return output;
2442}
2443
Eric Laurent36829f92017-04-07 19:04:42 -07002444audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2445{
2446 return selectOutputForMusicEffects();
2447}
2448
Eric Laurente0720872014-03-11 09:30:41 -07002449status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002450 audio_io_handle_t io,
2451 uint32_t strategy,
2452 int session,
2453 int id)
2454{
2455 ssize_t index = mOutputs.indexOfKey(io);
2456 if (index < 0) {
2457 index = mInputs.indexOfKey(io);
2458 if (index < 0) {
2459 ALOGW("registerEffect() unknown io %d", io);
2460 return INVALID_OPERATION;
2461 }
2462 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002463 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002464}
2465
Eric Laurentc75307b2015-03-17 15:29:32 -07002466bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2467{
Eric Laurent28d09f02016-03-08 10:43:05 -08002468 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002469 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2470 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002471 continue;
2472 }
2473 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2474 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002475 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002476}
2477
2478bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2479{
2480 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2481}
2482
Eric Laurente0720872014-03-11 09:30:41 -07002483bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002484{
2485 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002486 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002487 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002488 return true;
2489 }
2490 }
2491 return false;
2492}
2493
Eric Laurent275e8e92014-11-30 15:14:47 -08002494// Register a list of custom mixes with their attributes and format.
2495// When a mix is registered, corresponding input and output profiles are
2496// added to the remote submix hw module. The profile contains only the
2497// parameters (sampling rate, format...) specified by the mix.
2498// The corresponding input remote submix device is also connected.
2499//
2500// When a remote submix device is connected, the address is checked to select the
2501// appropriate profile and the corresponding input or output stream is opened.
2502//
2503// When capture starts, getInputForAttr() will:
2504// - 1 look for a mix matching the address passed in attribtutes tags if any
2505// - 2 if none found, getDeviceForInputSource() will:
2506// - 2.1 look for a mix matching the attributes source
2507// - 2.2 if none found, default to device selection by policy rules
2508// At this time, the corresponding output remote submix device is also connected
2509// and active playback use cases can be transferred to this mix if needed when reconnecting
2510// after AudioTracks are invalidated
2511//
2512// When playback starts, getOutputForAttr() will:
2513// - 1 look for a mix matching the address passed in attribtutes tags if any
2514// - 2 if none found, look for a mix matching the attributes usage
2515// - 3 if none found, default to device and output selection by policy rules.
2516
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002517status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002518{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002519 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2520 status_t res = NO_ERROR;
2521
2522 sp<HwModule> rSubmixModule;
2523 // examine each mix's route type
2524 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002525 AudioMix mix = mixes[i];
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002526 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
Eric Laurent97ac8712018-07-27 18:59:02 -07002527 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002528 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002529 break;
2530 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002531 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002532 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002533 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002534 rSubmixModule = mHwModules.getModuleFromName(
2535 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2536 if (rSubmixModule == 0) {
2537 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2538 i);
2539 res = INVALID_OPERATION;
2540 break;
2541 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002542 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002543
Eric Laurent97ac8712018-07-27 18:59:02 -07002544 String8 address = mix.mDeviceAddress;
2545 if (mix.mMixType == MIX_TYPE_PLAYERS) {
2546 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2547 } else {
2548 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
2549 }
François Gaffie036e1e92015-03-19 10:16:24 +01002550
Eric Laurent97ac8712018-07-27 18:59:02 -07002551 if (mPolicyMixes.registerMix(address, mix, 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002552 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002553 res = INVALID_OPERATION;
2554 break;
2555 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002556 audio_config_t outputConfig = mix.mFormat;
2557 audio_config_t inputConfig = mix.mFormat;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002558 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2559 // stereo and let audio flinger do the channel conversion if needed.
2560 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2561 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2562 rSubmixModule->addOutputProfile(address, &outputConfig,
2563 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2564 rSubmixModule->addInputProfile(address, &inputConfig,
2565 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002566
Eric Laurent97ac8712018-07-27 18:59:02 -07002567 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002568 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2569 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2570 address.string(), "remote-submix");
2571 } else {
2572 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2573 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2574 address.string(), "remote-submix");
2575 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002576 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2577 String8 address = mix.mDeviceAddress;
2578 audio_devices_t device = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002579 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2580 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002581
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002582 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002583 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2584 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2585 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2586 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2587 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2588 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002589 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2590 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002591 if (mPolicyMixes.registerMix(address, mix, desc) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002592 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002593 } else {
2594 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002595 }
2596 break;
2597 }
2598 }
2599
2600 if (res != NO_ERROR) {
2601 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002602 i, device, address.string());
2603 res = INVALID_OPERATION;
2604 break;
2605 } else if (!foundOutput) {
2606 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2607 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002608 res = INVALID_OPERATION;
2609 break;
2610 }
Eric Laurentc722f302014-12-10 11:21:49 -08002611 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002612 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002613 if (res != NO_ERROR) {
2614 unregisterPolicyMixes(mixes);
2615 }
2616 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002617}
2618
2619status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2620{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002621 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002622 status_t res = NO_ERROR;
2623 sp<HwModule> rSubmixModule;
2624 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002625 for (const auto& mix : mixes) {
2626 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002627
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002628 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002629 rSubmixModule = mHwModules.getModuleFromName(
2630 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2631 if (rSubmixModule == 0) {
2632 res = INVALID_OPERATION;
2633 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002634 }
2635 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002636
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002637 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002638
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002639 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2640 res = INVALID_OPERATION;
2641 continue;
2642 }
2643
2644 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2645 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2646 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2647 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2648 address.string(), "remote-submix");
2649 }
2650 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2651 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2652 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2653 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2654 address.string(), "remote-submix");
2655 }
2656 rSubmixModule->removeOutputProfile(address);
2657 rSubmixModule->removeInputProfile(address);
2658
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002659 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2660 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002661 res = INVALID_OPERATION;
2662 continue;
2663 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002664 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002665 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002666 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002667}
2668
Eric Laurente552edb2014-03-10 17:42:56 -07002669
Eric Laurente0720872014-03-11 09:30:41 -07002670status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002671{
Eric Laurente552edb2014-03-10 17:42:56 -07002672 String8 result;
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002673 result.appendFormat("\nAudioPolicyManager Dump: %p\n", this);
2674 result.appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07002675 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002676 std::string stateLiteral;
2677 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002678 result.appendFormat(" Phone state: %s\n", stateLiteral.c_str());
2679 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
2680 "communications", "media", "record", "dock", "system",
2681 "HDMI system audio", "encoded surround output", "vibrate ringing" };
2682 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
2683 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
2684 result.appendFormat(" Force use for %s: %d\n",
2685 forceUses[i], mEngine->getForceUse(i));
2686 }
2687 result.appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
2688 result.appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
2689 result.appendFormat(" Config source: %s\n", getConfig().getSource().c_str());
François Gaffie2110e042015-03-24 08:41:51 +01002690 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002691
François Gaffie112b0af2015-11-19 16:13:25 +01002692 mAvailableOutputDevices.dump(fd, String8("Available output"));
2693 mAvailableInputDevices.dump(fd, String8("Available input"));
Mikhail Naganovd4120142017-12-06 15:49:22 -08002694 mHwModulesAll.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002695 mOutputs.dump(fd);
2696 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002697 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002698 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002699 mAudioPatches.dump(fd);
Mikhail Naganov44344b02016-12-13 11:21:02 -08002700 mPolicyMixes.dump(fd);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07002701 mAudioSources.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002702
2703 return NO_ERROR;
2704}
2705
2706// This function checks for the parameters which can be offloaded.
2707// This can be enhanced depending on the capability of the DSP and policy
2708// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002709bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002710{
2711 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002712 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002713 offloadInfo.sample_rate, offloadInfo.channel_mask,
2714 offloadInfo.format,
2715 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2716 offloadInfo.has_video);
2717
Andy Hung2ddee192015-12-18 17:34:44 -08002718 if (mMasterMono) {
2719 return false; // no offloading if mono is set.
2720 }
2721
Eric Laurente552edb2014-03-10 17:42:56 -07002722 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07002723 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
2724 ALOGV("offload disabled by audio.offload.disable");
2725 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002726 }
2727
2728 // Check if stream type is music, then only allow offload as of now.
2729 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2730 {
2731 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2732 return false;
2733 }
2734
2735 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002736 const bool allowOffloadWithVideo =
2737 property_get_bool("audio.offload.video", false /* default_value */);
2738 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002739 ALOGV("isOffloadSupported: has_video == true, returning false");
2740 return false;
2741 }
2742
2743 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07002744 const int min_duration_secs = property_get_int32(
2745 "audio.offload.min.duration.secs", -1 /* default_value */);
2746 if (min_duration_secs >= 0) {
2747 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
2748 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%d)",
2749 min_duration_secs);
Eric Laurente552edb2014-03-10 17:42:56 -07002750 return false;
2751 }
2752 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2753 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2754 return false;
2755 }
2756
2757 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2758 // creating an offloaded track and tearing it down immediately after start when audioflinger
2759 // detects there is an active non offloadable effect.
2760 // FIXME: We should check the audio session here but we do not have it in this context.
2761 // This may prevent offloading in rare situations where effects are left active by apps
2762 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002763 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002764 return false;
2765 }
2766
2767 // See if there is a profile to support this.
2768 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002769 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002770 offloadInfo.sample_rate,
2771 offloadInfo.format,
2772 offloadInfo.channel_mask,
2773 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002774 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2775 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002776}
2777
Eric Laurent6a94d692014-05-20 11:18:06 -07002778status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2779 audio_port_type_t type,
2780 unsigned int *num_ports,
2781 struct audio_port *ports,
2782 unsigned int *generation)
2783{
2784 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2785 generation == NULL) {
2786 return BAD_VALUE;
2787 }
2788 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2789 if (ports == NULL) {
2790 *num_ports = 0;
2791 }
2792
2793 size_t portsWritten = 0;
2794 size_t portsMax = *num_ports;
2795 *num_ports = 0;
2796 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002797 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2798 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002799 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002800 for (const auto& dev : mAvailableOutputDevices) {
2801 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002802 continue;
2803 }
2804 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002805 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002806 }
2807 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002808 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002809 }
2810 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002811 for (const auto& dev : mAvailableInputDevices) {
2812 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002813 continue;
2814 }
2815 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002816 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002817 }
2818 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002819 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002820 }
2821 }
2822 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2823 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2824 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2825 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2826 }
2827 *num_ports += mInputs.size();
2828 }
2829 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002830 size_t numOutputs = 0;
2831 for (size_t i = 0; i < mOutputs.size(); i++) {
2832 if (!mOutputs[i]->isDuplicated()) {
2833 numOutputs++;
2834 if (portsWritten < portsMax) {
2835 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2836 }
2837 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002838 }
Eric Laurent84c70242014-06-23 08:46:27 -07002839 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002840 }
2841 }
2842 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002843 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002844 return NO_ERROR;
2845}
2846
Eric Laurent99fcae42018-05-17 16:59:18 -07002847status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07002848{
Eric Laurent99fcae42018-05-17 16:59:18 -07002849 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
2850 return BAD_VALUE;
2851 }
2852 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
2853 if (dev != 0) {
2854 dev->toAudioPort(port);
2855 return NO_ERROR;
2856 }
2857 dev = mAvailableInputDevices.getDeviceFromId(port->id);
2858 if (dev != 0) {
2859 dev->toAudioPort(port);
2860 return NO_ERROR;
2861 }
2862 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
2863 if (out != 0) {
2864 out->toAudioPort(port);
2865 return NO_ERROR;
2866 }
2867 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
2868 if (in != 0) {
2869 in->toAudioPort(port);
2870 return NO_ERROR;
2871 }
2872 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002873}
2874
Eric Laurent6a94d692014-05-20 11:18:06 -07002875status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2876 audio_patch_handle_t *handle,
2877 uid_t uid)
2878{
2879 ALOGV("createAudioPatch()");
2880
2881 if (handle == NULL || patch == NULL) {
2882 return BAD_VALUE;
2883 }
2884 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2885
Mikhail Naganovac9858b2018-06-15 13:12:37 -07002886 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07002887 return BAD_VALUE;
2888 }
2889 // only one source per audio patch supported for now
2890 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002891 return INVALID_OPERATION;
2892 }
Eric Laurent874c42872014-08-08 15:13:39 -07002893
2894 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002895 return INVALID_OPERATION;
2896 }
Eric Laurent874c42872014-08-08 15:13:39 -07002897 for (size_t i = 0; i < patch->num_sinks; i++) {
2898 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2899 return INVALID_OPERATION;
2900 }
2901 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002902
2903 sp<AudioPatch> patchDesc;
2904 ssize_t index = mAudioPatches.indexOfKey(*handle);
2905
Eric Laurent6a94d692014-05-20 11:18:06 -07002906 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2907 patch->sources[0].role,
2908 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002909#if LOG_NDEBUG == 0
2910 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002911 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002912 patch->sinks[i].role,
2913 patch->sinks[i].type);
2914 }
2915#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002916
2917 if (index >= 0) {
2918 patchDesc = mAudioPatches.valueAt(index);
2919 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2920 mUidCached, patchDesc->mUid, uid);
2921 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2922 return INVALID_OPERATION;
2923 }
2924 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002925 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002926 }
2927
2928 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002929 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002930 if (outputDesc == NULL) {
2931 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2932 return BAD_VALUE;
2933 }
Eric Laurent84c70242014-06-23 08:46:27 -07002934 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2935 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002936 if (patchDesc != 0) {
2937 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2938 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2939 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2940 return BAD_VALUE;
2941 }
2942 }
Eric Laurent874c42872014-08-08 15:13:39 -07002943 DeviceVector devices;
2944 for (size_t i = 0; i < patch->num_sinks; i++) {
2945 // Only support mix to devices connection
2946 // TODO add support for mix to mix connection
2947 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2948 ALOGV("createAudioPatch() source mix but sink is not a device");
2949 return INVALID_OPERATION;
2950 }
2951 sp<DeviceDescriptor> devDesc =
2952 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2953 if (devDesc == 0) {
2954 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2955 return BAD_VALUE;
2956 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002957
François Gaffie53615e22015-03-19 09:24:12 +01002958 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002959 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002960 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002961 NULL, // updatedSamplingRate
2962 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002963 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002964 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002965 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002966 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002967 ALOGV("createAudioPatch() profile not supported for device %08x",
2968 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002969 return INVALID_OPERATION;
2970 }
2971 devices.add(devDesc);
2972 }
2973 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002974 return INVALID_OPERATION;
2975 }
Eric Laurent874c42872014-08-08 15:13:39 -07002976
Eric Laurent6a94d692014-05-20 11:18:06 -07002977 // TODO: reconfigure output format and channels here
2978 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002979 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002980 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002981 index = mAudioPatches.indexOfKey(*handle);
2982 if (index >= 0) {
2983 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2984 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2985 }
2986 patchDesc = mAudioPatches.valueAt(index);
2987 patchDesc->mUid = uid;
2988 ALOGV("createAudioPatch() success");
2989 } else {
2990 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2991 return INVALID_OPERATION;
2992 }
2993 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2994 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2995 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002996 // only one sink supported when connecting an input device to a mix
2997 if (patch->num_sinks > 1) {
2998 return INVALID_OPERATION;
2999 }
François Gaffie53615e22015-03-19 09:24:12 +01003000 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003001 if (inputDesc == NULL) {
3002 return BAD_VALUE;
3003 }
3004 if (patchDesc != 0) {
3005 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3006 return BAD_VALUE;
3007 }
3008 }
3009 sp<DeviceDescriptor> devDesc =
3010 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
3011 if (devDesc == 0) {
3012 return BAD_VALUE;
3013 }
3014
François Gaffie53615e22015-03-19 09:24:12 +01003015 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08003016 devDesc->mAddress,
3017 patch->sinks[0].sample_rate,
3018 NULL, /*updatedSampleRate*/
3019 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003020 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003021 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003022 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003023 // FIXME for the parameter type,
3024 // and the NONE
3025 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003026 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003027 return INVALID_OPERATION;
3028 }
3029 // TODO: reconfigure output format and channels here
3030 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01003031 devDesc->type(), inputDesc->mIoHandle);
3032 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003033 index = mAudioPatches.indexOfKey(*handle);
3034 if (index >= 0) {
3035 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3036 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
3037 }
3038 patchDesc = mAudioPatches.valueAt(index);
3039 patchDesc->mUid = uid;
3040 ALOGV("createAudioPatch() success");
3041 } else {
3042 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
3043 return INVALID_OPERATION;
3044 }
3045 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3046 // device to device connection
3047 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003048 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003049 return BAD_VALUE;
3050 }
3051 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003052 sp<DeviceDescriptor> srcDeviceDesc =
3053 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07003054 if (srcDeviceDesc == 0) {
3055 return BAD_VALUE;
3056 }
Eric Laurent874c42872014-08-08 15:13:39 -07003057
Eric Laurent6a94d692014-05-20 11:18:06 -07003058 //update source and sink with our own data as the data passed in the patch may
3059 // be incomplete.
3060 struct audio_patch newPatch = *patch;
3061 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003062
Eric Laurent874c42872014-08-08 15:13:39 -07003063 for (size_t i = 0; i < patch->num_sinks; i++) {
3064 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3065 ALOGV("createAudioPatch() source device but one sink is not a device");
3066 return INVALID_OPERATION;
3067 }
3068
3069 sp<DeviceDescriptor> sinkDeviceDesc =
3070 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3071 if (sinkDeviceDesc == 0) {
3072 return BAD_VALUE;
3073 }
3074 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
3075
Eric Laurent3bcf8592015-04-03 12:13:24 -07003076 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003077 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003078 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08003079 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003080 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003081 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003082 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003083 return INVALID_OPERATION;
3084 }
Eric Laurent874c42872014-08-08 15:13:39 -07003085 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01003086 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003087 // if the sink device is reachable via an opened output stream, request to go via
3088 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07003089 audio_io_handle_t output = selectOutput(outputs,
3090 AUDIO_OUTPUT_FLAG_NONE,
3091 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07003092 if (output != AUDIO_IO_HANDLE_NONE) {
3093 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3094 if (outputDesc->isDuplicated()) {
3095 return INVALID_OPERATION;
3096 }
3097 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003098 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003099 newPatch.num_sources = 2;
3100 }
Eric Laurent83b88082014-06-20 18:31:16 -07003101 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003102 }
3103 // TODO: check from routing capabilities in config file and other conflicting patches
3104
Mikhail Naganovdc769682018-05-04 15:34:08 -07003105 status_t status = installPatch(__func__, index, handle, &newPatch, 0, uid, &patchDesc);
3106 if (status != NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003107 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3108 status);
3109 return INVALID_OPERATION;
3110 }
3111 } else {
3112 return BAD_VALUE;
3113 }
3114 } else {
3115 return BAD_VALUE;
3116 }
3117 return NO_ERROR;
3118}
3119
3120status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3121 uid_t uid)
3122{
3123 ALOGV("releaseAudioPatch() patch %d", handle);
3124
3125 ssize_t index = mAudioPatches.indexOfKey(handle);
3126
3127 if (index < 0) {
3128 return BAD_VALUE;
3129 }
3130 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3131 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3132 mUidCached, patchDesc->mUid, uid);
3133 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3134 return INVALID_OPERATION;
3135 }
3136
3137 struct audio_patch *patch = &patchDesc->mPatch;
3138 patchDesc->mUid = mUidCached;
3139 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003140 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003141 if (outputDesc == NULL) {
3142 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3143 return BAD_VALUE;
3144 }
3145
Eric Laurentc75307b2015-03-17 15:29:32 -07003146 setOutputDevice(outputDesc,
3147 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07003148 true,
3149 0,
3150 NULL);
3151 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3152 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003153 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003154 if (inputDesc == NULL) {
3155 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3156 return BAD_VALUE;
3157 }
3158 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003159 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003160 true,
3161 NULL);
3162 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003163 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3164 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3165 status, patchDesc->mAfPatchHandle);
3166 removeAudioPatch(patchDesc->mHandle);
3167 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003168 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003169 } else {
3170 return BAD_VALUE;
3171 }
3172 } else {
3173 return BAD_VALUE;
3174 }
3175 return NO_ERROR;
3176}
3177
3178status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3179 struct audio_patch *patches,
3180 unsigned int *generation)
3181{
François Gaffie53615e22015-03-19 09:24:12 +01003182 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003183 return BAD_VALUE;
3184 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003185 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003186 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003187}
3188
Eric Laurente1715a42014-05-20 11:30:42 -07003189status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003190{
Eric Laurente1715a42014-05-20 11:30:42 -07003191 ALOGV("setAudioPortConfig()");
3192
3193 if (config == NULL) {
3194 return BAD_VALUE;
3195 }
3196 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3197 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003198 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3199 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003200 }
3201
Eric Laurenta121f902014-06-03 13:32:54 -07003202 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003203 if (config->type == AUDIO_PORT_TYPE_MIX) {
3204 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003205 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003206 if (outputDesc == NULL) {
3207 return BAD_VALUE;
3208 }
Eric Laurent84c70242014-06-23 08:46:27 -07003209 ALOG_ASSERT(!outputDesc->isDuplicated(),
3210 "setAudioPortConfig() called on duplicated output %d",
3211 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003212 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003213 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003214 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003215 if (inputDesc == NULL) {
3216 return BAD_VALUE;
3217 }
Eric Laurenta121f902014-06-03 13:32:54 -07003218 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003219 } else {
3220 return BAD_VALUE;
3221 }
3222 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3223 sp<DeviceDescriptor> deviceDesc;
3224 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3225 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3226 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3227 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3228 } else {
3229 return BAD_VALUE;
3230 }
3231 if (deviceDesc == NULL) {
3232 return BAD_VALUE;
3233 }
Eric Laurenta121f902014-06-03 13:32:54 -07003234 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003235 } else {
3236 return BAD_VALUE;
3237 }
3238
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003239 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003240 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3241 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003242 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003243 audioPortConfig->toAudioPortConfig(&newConfig, config);
3244 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003245 }
Eric Laurenta121f902014-06-03 13:32:54 -07003246 if (status != NO_ERROR) {
3247 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003248 }
Eric Laurente1715a42014-05-20 11:30:42 -07003249
3250 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003251}
3252
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003253void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3254{
Eric Laurentd60560a2015-04-10 11:31:20 -07003255 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003256 clearAudioPatches(uid);
3257 clearSessionRoutes(uid);
3258}
3259
Eric Laurent6a94d692014-05-20 11:18:06 -07003260void AudioPolicyManager::clearAudioPatches(uid_t uid)
3261{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003262 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003263 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3264 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003265 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003266 }
3267 }
3268}
3269
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003270void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3271 audio_io_handle_t ouptutToSkip)
3272{
3273 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3274 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3275 for (size_t j = 0; j < mOutputs.size(); j++) {
3276 if (mOutputs.keyAt(j) == ouptutToSkip) {
3277 continue;
3278 }
3279 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3280 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3281 continue;
3282 }
3283 // If the default device for this strategy is on another output mix,
3284 // invalidate all tracks in this strategy to force re connection.
3285 // Otherwise select new device on the output mix.
3286 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003287 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003288 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3289 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3290 }
3291 }
3292 } else {
3293 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3294 setOutputDevice(outputDesc, newDevice, false);
3295 }
3296 }
3297}
3298
3299void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3300{
3301 // remove output routes associated with this uid
3302 SortedVector<routing_strategy> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07003303 for (size_t i = 0; i < mOutputs.size(); i++) {
3304 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3305 TrackClientMap clients = outputDesc->clientsMap();
3306 for (const auto& client : clients) {
3307 if (client.second->hasPreferredDevice() && client.second->uid() == uid) {
3308 client.second->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3309 affectedStrategies.add(getStrategy(client.second->stream()));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003310 }
3311 }
3312 }
3313 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003314 for (const auto& strategy : affectedStrategies) {
3315 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003316 }
3317
3318 // remove input routes associated with this uid
3319 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07003320 for (size_t i = 0; i < mInputs.size(); i++) {
3321 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
3322 RecordClientMap clients = inputDesc->clientsMap();
3323 for (const auto& client : clients) {
3324 if (client.second->hasPreferredDevice() && client.second->uid() == uid) {
3325 client.second->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3326 affectedSources.add(client.second->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003327 }
3328 }
3329 }
3330 // reroute inputs if necessary
3331 SortedVector<audio_io_handle_t> inputsToClose;
3332 for (size_t i = 0; i < mInputs.size(); i++) {
3333 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003334 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003335 inputsToClose.add(inputDesc->mIoHandle);
3336 }
3337 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003338 for (const auto& input : inputsToClose) {
3339 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003340 }
3341}
3342
Eric Laurentd60560a2015-04-10 11:31:20 -07003343void AudioPolicyManager::clearAudioSources(uid_t uid)
3344{
3345 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003346 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3347 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07003348 stopAudioSource(mAudioSources.keyAt(i));
3349 }
3350 }
3351}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003352
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003353status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3354 audio_io_handle_t *ioHandle,
3355 audio_devices_t *device)
3356{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003357 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3358 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003359 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003360
François Gaffiedf372692015-03-19 10:43:27 +01003361 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003362}
3363
Eric Laurentd60560a2015-04-10 11:31:20 -07003364status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003365 const audio_attributes_t *attributes,
3366 audio_port_handle_t *portId,
3367 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003368{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003369 ALOGV("%s", __FUNCTION__);
3370 *portId = AUDIO_PORT_HANDLE_NONE;
3371
3372 if (source == NULL || attributes == NULL || portId == NULL) {
3373 ALOGW("%s invalid argument: source %p attributes %p handle %p",
3374 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003375 return BAD_VALUE;
3376 }
3377
Eric Laurentd60560a2015-04-10 11:31:20 -07003378 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3379 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003380 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
3381 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003382 return INVALID_OPERATION;
3383 }
3384
3385 sp<DeviceDescriptor> srcDeviceDesc =
3386 mAvailableInputDevices.getDevice(source->ext.device.type,
3387 String8(source->ext.device.address));
3388 if (srcDeviceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003389 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003390 return BAD_VALUE;
3391 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003392
3393 *portId = AudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07003394
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003395 struct audio_patch dummyPatch = {};
Eric Laurentd60560a2015-04-10 11:31:20 -07003396 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003397
3398 sp<SourceClientDescriptor> sourceDesc =
3399 new SourceClientDescriptor(*portId, uid, *attributes, patchDesc, srcDeviceDesc,
Eric Laurent97ac8712018-07-27 18:59:02 -07003400 streamTypefromAttributesInt(attributes),
3401 getStrategyForAttr(attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07003402
3403 status_t status = connectAudioSource(sourceDesc);
3404 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003405 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003406 }
3407 return status;
3408}
3409
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003410status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003411{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003412 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003413
3414 // make sure we only have one patch per source.
3415 disconnectAudioSource(sourceDesc);
3416
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003417 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003418 routing_strategy strategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003419 audio_stream_type_t stream = sourceDesc->stream();
3420 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->srcDevice();
Eric Laurentd60560a2015-04-10 11:31:20 -07003421
3422 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3423 sp<DeviceDescriptor> sinkDeviceDesc =
3424 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3425
3426 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003427
3428 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3429 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003430 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003431 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3432 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3433 // create patch between src device and output device
3434 // create Hwoutput and add to mHwOutputs
3435 } else {
3436 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3437 audio_io_handle_t output =
3438 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3439 if (output == AUDIO_IO_HANDLE_NONE) {
3440 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3441 return INVALID_OPERATION;
3442 }
3443 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3444 if (outputDesc->isDuplicated()) {
3445 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3446 return INVALID_OPERATION;
3447 }
Eric Laurent733ce942017-12-07 12:18:25 -08003448 status_t status = outputDesc->start();
3449 if (status != NO_ERROR) {
3450 return status;
3451 }
3452
Eric Laurentd60560a2015-04-10 11:31:20 -07003453 // create a special patch with no sink and two sources:
3454 // - the second source indicates to PatchPanel through which output mix this patch should
3455 // be connected as well as the stream type for volume control
3456 // - the sink is defined by whatever output device is currently selected for the output
3457 // though which this patch is routed.
Mikhail Naganovdc769682018-05-04 15:34:08 -07003458 PatchBuilder patchBuilder;
3459 patchBuilder.addSource(srcDeviceDesc).addSource(outputDesc, { .stream = stream });
3460 status = mpClientInterface->createAudioPatch(patchBuilder.patch(),
Eric Laurentd60560a2015-04-10 11:31:20 -07003461 &afPatchHandle,
3462 0);
3463 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3464 status, afPatchHandle);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003465 sourceDesc->patchDesc()->mPatch = *patchBuilder.patch();
Eric Laurentd60560a2015-04-10 11:31:20 -07003466 if (status != NO_ERROR) {
3467 ALOGW("%s patch panel could not connect device patch, error %d",
3468 __FUNCTION__, status);
3469 return INVALID_OPERATION;
3470 }
3471 uint32_t delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07003472 status = startSource(outputDesc, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003473
3474 if (status != NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003475 mpClientInterface->releaseAudioPatch(sourceDesc->patchDesc()->mAfPatchHandle, 0);
Eric Laurentd60560a2015-04-10 11:31:20 -07003476 return status;
3477 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003478 sourceDesc->setSwOutput(outputDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003479 if (delayMs != 0) {
3480 usleep(delayMs * 1000);
3481 }
3482 }
3483
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003484 sourceDesc->patchDesc()->mAfPatchHandle = afPatchHandle;
3485 addAudioPatch(sourceDesc->patchDesc()->mHandle, sourceDesc->patchDesc());
Eric Laurentd60560a2015-04-10 11:31:20 -07003486
3487 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003488}
3489
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003490status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07003491{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003492 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
3493 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003494 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003495 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003496 return BAD_VALUE;
3497 }
3498 status_t status = disconnectAudioSource(sourceDesc);
3499
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003500 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003501 return status;
3502}
3503
Andy Hung2ddee192015-12-18 17:34:44 -08003504status_t AudioPolicyManager::setMasterMono(bool mono)
3505{
3506 if (mMasterMono == mono) {
3507 return NO_ERROR;
3508 }
3509 mMasterMono = mono;
3510 // if enabling mono we close all offloaded devices, which will invalidate the
3511 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3512 // for recreating the new AudioTrack as non-offloaded PCM.
3513 //
3514 // If disabling mono, we leave all tracks as is: we don't know which clients
3515 // and tracks are able to be recreated as offloaded. The next "song" should
3516 // play back offloaded.
3517 if (mMasterMono) {
3518 Vector<audio_io_handle_t> offloaded;
3519 for (size_t i = 0; i < mOutputs.size(); ++i) {
3520 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3521 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3522 offloaded.push(desc->mIoHandle);
3523 }
3524 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003525 for (const auto& handle : offloaded) {
3526 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003527 }
3528 }
3529 // update master mono for all remaining outputs
3530 for (size_t i = 0; i < mOutputs.size(); ++i) {
3531 updateMono(mOutputs.keyAt(i));
3532 }
3533 return NO_ERROR;
3534}
3535
3536status_t AudioPolicyManager::getMasterMono(bool *mono)
3537{
3538 *mono = mMasterMono;
3539 return NO_ERROR;
3540}
3541
Eric Laurentac9cef52017-06-09 15:46:26 -07003542float AudioPolicyManager::getStreamVolumeDB(
3543 audio_stream_type_t stream, int index, audio_devices_t device)
3544{
3545 return computeVolume(stream, index, device);
3546}
3547
jiabin81772902018-04-02 17:52:27 -07003548status_t AudioPolicyManager::getSupportedFormats(audio_io_handle_t ioHandle,
3549 FormatVector& formats) {
3550 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
3551 return BAD_VALUE;
3552 }
3553 String8 reply;
3554 reply = mpClientInterface->getParameters(
3555 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
3556 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
3557 AudioParameter repliedParameters(reply);
3558 if (repliedParameters.get(
3559 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
3560 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
3561 return BAD_VALUE;
3562 }
3563 for (auto format : formatsFromString(reply.string())) {
3564 // Only AUDIO_FORMAT_AAC_LC will be used in Settings UI for all AAC formats.
3565 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3566 if (format == AAC_FORMATS[i]) {
3567 format = AUDIO_FORMAT_AAC_LC;
3568 break;
3569 }
3570 }
3571 bool exist = false;
3572 for (size_t i = 0; i < formats.size(); i++) {
3573 if (format == formats[i]) {
3574 exist = true;
3575 break;
3576 }
3577 }
3578 bool isSurroundFormat = false;
3579 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3580 if (SURROUND_FORMATS[i] == format) {
3581 isSurroundFormat = true;
3582 break;
3583 }
3584 }
3585 if (!exist && isSurroundFormat) {
3586 formats.add(format);
3587 }
3588 }
3589 return NO_ERROR;
3590}
3591
3592status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3593 audio_format_t *surroundFormats,
3594 bool *surroundFormatsEnabled,
3595 bool reported)
3596{
3597 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3598 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3599 return BAD_VALUE;
3600 }
3601 ALOGV("getSurroundFormats() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
3602 *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
3603
3604 // Only return value if there is HDMI output.
3605 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3606 return INVALID_OPERATION;
3607 }
3608
3609 size_t formatsWritten = 0;
3610 size_t formatsMax = *numSurroundFormats;
3611 *numSurroundFormats = 0;
3612 FormatVector formats;
3613 if (reported) {
3614 // Only get surround formats which are reported by device.
3615 // First list already open outputs that can be routed to this device
3616 audio_devices_t device = AUDIO_DEVICE_OUT_HDMI;
3617 SortedVector<audio_io_handle_t> outputs;
3618 bool reportedFormatFound = false;
3619 status_t status;
3620 sp<SwAudioOutputDescriptor> desc;
3621 for (size_t i = 0; i < mOutputs.size(); i++) {
3622 desc = mOutputs.valueAt(i);
3623 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
3624 outputs.add(mOutputs.keyAt(i));
3625 }
3626 }
3627 // Open an output to query dynamic parameters.
Mikhail Naganov708e0382018-05-30 09:53:04 -07003628 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003629 AUDIO_DEVICE_OUT_HDMI);
3630 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3631 String8 address = hdmiOutputDevices[i]->mAddress;
3632 for (const auto& hwModule : mHwModules) {
3633 for (size_t i = 0; i < hwModule->getOutputProfiles().size(); i++) {
3634 sp<IOProfile> profile = hwModule->getOutputProfiles()[i];
3635 if (profile->supportDevice(AUDIO_DEVICE_OUT_HDMI) &&
3636 profile->supportDeviceAddress(address)) {
3637 size_t j;
3638 for (j = 0; j < outputs.size(); j++) {
3639 desc = mOutputs.valueFor(outputs.itemAt(j));
3640 if (!desc->isDuplicated() && desc->mProfile == profile) {
3641 break;
3642 }
3643 }
3644 if (j != outputs.size()) {
3645 status = getSupportedFormats(outputs.itemAt(j), formats);
3646 reportedFormatFound |= (status == NO_ERROR);
3647 continue;
3648 }
3649
3650 if (!profile->canOpenNewIo()) {
3651 ALOGW("Max Output number %u already opened for this profile %s",
3652 profile->maxOpenCount, profile->getTagName().c_str());
3653 continue;
3654 }
3655
3656 ALOGV("opening output for device %08x with params %s profile %p name %s",
3657 device, address.string(), profile.get(), profile->getName().string());
3658 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
3659 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3660 status_t status = desc->open(nullptr, device, address,
3661 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE,
3662 &output);
3663
3664 if (status == NO_ERROR) {
3665 status = getSupportedFormats(output, formats);
3666 reportedFormatFound |= (status == NO_ERROR);
3667 desc->close();
3668 output = AUDIO_IO_HANDLE_NONE;
3669 }
3670 }
3671 }
3672 }
3673 }
3674
3675 if (!reportedFormatFound) {
3676 return UNKNOWN_ERROR;
3677 }
3678 } else {
3679 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3680 formats.add(SURROUND_FORMATS[i]);
3681 }
3682 }
3683 for (size_t i = 0; i < formats.size(); i++) {
3684 if (formatsWritten < formatsMax) {
3685 surroundFormats[formatsWritten] = formats[i];
3686 bool formatEnabled = false;
3687 if (formats[i] == AUDIO_FORMAT_AAC_LC) {
3688 for (size_t j = 0; j < ARRAY_SIZE(AAC_FORMATS); j++) {
3689 formatEnabled =
3690 mSurroundFormats.find(AAC_FORMATS[i]) != mSurroundFormats.end();
3691 break;
3692 }
3693 } else {
3694 formatEnabled = mSurroundFormats.find(formats[i]) != mSurroundFormats.end();
3695 }
3696 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3697 }
3698 (*numSurroundFormats)++;
3699 }
3700 return NO_ERROR;
3701}
3702
3703status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3704{
3705 // Check if audio format is a surround formats.
3706 bool isSurroundFormat = false;
3707 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3708 if (audioFormat == SURROUND_FORMATS[i]) {
3709 isSurroundFormat = true;
3710 break;
3711 }
3712 }
3713 if (!isSurroundFormat) {
3714 return BAD_VALUE;
3715 }
3716
3717 // Should only be called when MANUAL.
3718 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3719 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
3720 if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3721 return INVALID_OPERATION;
3722 }
3723
3724 if ((mSurroundFormats.find(audioFormat) != mSurroundFormats.end() && enabled)
3725 || (mSurroundFormats.find(audioFormat) == mSurroundFormats.end() && !enabled)) {
3726 return NO_ERROR;
3727 }
3728
3729 // The operation is valid only when there is HDMI output available.
3730 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3731 return INVALID_OPERATION;
3732 }
3733
3734 if (enabled) {
3735 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3736 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3737 mSurroundFormats.insert(AAC_FORMATS[i]);
3738 }
3739 } else {
3740 mSurroundFormats.insert(audioFormat);
3741 }
3742 } else {
3743 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3744 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3745 mSurroundFormats.erase(AAC_FORMATS[i]);
3746 }
3747 } else {
3748 mSurroundFormats.erase(audioFormat);
3749 }
3750 }
3751
3752 sp<SwAudioOutputDescriptor> outputDesc;
3753 bool profileUpdated = false;
Mikhail Naganov708e0382018-05-30 09:53:04 -07003754 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003755 AUDIO_DEVICE_OUT_HDMI);
3756 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3757 // Simulate reconnection to update enabled surround sound formats.
3758 String8 address = hdmiOutputDevices[i]->mAddress;
3759 String8 name = hdmiOutputDevices[i]->getName();
3760 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3761 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3762 address.c_str(),
3763 name.c_str());
3764 if (status != NO_ERROR) {
3765 continue;
3766 }
3767 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3768 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3769 address.c_str(),
3770 name.c_str());
3771 profileUpdated |= (status == NO_ERROR);
3772 }
Mikhail Naganov708e0382018-05-30 09:53:04 -07003773 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003774 AUDIO_DEVICE_IN_HDMI);
3775 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3776 // Simulate reconnection to update enabled surround sound formats.
3777 String8 address = hdmiInputDevices[i]->mAddress;
3778 String8 name = hdmiInputDevices[i]->getName();
3779 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3780 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3781 address.c_str(),
3782 name.c_str());
3783 if (status != NO_ERROR) {
3784 continue;
3785 }
3786 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3787 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3788 address.c_str(),
3789 name.c_str());
3790 profileUpdated |= (status == NO_ERROR);
3791 }
3792
3793 // Undo the surround formats change due to no audio profiles updated.
3794 if (!profileUpdated) {
3795 if (enabled) {
3796 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3797 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3798 mSurroundFormats.erase(AAC_FORMATS[i]);
3799 }
3800 } else {
3801 mSurroundFormats.erase(audioFormat);
3802 }
3803 } else {
3804 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3805 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3806 mSurroundFormats.insert(AAC_FORMATS[i]);
3807 }
3808 } else {
3809 mSurroundFormats.insert(audioFormat);
3810 }
3811 }
3812 }
3813
3814 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3815}
3816
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003817void AudioPolicyManager::setRecordSilenced(uid_t uid, bool silenced)
3818{
3819 ALOGV("AudioPolicyManager:setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
3820
3821 Vector<sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
3822 for (size_t i = 0; i < activeInputs.size(); i++) {
3823 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
Eric Laurent8f42ea12018-08-08 09:08:25 -07003824 RecordClientVector clients = activeDesc->clientsList(true /*activeOnly*/);
3825 for (const auto& client : clients) {
3826 if (uid == client->uid()) {
3827 client->setSilenced(silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003828 }
3829 }
3830 }
3831}
3832
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003833status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003834{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003835 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003836
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003837 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003838 if (patchDesc == 0) {
3839 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003840 sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003841 return BAD_VALUE;
3842 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003843 removeAudioPatch(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003844
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003845 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003846 if (swOutputDesc != 0) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003847 status_t status = stopSource(swOutputDesc, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08003848 if (status == NO_ERROR) {
3849 swOutputDesc->stop();
3850 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003851 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3852 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003853 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003854 if (hwOutputDesc != 0) {
3855 // release patch between src device and output device
3856 // close Hwoutput and remove from mHwOutputs
3857 } else {
3858 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3859 }
3860 }
3861 return NO_ERROR;
3862}
3863
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003864sp<SourceClientDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
Eric Laurentd60560a2015-04-10 11:31:20 -07003865 audio_io_handle_t output, routing_strategy strategy)
3866{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003867 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07003868 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003869 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3870 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003871 routing_strategy sourceStrategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003872 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003873 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3874 source = sourceDesc;
3875 break;
3876 }
3877 }
3878 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003879}
3880
Eric Laurente552edb2014-03-10 17:42:56 -07003881// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003882// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003883// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003884uint32_t AudioPolicyManager::nextAudioPortGeneration()
3885{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003886 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003887}
3888
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003889#ifdef USE_XML_AUDIO_POLICY_CONF
3890// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3891static const char *kConfigLocationList[] =
3892 {"/odm/etc", "/vendor/etc", "/system/etc"};
3893static const int kConfigLocationListSize =
3894 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3895
3896static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3897 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07003898 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003899 status_t ret;
3900
Petri Gyntherf497f292018-04-17 18:46:10 -07003901 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
3902 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
3903 // A2DP offload supported but disabled: try to use special XML file
3904 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
3905 }
3906 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3907
3908 for (const char* fileName : fileNames) {
3909 for (int i = 0; i < kConfigLocationListSize; i++) {
3910 PolicySerializer serializer;
3911 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
3912 "%s/%s", kConfigLocationList[i], fileName);
3913 ret = serializer.deserialize(audioPolicyXmlConfigFile, config);
3914 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003915 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07003916 return ret;
3917 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003918 }
3919 }
3920 return ret;
3921}
3922#endif
3923
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003924AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
3925 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07003926 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07003927 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003928 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07003929 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003930 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003931#ifdef USE_XML_AUDIO_POLICY_CONF
3932 mVolumeCurves(new VolumeCurvesCollection()),
3933 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08003934 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003935#else
3936 mVolumeCurves(new StreamDescriptorCollection()),
3937 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
3938 mDefaultOutputDevice),
3939#endif
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003940 mAudioPortGeneration(1),
3941 mBeaconMuteRefCount(0),
3942 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003943 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003944 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003945 mMasterMono(false),
Chris Thornton2b864642017-06-27 21:26:07 -07003946 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE),
3947 mHasComputedSoundTriggerSupportsConcurrentCapture(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003948{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003949}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003950
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003951AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
3952 : AudioPolicyManager(clientInterface, false /*forTesting*/)
3953{
3954 loadConfig();
3955 initialize();
3956}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003957
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003958void AudioPolicyManager::loadConfig() {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003959#ifdef USE_XML_AUDIO_POLICY_CONF
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003960 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003961#else
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003962 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, getConfig()) != NO_ERROR)
3963 && (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, getConfig()) != NO_ERROR)) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003964#endif
3965 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003966 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01003967 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003968}
3969
3970status_t AudioPolicyManager::initialize() {
3971 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01003972
3973 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003974 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3975 if (!engineInstance) {
3976 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003977 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003978 }
3979 // Retrieve the Policy Manager Interface
3980 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3981 if (mEngine == NULL) {
3982 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003983 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003984 }
3985 mEngine->setObserver(this);
3986 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003987 if (status != NO_ERROR) {
3988 LOG_FATAL("Policy engine not initialized(err=%d)", status);
3989 return status;
3990 }
François Gaffie2110e042015-03-24 08:41:51 +01003991
Eric Laurent3a4311c2014-03-17 12:00:47 -07003992 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003993 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003994 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3995 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Mikhail Naganovd4120142017-12-06 15:49:22 -08003996 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003997 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08003998 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
3999 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07004000 continue;
4001 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08004002 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07004003 // open all output streams needed to access attached devices
4004 // except for direct output streams that are only opened when they are actually
4005 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07004006 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004007 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004008 if (!outProfile->canOpenNewIo()) {
4009 ALOGE("Invalid Output profile max open count %u for profile %s",
4010 outProfile->maxOpenCount, outProfile->getTagName().c_str());
4011 continue;
4012 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004013 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004014 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004015 continue;
4016 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004017 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004018 mTtsOutputAvailable = true;
4019 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004020
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004021 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07004022 continue;
4023 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004024 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01004025 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
4026 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07004027 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004028 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07004029 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004030 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07004031 }
Eric Laurentd78f1532014-09-16 16:38:20 -07004032 if ((profileType & outputDeviceTypes) == 0) {
4033 continue;
4034 }
Eric Laurentc75307b2015-03-17 15:29:32 -07004035 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
4036 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07004037 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov708e0382018-05-30 09:53:04 -07004038 const DeviceVector &devicesForType = supportedDevices.getDevicesFromTypeMask(
4039 profileType);
Eric Laurentc40d9692016-04-13 19:14:13 -07004040 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
4041 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07004042 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004043 status_t status = outputDesc->open(nullptr, profileType, address,
4044 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07004045
4046 if (status != NO_ERROR) {
4047 ALOGW("Cannot open output stream for device %08x on hw module %s",
4048 outputDesc->mDevice,
Mikhail Naganovd4120142017-12-06 15:49:22 -08004049 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07004050 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004051 for (const auto& dev : supportedDevices) {
4052 ssize_t index = mAvailableOutputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07004053 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08004054 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004055 mAvailableOutputDevices[index]->attach(hwModule);
Eric Laurentd78f1532014-09-16 16:38:20 -07004056 }
4057 }
4058 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004059 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004060 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07004061 }
4062 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07004063 setOutputDevice(outputDesc,
Eric Laurentfe231122017-11-17 17:48:06 -08004064 profileType,
Eric Laurentc40d9692016-04-13 19:14:13 -07004065 true,
4066 0,
4067 NULL,
Eric Laurentfe231122017-11-17 17:48:06 -08004068 address);
Eric Laurentd78f1532014-09-16 16:38:20 -07004069 }
Eric Laurente552edb2014-03-10 17:42:56 -07004070 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004071 // open input streams needed to access attached devices to validate
4072 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004073 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004074 if (!inProfile->canOpenNewIo()) {
4075 ALOGE("Invalid Input profile max open count %u for profile %s",
4076 inProfile->maxOpenCount, inProfile->getTagName().c_str());
4077 continue;
4078 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004079 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004080 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004081 continue;
4082 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004083 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07004084 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004085 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
4086
Eric Laurentd78f1532014-09-16 16:38:20 -07004087 if ((profileType & inputDeviceTypes) == 0) {
4088 continue;
4089 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08004090 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08004091 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004092
Mikhail Naganov708e0382018-05-30 09:53:04 -07004093 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(profileType);
Eric Laurent53b810e2017-12-10 17:25:10 -08004094 // the inputs vector must be of size >= 1, but we don't want to crash here
4095 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
4096 : String8("");
4097 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
4098 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
4099
Eric Laurentd78f1532014-09-16 16:38:20 -07004100 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004101 status_t status = inputDesc->open(nullptr,
4102 profileType,
Eric Laurent53b810e2017-12-10 17:25:10 -08004103 address,
Eric Laurentfe231122017-11-17 17:48:06 -08004104 AUDIO_SOURCE_MIC,
4105 AUDIO_INPUT_FLAG_NONE,
4106 &input);
Eric Laurentd78f1532014-09-16 16:38:20 -07004107
4108 if (status == NO_ERROR) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004109 for (const auto& dev : inProfile->getSupportedDevices()) {
4110 ssize_t index = mAvailableInputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07004111 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07004112 if (index >= 0) {
4113 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
4114 if (!devDesc->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004115 devDesc->attach(hwModule);
Eric Laurent83efe1c2017-07-09 16:51:08 -07004116 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07004117 }
Eric Laurentd78f1532014-09-16 16:38:20 -07004118 }
4119 }
Eric Laurentfe231122017-11-17 17:48:06 -08004120 inputDesc->close();
Eric Laurentd78f1532014-09-16 16:38:20 -07004121 } else {
4122 ALOGW("Cannot open input stream for device %08x on hw module %s",
Eric Laurentfe231122017-11-17 17:48:06 -08004123 profileType,
Mikhail Naganovd4120142017-12-06 15:49:22 -08004124 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07004125 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004126 }
4127 }
4128 // make sure all attached devices have been allocated a unique ID
4129 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004130 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004131 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004132 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
4133 continue;
4134 }
François Gaffie2110e042015-03-24 08:41:51 +01004135 // The device is now validated and can be appended to the available devices of the engine
4136 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
4137 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004138 i++;
4139 }
4140 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004141 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01004142 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004143 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
4144 continue;
4145 }
François Gaffie2110e042015-03-24 08:41:51 +01004146 // The device is now validated and can be appended to the available devices of the engine
4147 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
4148 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004149 i++;
4150 }
4151 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004152 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01004153 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004154 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004155 }
jiabin9ff780e2018-03-19 18:19:52 -07004156 // If microphones address is empty, set it according to device type
4157 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
4158 if (mAvailableInputDevices[i]->mAddress.isEmpty()) {
4159 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
4160 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
4161 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
4162 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BACK_MICROPHONE_ADDRESS);
4163 }
4164 }
4165 }
Eric Laurente552edb2014-03-10 17:42:56 -07004166
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004167 if (mPrimaryOutput == 0) {
4168 ALOGE("Failed to open primary output");
4169 status = NO_INIT;
4170 }
Eric Laurente552edb2014-03-10 17:42:56 -07004171
4172 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004173 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004174}
4175
Eric Laurente0720872014-03-11 09:30:41 -07004176AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004177{
Eric Laurente552edb2014-03-10 17:42:56 -07004178 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004179 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004180 }
4181 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004182 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004183 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004184 mAvailableOutputDevices.clear();
4185 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004186 mOutputs.clear();
4187 mInputs.clear();
4188 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004189 mHwModulesAll.clear();
jiabin81772902018-04-02 17:52:27 -07004190 mSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004191}
4192
Eric Laurente0720872014-03-11 09:30:41 -07004193status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004194{
Eric Laurent87ffa392015-05-22 10:32:38 -07004195 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004196}
4197
Eric Laurente552edb2014-03-10 17:42:56 -07004198// ---
4199
Eric Laurent98e38192018-02-15 18:31:53 -08004200void AudioPolicyManager::addOutput(audio_io_handle_t output,
4201 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004202{
Eric Laurent1c333e22014-05-20 10:48:17 -07004203 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08004204 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004205 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004206 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004207 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004208}
4209
François Gaffie53615e22015-03-19 09:24:12 +01004210void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4211{
4212 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004213 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004214}
4215
Eric Laurent98e38192018-02-15 18:31:53 -08004216void AudioPolicyManager::addInput(audio_io_handle_t input,
4217 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004218{
Eric Laurent1c333e22014-05-20 10:48:17 -07004219 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004220 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004221}
Eric Laurente552edb2014-03-10 17:42:56 -07004222
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004223void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08004224 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004225 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004226 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08004227 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004228 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08004229 if (devDesc != 0) {
4230 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
4231 desc->mIoHandle, address.string());
4232 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004233 }
4234}
4235
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004236status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004237 audio_policy_dev_state_t state,
4238 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004239 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07004240{
François Gaffie53615e22015-03-19 09:24:12 +01004241 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07004242 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004243
4244 if (audio_device_is_digital(device)) {
4245 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004246 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004247 }
Eric Laurente552edb2014-03-10 17:42:56 -07004248
Eric Laurent3b73df72014-03-11 09:06:29 -07004249 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004250 // first list already open outputs that can be routed to this device
4251 for (size_t i = 0; i < mOutputs.size(); i++) {
4252 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07004253 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004254 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004255 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
4256 outputs.add(mOutputs.keyAt(i));
4257 } else {
4258 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08004259 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004260 }
Eric Laurente552edb2014-03-10 17:42:56 -07004261 }
4262 }
4263 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004264 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004265 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004266 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4267 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004268 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004269 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004270 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004271 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004272 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4273 j, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004274 }
Eric Laurente552edb2014-03-10 17:42:56 -07004275 }
4276 }
4277 }
4278
Eric Laurent7b279bb2015-12-14 10:18:23 -08004279 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004280
Eric Laurente552edb2014-03-10 17:42:56 -07004281 if (profiles.isEmpty() && outputs.isEmpty()) {
4282 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4283 return BAD_VALUE;
4284 }
4285
4286 // open outputs for matching profiles if needed. Direct outputs are also opened to
4287 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4288 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004289 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004290
4291 // nothing to do if one output is already opened for this profile
4292 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004293 for (j = 0; j < outputs.size(); j++) {
4294 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004295 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004296 // matching profile: save the sample rates, format and channel masks supported
4297 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07004298 if (audio_device_is_digital(device)) {
4299 devDesc->importAudioPort(profile);
4300 }
Eric Laurente552edb2014-03-10 17:42:56 -07004301 break;
4302 }
4303 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004304 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004305 continue;
4306 }
4307
Eric Laurent3974e3b2017-12-07 17:58:43 -08004308 if (!profile->canOpenNewIo()) {
4309 ALOGW("Max Output number %u already opened for this profile %s",
4310 profile->maxOpenCount, profile->getTagName().c_str());
4311 continue;
4312 }
4313
Eric Laurent83efe1c2017-07-09 16:51:08 -07004314 ALOGV("opening output for device %08x with params %s profile %p name %s",
4315 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004316 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004317 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004318 status_t status = desc->open(nullptr, device, address,
4319 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004320
Eric Laurentfe231122017-11-17 17:48:06 -08004321 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004322 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004323 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004324 char *param = audio_device_address_to_parameter(device, address);
4325 mpClientInterface->setParameters(output, String8(param));
4326 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004327 }
Phil Burk00eeb322016-03-31 12:41:00 -07004328 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004329 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004330 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004331 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004332 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004333 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004334 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004335 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004336 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4337 profile->pickAudioProfile(
4338 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004339 config.offload_info.sample_rate = config.sample_rate;
4340 config.offload_info.channel_mask = config.channel_mask;
4341 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004342
4343 status_t status = desc->open(&config, device, address, AUDIO_STREAM_DEFAULT,
4344 AUDIO_OUTPUT_FLAG_NONE, &output);
4345 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004346 output = AUDIO_IO_HANDLE_NONE;
4347 }
Eric Laurentd4692962014-05-05 18:13:44 -07004348 }
4349
Eric Laurentcf2c0212014-07-25 16:20:43 -07004350 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004351 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01004352 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004353 sp<AudioPolicyMix> policyMix;
4354 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004355 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
4356 address.string());
4357 }
François Gaffie036e1e92015-03-19 10:16:24 +01004358 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07004359 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01004360
Eric Laurent87ffa392015-05-22 10:32:38 -07004361 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4362 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004363 // no duplicated output for direct outputs and
4364 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004365 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004366
Eric Laurentd4692962014-05-05 18:13:44 -07004367 //TODO: configure audio effect output stage here
4368
4369 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004370 sp<SwAudioOutputDescriptor> dupOutputDesc =
4371 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4372 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4373 &duplicatedOutput);
4374 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004375 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004376 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004377 } else {
4378 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004379 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004380 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004381 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004382 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004383 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004384 }
Eric Laurente552edb2014-03-10 17:42:56 -07004385 }
4386 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004387 } else {
4388 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004389 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004390 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004391 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004392 profiles.removeAt(profile_index);
4393 profile_index--;
4394 } else {
4395 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004396 // Load digital format info only for digital devices
4397 if (audio_device_is_digital(device)) {
4398 devDesc->importAudioPort(profile);
4399 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004400
François Gaffie53615e22015-03-19 09:24:12 +01004401 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004402 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4403 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004404 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004405 NULL/*patch handle*/, address.string());
4406 }
Eric Laurente552edb2014-03-10 17:42:56 -07004407 ALOGV("checkOutputsForDevice(): adding output %d", output);
4408 }
4409 }
4410
4411 if (profiles.isEmpty()) {
4412 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4413 return BAD_VALUE;
4414 }
Eric Laurentd4692962014-05-05 18:13:44 -07004415 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004416 // check if one opened output is not needed any more after disconnecting one device
4417 for (size_t i = 0; i < mOutputs.size(); i++) {
4418 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004419 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004420 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004421 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004422 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004423 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004424 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004425 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4426 mOutputs.keyAt(i));
4427 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004428 }
Eric Laurente552edb2014-03-10 17:42:56 -07004429 }
4430 }
Eric Laurentd4692962014-05-05 18:13:44 -07004431 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004432 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004433 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4434 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004435 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004436 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004437 "clearing direct output profile %zu on module %s",
4438 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004439 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004440 }
4441 }
4442 }
4443 }
4444 return NO_ERROR;
4445}
4446
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004447status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004448 audio_policy_dev_state_t state,
4449 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004450 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004451{
Paul McLean9080a4c2015-06-18 08:24:02 -07004452 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004453 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004454
4455 if (audio_device_is_digital(device)) {
4456 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004457 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004458 }
4459
Eric Laurentd4692962014-05-05 18:13:44 -07004460 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4461 // first list already open inputs that can be routed to this device
4462 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4463 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004464 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004465 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4466 inputs.add(mInputs.keyAt(input_index));
4467 }
4468 }
4469
4470 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004471 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004472 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004473 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004474 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004475 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004476 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004477
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004478 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004479 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004480 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004481 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004482 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4483 profile_index, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004484 }
Eric Laurentd4692962014-05-05 18:13:44 -07004485 }
4486 }
4487 }
4488
4489 if (profiles.isEmpty() && inputs.isEmpty()) {
4490 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4491 return BAD_VALUE;
4492 }
4493
4494 // open inputs for matching profiles if needed. Direct inputs are also opened to
4495 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4496 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4497
Eric Laurent1c333e22014-05-20 10:48:17 -07004498 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004499
Eric Laurentd4692962014-05-05 18:13:44 -07004500 // nothing to do if one input is already opened for this profile
4501 size_t input_index;
4502 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4503 desc = mInputs.valueAt(input_index);
4504 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004505 if (audio_device_is_digital(device)) {
4506 devDesc->importAudioPort(profile);
4507 }
Eric Laurentd4692962014-05-05 18:13:44 -07004508 break;
4509 }
4510 }
4511 if (input_index != mInputs.size()) {
4512 continue;
4513 }
4514
Eric Laurent3974e3b2017-12-07 17:58:43 -08004515 if (!profile->canOpenNewIo()) {
4516 ALOGW("Max Input number %u already opened for this profile %s",
4517 profile->maxOpenCount, profile->getTagName().c_str());
4518 continue;
4519 }
4520
Eric Laurentfe231122017-11-17 17:48:06 -08004521 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004522 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004523 status_t status = desc->open(nullptr,
4524 device,
4525 address,
4526 AUDIO_SOURCE_MIC,
4527 AUDIO_INPUT_FLAG_NONE,
4528 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004529
Eric Laurentcf2c0212014-07-25 16:20:43 -07004530 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004531 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004532 char *param = audio_device_address_to_parameter(device, address);
4533 mpClientInterface->setParameters(input, String8(param));
4534 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004535 }
Phil Burk00eeb322016-03-31 12:41:00 -07004536 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004537 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004538 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004539 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004540 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004541 }
4542
4543 if (input != 0) {
4544 addInput(input, desc);
4545 }
4546 } // endif input != 0
4547
Eric Laurentcf2c0212014-07-25 16:20:43 -07004548 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004549 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004550 profiles.removeAt(profile_index);
4551 profile_index--;
4552 } else {
4553 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004554 if (audio_device_is_digital(device)) {
4555 devDesc->importAudioPort(profile);
4556 }
Eric Laurentd4692962014-05-05 18:13:44 -07004557 ALOGV("checkInputsForDevice(): adding input %d", input);
4558 }
4559 } // end scan profiles
4560
4561 if (profiles.isEmpty()) {
4562 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4563 return BAD_VALUE;
4564 }
4565 } else {
4566 // Disconnect
4567 // check if one opened input is not needed any more after disconnecting one device
4568 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4569 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004570 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004571 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4572 mInputs.keyAt(input_index));
4573 inputs.add(mInputs.keyAt(input_index));
4574 }
4575 }
4576 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004577 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004578 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004579 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004580 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004581 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004582 if (profile->supportDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004583 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4584 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004585 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004586 }
4587 }
4588 }
4589 } // end disconnect
4590
4591 return NO_ERROR;
4592}
4593
4594
Eric Laurente0720872014-03-11 09:30:41 -07004595void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004596{
4597 ALOGV("closeOutput(%d)", output);
4598
Eric Laurentc75307b2015-03-17 15:29:32 -07004599 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004600 if (outputDesc == NULL) {
4601 ALOGW("closeOutput() unknown output %d", output);
4602 return;
4603 }
François Gaffie036e1e92015-03-19 10:16:24 +01004604 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004605
Eric Laurente552edb2014-03-10 17:42:56 -07004606 // look for duplicated outputs connected to the output being removed.
4607 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004608 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004609 if (dupOutputDesc->isDuplicated() &&
4610 (dupOutputDesc->mOutput1 == outputDesc ||
4611 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004612 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004613 if (dupOutputDesc->mOutput1 == outputDesc) {
4614 outputDesc2 = dupOutputDesc->mOutput2;
4615 } else {
4616 outputDesc2 = dupOutputDesc->mOutput1;
4617 }
4618 // As all active tracks on duplicated output will be deleted,
4619 // and as they were also referenced on the other output, the reference
4620 // count for their stream type must be adjusted accordingly on
4621 // the other output.
Eric Laurent733ce942017-12-07 12:18:25 -08004622 bool wasActive = outputDesc2->isActive();
Eric Laurent3b73df72014-03-11 09:06:29 -07004623 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004624 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07004625 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004626 }
Eric Laurent733ce942017-12-07 12:18:25 -08004627 // stop() will be a no op if the output is still active but is needed in case all
4628 // active streams refcounts where cleared above
4629 if (wasActive) {
4630 outputDesc2->stop();
4631 }
Eric Laurente552edb2014-03-10 17:42:56 -07004632 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4633 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4634
4635 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004636 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004637 }
4638 }
4639
Eric Laurent05b90f82014-08-27 15:32:29 -07004640 nextAudioPortGeneration();
4641
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004642 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004643 if (index >= 0) {
4644 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004645 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004646 mAudioPatches.removeItemsAt(index);
4647 mpClientInterface->onAudioPatchListUpdate();
4648 }
4649
Eric Laurentfe231122017-11-17 17:48:06 -08004650 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004651
François Gaffie53615e22015-03-19 09:24:12 +01004652 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004653 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004654}
4655
4656void AudioPolicyManager::closeInput(audio_io_handle_t input)
4657{
4658 ALOGV("closeInput(%d)", input);
4659
4660 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4661 if (inputDesc == NULL) {
4662 ALOGW("closeInput() unknown input %d", input);
4663 return;
4664 }
4665
Eric Laurent6a94d692014-05-20 11:18:06 -07004666 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004667
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004668 audio_devices_t device = inputDesc->mDevice;
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004669 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004670 if (index >= 0) {
4671 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004672 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004673 mAudioPatches.removeItemsAt(index);
4674 mpClientInterface->onAudioPatchListUpdate();
4675 }
4676
Eric Laurentfe231122017-11-17 17:48:06 -08004677 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004678 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004679
4680 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
4681 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
4682 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
4683 SoundTrigger::setCaptureState(false);
4684 }
Eric Laurente552edb2014-03-10 17:42:56 -07004685}
4686
Eric Laurentc75307b2015-03-17 15:29:32 -07004687SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4688 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004689 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004690{
4691 SortedVector<audio_io_handle_t> outputs;
4692
4693 ALOGVV("getOutputsForDevice() device %04x", device);
4694 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004695 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004696 i, openOutputs.valueAt(i)->isDuplicated(),
4697 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004698 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4699 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4700 outputs.add(openOutputs.keyAt(i));
4701 }
4702 }
4703 return outputs;
4704}
4705
Mikhail Naganov37977152018-07-11 15:54:44 -07004706void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
4707{
4708 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
4709 // output is suspended before any tracks are moved to it
4710 checkA2dpSuspend();
4711 checkOutputForAllStrategies();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004712 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07004713 updateDevicesAndOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004714 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
4715 setMsdPatch();
4716 }
Mikhail Naganov37977152018-07-11 15:54:44 -07004717}
4718
Eric Laurente0720872014-03-11 09:30:41 -07004719void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004720{
4721 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4722 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4723 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4724 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4725
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004726 // also take into account external policy-related changes: add all outputs which are
4727 // associated with policies in the "before" and "after" output vectors
4728 ALOGVV("checkOutputForStrategy(): policy related outputs");
4729 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004730 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004731 if (desc != 0 && desc->mPolicyMix != NULL) {
4732 srcOutputs.add(desc->mIoHandle);
4733 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4734 }
4735 }
4736 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004737 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004738 if (desc != 0 && desc->mPolicyMix != NULL) {
4739 dstOutputs.add(desc->mIoHandle);
4740 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4741 }
4742 }
4743
Mikhail Naganov9de8bd12018-07-23 16:41:31 -07004744 if (srcOutputs != dstOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004745 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4746 // audio from invalidated tracks will be rendered when unmuting
4747 uint32_t maxLatency = 0;
4748 for (audio_io_handle_t srcOut : srcOutputs) {
4749 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4750 if (desc != 0 && maxLatency < desc->latency()) {
4751 maxLatency = desc->latency();
4752 }
4753 }
Eric Laurente552edb2014-03-10 17:42:56 -07004754 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4755 strategy, srcOutputs[0], dstOutputs[0]);
4756 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004757 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004758 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4759 if (desc != 0 && isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004760 setStrategyMute(strategy, true, desc);
Eric Laurentac3a6902018-05-11 16:39:10 -07004761 setStrategyMute(strategy, false, desc, maxLatency * LATENCY_MUTE_FACTOR, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004762 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004763 sp<SourceClientDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004764 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004765 if (source != 0){
4766 connectAudioSource(source);
4767 }
Eric Laurente552edb2014-03-10 17:42:56 -07004768 }
4769
4770 // Move effects associated to this strategy from previous output to new output
4771 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004772 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004773 }
4774 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004775 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004776 if (getStrategy((audio_stream_type_t)i) == strategy) {
4777 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004778 }
4779 }
4780 }
4781}
4782
Eric Laurente0720872014-03-11 09:30:41 -07004783void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004784{
François Gaffie2110e042015-03-24 08:41:51 +01004785 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004786 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004787 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004788 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004789 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004790 checkOutputForStrategy(STRATEGY_SONIFICATION);
4791 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004792 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004793 checkOutputForStrategy(STRATEGY_MEDIA);
4794 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004795 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004796}
4797
Eric Laurente0720872014-03-11 09:30:41 -07004798void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004799{
François Gaffie53615e22015-03-19 09:24:12 +01004800 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004801 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004802 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004803 return;
4804 }
4805
Eric Laurent3a4311c2014-03-17 12:00:47 -07004806 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004807 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4808 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4809 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004810
4811 // if suspended, restore A2DP output if:
4812 // ((SCO device is NOT connected) ||
4813 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4814 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004815 //
Eric Laurentf732e072016-08-03 19:30:28 -07004816 // if not suspended, suspend A2DP output if:
4817 // (SCO device is connected) &&
4818 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4819 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004820 //
4821 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004822 if (!isScoConnected ||
4823 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4824 AUDIO_POLICY_FORCE_BT_SCO) &&
4825 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4826 AUDIO_POLICY_FORCE_BT_SCO) &&
4827 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004828 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004829
4830 mpClientInterface->restoreOutput(a2dpOutput);
4831 mA2dpSuspended = false;
4832 }
4833 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004834 if (isScoConnected &&
4835 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4836 AUDIO_POLICY_FORCE_BT_SCO) ||
4837 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4838 AUDIO_POLICY_FORCE_BT_SCO) ||
4839 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004840 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004841
4842 mpClientInterface->suspendOutput(a2dpOutput);
4843 mA2dpSuspended = true;
4844 }
4845 }
4846}
4847
Eric Laurent97ac8712018-07-27 18:59:02 -07004848template <class IoDescriptor, class Filter>
4849sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4850 IoDescriptor& desc, Filter filter, bool& active, const DeviceVector& devices)
4851{
4852 auto activeClients = desc->clientsList(true /*activeOnly*/);
4853 auto activeClientsWithRoute =
4854 desc->clientsList(true /*activeOnly*/, filter, true /*preferredDevice*/);
4855 active = activeClients.size() > 0;
4856 if (active && activeClients.size() == activeClientsWithRoute.size()) {
4857 return devices.getDeviceFromId(activeClientsWithRoute[0]->preferredDeviceId());
4858 }
4859 return nullptr;
4860}
4861
4862template <class IoCollection, class Filter>
4863sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4864 IoCollection& ioCollection, Filter filter, const DeviceVector& devices)
4865{
4866 sp<DeviceDescriptor> device;
4867 for (size_t i = 0; i < ioCollection.size(); i++) {
4868 auto desc = ioCollection.valueAt(i);
4869 bool active;
4870 sp<DeviceDescriptor> curDevice = findPreferredDevice(desc, filter, active, devices);
4871 if (active && curDevice == nullptr) {
4872 return nullptr;
4873 } else if (curDevice != nullptr) {
4874 device = curDevice;
4875 }
4876 }
4877 return device;
4878}
4879
Eric Laurentc75307b2015-03-17 15:29:32 -07004880audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4881 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004882{
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004883 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004884 if (index >= 0) {
4885 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4886 if (patchDesc->mUid != mUidCached) {
4887 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004888 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004889 return outputDesc->device();
4890 }
4891 }
4892
Eric Laurent97ac8712018-07-27 18:59:02 -07004893 // Honor explicit routing requests only if no client using default routing is active on this
4894 // input: a specific app can not force routing for other apps by setting a preferred device.
4895 bool active; // unused
4896 sp<DeviceDescriptor> deviceDesc =
4897 findPreferredDevice(outputDesc, STRATEGY_NONE, active, mAvailableOutputDevices);
4898 if (deviceDesc != nullptr) {
4899 return deviceDesc->type();
Eric Laurentf3a5a602018-05-22 18:42:55 -07004900 }
4901
Eric Laurente552edb2014-03-10 17:42:56 -07004902 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004903 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004904 // use device for strategy enforced audible
4905 // 2: we are in call or the strategy phone is active on the output:
4906 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004907 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004908 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004909 // 4: the strategy for enforced audible is active but not enforced on the output:
4910 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004911 // 5: the strategy accessibility is active on the output:
4912 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004913 // 6: the strategy "respectful" sonification is active on the output:
4914 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004915 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004916 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004917 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004918 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004919 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004920 // use device for strategy t-t-s
Eric Laurent484e9272018-06-07 17:29:23 -07004921
4922 // FIXME: extend use of isStrategyActiveOnSameModule() to all strategies
4923 // with a refined rule considering mutually exclusive devices (using same backend)
4924 // as opposed to all streams on the same audio HAL module.
Eric Laurent97ac8712018-07-27 18:59:02 -07004925 audio_devices_t device = AUDIO_DEVICE_NONE;
François Gaffiead3183e2015-03-18 16:55:35 +01004926 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004927 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004928 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4929 } else if (isInCall() ||
Eric Laurent484e9272018-06-07 17:29:23 -07004930 isStrategyActiveOnSameModule(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004931 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
Yung Ti Su3e7eb5e2018-06-13 11:48:42 +08004932 } else if (isStrategyActiveOnSameModule(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004933 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004934 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
4935 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004936 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4937 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004938 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004939 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004940 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004941 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004942 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004943 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004944 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004945 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004946 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004947 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004948 }
4949
Eric Laurent1c333e22014-05-20 10:48:17 -07004950 ALOGV("getNewOutputDevice() selected device %x", device);
4951 return device;
4952}
4953
Eric Laurentfb66dd92016-01-28 18:32:03 -08004954audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004955{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004956 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004957
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004958 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004959 if (index >= 0) {
4960 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4961 if (patchDesc->mUid != mUidCached) {
4962 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004963 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004964 return inputDesc->mDevice;
4965 }
4966 }
4967
Eric Laurent97ac8712018-07-27 18:59:02 -07004968 // Honor explicit routing requests only if no client using default routing is active on this
4969 // input: a specific app can not force routing for other apps by setting a preferred device.
4970 bool active;
4971 sp<DeviceDescriptor> deviceDesc =
4972 findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
4973 if (deviceDesc != nullptr) {
4974 return deviceDesc->type();
4975 }
4976
Eric Laurentdc95a252018-04-12 12:46:56 -07004977 // If we are not in call and no client is active on this input, this methods returns
4978 // AUDIO_DEVICE_NONE, causing the patch on the input stream to be released.
Eric Laurentfb66dd92016-01-28 18:32:03 -08004979 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
Eric Laurentdc95a252018-04-12 12:46:56 -07004980 if (source == AUDIO_SOURCE_DEFAULT && isInCall()) {
4981 source = AUDIO_SOURCE_VOICE_COMMUNICATION;
4982 }
4983 if (source != AUDIO_SOURCE_DEFAULT) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08004984 device = getDeviceAndMixForInputSource(source);
4985 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004986
Eric Laurente552edb2014-03-10 17:42:56 -07004987 return device;
4988}
4989
Eric Laurent794fde22016-03-11 09:50:45 -08004990bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4991 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004992 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004993}
4994
Eric Laurente0720872014-03-11 09:30:41 -07004995uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004996 return (uint32_t)getStrategy(stream);
4997}
4998
Eric Laurente0720872014-03-11 09:30:41 -07004999audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005000 // By checking the range of stream before calling getStrategy, we avoid
5001 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
5002 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08005003 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005004 return AUDIO_DEVICE_NONE;
5005 }
Eric Laurent28d09f02016-03-08 10:43:05 -08005006 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08005007 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
5008 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08005009 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07005010 }
Eric Laurent794fde22016-03-11 09:50:45 -08005011 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08005012 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07005013 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005014 for (audio_io_handle_t output : getOutputsForDevice(curDevices, mOutputs)) {
5015 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08005016 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08005017 curDevices |= outputDesc->device();
5018 }
5019 }
5020 devices |= curDevices;
Eric Laurente552edb2014-03-10 17:42:56 -07005021 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005022
5023 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
5024 and doesn't really need to.*/
5025 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
5026 devices |= AUDIO_DEVICE_OUT_SPEAKER;
5027 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
5028 }
Eric Laurente552edb2014-03-10 17:42:56 -07005029 return devices;
5030}
5031
François Gaffie2110e042015-03-24 08:41:51 +01005032routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
5033{
Eric Laurent223fd5c2014-11-11 13:43:36 -08005034 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01005035 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005036}
5037
Eric Laurent97ac8712018-07-27 18:59:02 -07005038routing_strategy AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005039 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005040 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
Eric Laurent97ac8712018-07-27 18:59:02 -07005041 return STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005042 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005043 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
Eric Laurent97ac8712018-07-27 18:59:02 -07005044 return STRATEGY_ENFORCED_AUDIBLE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005045 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005046 // usage to strategy mapping
Eric Laurent97ac8712018-07-27 18:59:02 -07005047 return mEngine->getStrategyForUsage(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005048}
5049
Eric Laurente0720872014-03-11 09:30:41 -07005050void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005051 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005052 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07005053 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
5054 updateDevicesAndOutputs();
5055 break;
5056 default:
5057 break;
5058 }
5059}
5060
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005061uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07005062
5063 // skip beacon mute management if a dedicated TTS output is available
5064 if (mTtsOutputAvailable) {
5065 return 0;
5066 }
5067
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005068 switch(event) {
5069 case STARTING_OUTPUT:
5070 mBeaconMuteRefCount++;
5071 break;
5072 case STOPPING_OUTPUT:
5073 if (mBeaconMuteRefCount > 0) {
5074 mBeaconMuteRefCount--;
5075 }
5076 break;
5077 case STARTING_BEACON:
5078 mBeaconPlayingRefCount++;
5079 break;
5080 case STOPPING_BEACON:
5081 if (mBeaconPlayingRefCount > 0) {
5082 mBeaconPlayingRefCount--;
5083 }
5084 break;
5085 }
5086
5087 if (mBeaconMuteRefCount > 0) {
5088 // any playback causes beacon to be muted
5089 return setBeaconMute(true);
5090 } else {
5091 // no other playback: unmute when beacon starts playing, mute when it stops
5092 return setBeaconMute(mBeaconPlayingRefCount == 0);
5093 }
5094}
5095
5096uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5097 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5098 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5099 // keep track of muted state to avoid repeating mute/unmute operations
5100 if (mBeaconMuted != mute) {
5101 // mute/unmute AUDIO_STREAM_TTS on all outputs
5102 ALOGV("\t muting %d", mute);
5103 uint32_t maxLatency = 0;
5104 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005105 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005106 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07005107 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005108 0 /*delay*/, AUDIO_DEVICE_NONE);
5109 const uint32_t latency = desc->latency() * 2;
5110 if (latency > maxLatency) {
5111 maxLatency = latency;
5112 }
5113 }
5114 mBeaconMuted = mute;
5115 return maxLatency;
5116 }
5117 return 0;
5118}
5119
Eric Laurente0720872014-03-11 09:30:41 -07005120audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01005121 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005122{
Eric Laurent97ac8712018-07-27 18:59:02 -07005123 // Honor explicit routing requests only if all active clients have a preferred route in which
5124 // case the last active client route is used
5125 sp<DeviceDescriptor> deviceDesc = findPreferredDevice(mOutputs, strategy, mAvailableOutputDevices);
5126 if (deviceDesc != nullptr) {
5127 return deviceDesc->type();
Paul McLeanaa981192015-03-21 09:55:15 -07005128 }
5129
Eric Laurente552edb2014-03-10 17:42:56 -07005130 if (fromCache) {
5131 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
5132 strategy, mDeviceForStrategy[strategy]);
5133 return mDeviceForStrategy[strategy];
5134 }
François Gaffie2110e042015-03-24 08:41:51 +01005135 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07005136}
5137
Eric Laurente0720872014-03-11 09:30:41 -07005138void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005139{
5140 for (int i = 0; i < NUM_STRATEGIES; i++) {
5141 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
5142 }
5143 mPreviousOutputs = mOutputs;
5144}
5145
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005146uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005147 audio_devices_t prevDevice,
5148 uint32_t delayMs)
5149{
5150 // mute/unmute strategies using an incompatible device combination
5151 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5152 // if unmuting, unmute only after the specified delay
5153 if (outputDesc->isDuplicated()) {
5154 return 0;
5155 }
5156
5157 uint32_t muteWaitMs = 0;
5158 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07005159 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005160
5161 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
5162 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07005163 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07005164 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
5165 bool doMute = false;
5166
5167 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
5168 doMute = true;
5169 outputDesc->mStrategyMutedByDevice[i] = true;
5170 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
5171 doMute = true;
5172 outputDesc->mStrategyMutedByDevice[i] = false;
5173 }
Eric Laurent99401132014-05-07 19:48:15 -07005174 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005175 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005176 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005177 // skip output if it does not share any device with current output
5178 if ((desc->supportedDevices() & outputDesc->supportedDevices())
5179 == AUDIO_DEVICE_NONE) {
5180 continue;
5181 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005182 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07005183 mute ? "muting" : "unmuting", i, curDevice);
5184 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005185 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005186 if (mute) {
5187 // FIXME: should not need to double latency if volume could be applied
5188 // immediately by the audioflinger mixer. We must account for the delay
5189 // between now and the next time the audioflinger thread for this output
5190 // will process a buffer (which corresponds to one buffer size,
5191 // usually 1/2 or 1/4 of the latency).
5192 if (muteWaitMs < desc->latency() * 2) {
5193 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005194 }
5195 }
5196 }
5197 }
5198 }
5199 }
5200
Eric Laurent99401132014-05-07 19:48:15 -07005201 // temporary mute output if device selection changes to avoid volume bursts due to
5202 // different per device volumes
5203 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005204 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5205 // temporary mute duration is conservatively set to 4 times the reported latency
5206 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5207 if (muteWaitMs < tempMuteWaitMs) {
5208 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005209 }
Eric Laurentdc462862016-07-19 12:29:53 -07005210
Eric Laurent99401132014-05-07 19:48:15 -07005211 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005212 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005213 // make sure that we do not start the temporary mute period too early in case of
5214 // delayed device change
5215 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005216 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07005217 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07005218 }
5219 }
5220 }
5221
Eric Laurente552edb2014-03-10 17:42:56 -07005222 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5223 if (muteWaitMs > delayMs) {
5224 muteWaitMs -= delayMs;
5225 usleep(muteWaitMs * 1000);
5226 return muteWaitMs;
5227 }
5228 return 0;
5229}
5230
Eric Laurentc75307b2015-03-17 15:29:32 -07005231uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005232 audio_devices_t device,
5233 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07005234 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005235 audio_patch_handle_t *patchHandle,
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005236 const char *address,
5237 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005238{
Eric Laurentc75307b2015-03-17 15:29:32 -07005239 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005240 AudioParameter param;
5241 uint32_t muteWaitMs;
5242
5243 if (outputDesc->isDuplicated()) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005244 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs,
5245 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
5246 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs,
5247 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005248 return muteWaitMs;
5249 }
5250 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5251 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07005252 if ((device != AUDIO_DEVICE_NONE) &&
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005253 ((device & outputDesc->supportedDevices()) == AUDIO_DEVICE_NONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005254 return 0;
5255 }
5256
5257 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07005258 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07005259
5260 audio_devices_t prevDevice = outputDesc->mDevice;
5261
Paul McLeanaa981192015-03-21 09:55:15 -07005262 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005263
5264 if (device != AUDIO_DEVICE_NONE) {
5265 outputDesc->mDevice = device;
5266 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005267
5268 // if the outputs are not materially active, there is no need to mute.
5269 if (requiresMuteCheck) {
5270 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
5271 } else {
5272 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5273 muteWaitMs = 0;
5274 }
Eric Laurente552edb2014-03-10 17:42:56 -07005275
5276 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005277 // the requested device is AUDIO_DEVICE_NONE
5278 // OR the requested device is the same as current device
5279 // AND force is not specified
5280 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07005281 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07005282 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
5283 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005284 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005285 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005286 return muteWaitMs;
5287 }
5288
5289 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07005290
Eric Laurente552edb2014-03-10 17:42:56 -07005291 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07005292 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005293 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005294 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07005295 DeviceVector deviceList;
5296 if ((address == NULL) || (strlen(address) == 0)) {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005297 deviceList = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurentc40d9692016-04-13 19:14:13 -07005298 } else {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005299 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
5300 device, String8(address));
5301 if (deviceDesc) deviceList.add(deviceDesc);
Eric Laurentc40d9692016-04-13 19:14:13 -07005302 }
5303
Eric Laurent1c333e22014-05-20 10:48:17 -07005304 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005305 PatchBuilder patchBuilder;
5306 patchBuilder.addSource(outputDesc);
Eric Laurent1c333e22014-05-20 10:48:17 -07005307 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005308 patchBuilder.addSink(deviceList.itemAt(i));
Eric Laurent1c333e22014-05-20 10:48:17 -07005309 }
Mikhail Naganovdc769682018-05-04 15:34:08 -07005310 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005311 }
bryant_liuf5e7e792014-08-19 20:07:05 +08005312
5313 // inform all input as well
5314 for (size_t i = 0; i < mInputs.size(); i++) {
5315 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01005316 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08005317 AudioParameter inputCmd = AudioParameter();
5318 ALOGV("%s: inform input %d of device:%d", __func__,
5319 inputDescriptor->mIoHandle, device);
5320 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
5321 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
5322 inputCmd.toString(),
5323 delayMs);
5324 }
5325 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005326 }
Eric Laurente552edb2014-03-10 17:42:56 -07005327
5328 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07005329 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005330
5331 return muteWaitMs;
5332}
5333
Eric Laurentc75307b2015-03-17 15:29:32 -07005334status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005335 int delayMs,
5336 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005337{
Eric Laurent6a94d692014-05-20 11:18:06 -07005338 ssize_t index;
5339 if (patchHandle) {
5340 index = mAudioPatches.indexOfKey(*patchHandle);
5341 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005342 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005343 }
5344 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005345 return INVALID_OPERATION;
5346 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005347 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5348 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005349 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005350 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005351 removeAudioPatch(patchDesc->mHandle);
5352 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005353 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005354 return status;
5355}
5356
5357status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5358 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005359 bool force,
5360 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005361{
5362 status_t status = NO_ERROR;
5363
Eric Laurent1f2f2232014-06-02 12:01:23 -07005364 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005365 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5366 inputDesc->mDevice = device;
5367
Mikhail Naganov708e0382018-05-30 09:53:04 -07005368 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005369 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005370 PatchBuilder patchBuilder;
5371 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005372 // AUDIO_SOURCE_HOTWORD is for internal use only:
5373 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07005374 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5375 auto result = usecase;
5376 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5377 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5378 }
5379 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07005380 //only one input device for now
Mikhail Naganovdc769682018-05-04 15:34:08 -07005381 addSource(deviceList.itemAt(0));
5382 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005383 }
5384 }
5385 return status;
5386}
5387
Eric Laurent6a94d692014-05-20 11:18:06 -07005388status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5389 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005390{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005391 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005392 ssize_t index;
5393 if (patchHandle) {
5394 index = mAudioPatches.indexOfKey(*patchHandle);
5395 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005396 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005397 }
5398 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005399 return INVALID_OPERATION;
5400 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005401 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5402 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005403 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005404 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005405 removeAudioPatch(patchDesc->mHandle);
5406 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005407 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005408 return status;
5409}
5410
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005411sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005412 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005413 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005414 audio_format_t& format,
5415 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005416 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005417{
5418 // Choose an input profile based on the requested capture parameters: select the first available
5419 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005420 //
5421 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5422 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005423
Glenn Kasten730b9262018-03-29 15:01:26 -07005424 sp<IOProfile> firstInexact;
5425 uint32_t updatedSamplingRate = 0;
5426 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5427 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005428 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005429 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005430 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005431 //updatedFormat = format;
Eric Laurent275e8e92014-11-30 15:14:47 -08005432 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005433 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005434 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005435 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005436 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005437 &channelMask /*updatedChannelMask*/,
5438 // FIXME ugly cast
5439 (audio_output_flags_t) flags,
5440 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005441 return profile;
5442 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005443 if (firstInexact == nullptr && profile->isCompatibleProfile(device, address,
5444 samplingRate,
5445 &updatedSamplingRate,
5446 format,
5447 &updatedFormat,
5448 channelMask,
5449 &updatedChannelMask,
5450 // FIXME ugly cast
5451 (audio_output_flags_t) flags,
5452 false /*exactMatchRequiredForInputFlags*/)) {
5453 firstInexact = profile;
5454 }
5455
Eric Laurente552edb2014-03-10 17:42:56 -07005456 }
5457 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005458 if (firstInexact != nullptr) {
5459 samplingRate = updatedSamplingRate;
5460 format = updatedFormat;
5461 channelMask = updatedChannelMask;
5462 return firstInexact;
5463 }
Eric Laurente552edb2014-03-10 17:42:56 -07005464 return NULL;
5465}
5466
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005467
5468audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005469 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005470{
Eric Laurent97ac8712018-07-27 18:59:02 -07005471 // Honor explicit routing requests only if all active clients have a preferred route in which
5472 // case the last active client route is used
5473 sp<DeviceDescriptor> deviceDesc =
5474 findPreferredDevice(mInputs, inputSource, mAvailableInputDevices);
5475 if (deviceDesc != nullptr) {
5476 return deviceDesc->type();
5477 }
5478
5479
François Gaffie036e1e92015-03-19 10:16:24 +01005480 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5481 audio_devices_t selectedDeviceFromMix =
5482 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005483
François Gaffie036e1e92015-03-19 10:16:24 +01005484 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5485 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005486 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005487 return getDeviceForInputSource(inputSource);
5488}
5489
5490audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5491{
Eric Laurent97ac8712018-07-27 18:59:02 -07005492 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005493}
5494
Eric Laurente0720872014-03-11 09:30:41 -07005495float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005496 int index,
5497 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005498{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005499 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005500
5501 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5502 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5503 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5504 // the ringtone volume
5505 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5506 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5507 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5508 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5509 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5510 }
5511
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005512 // in-call: always cap volume by voice volume + some low headroom
5513 if ((stream != AUDIO_STREAM_VOICE_CALL) &&
Eric Laurent7731b5a2018-04-06 15:47:22 -07005514 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005515 switch (stream) {
5516 case AUDIO_STREAM_SYSTEM:
5517 case AUDIO_STREAM_RING:
5518 case AUDIO_STREAM_MUSIC:
5519 case AUDIO_STREAM_ALARM:
5520 case AUDIO_STREAM_NOTIFICATION:
5521 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5522 case AUDIO_STREAM_DTMF:
5523 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005524 int voiceVolumeIndex =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005525 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, device);
Eric Laurent7731b5a2018-04-06 15:47:22 -07005526 const float maxVoiceVolDb =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005527 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, device)
Eric Laurent7731b5a2018-04-06 15:47:22 -07005528 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005529 if (volumeDB > maxVoiceVolDb) {
5530 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5531 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5532 volumeDB = maxVoiceVolDb;
5533 }
5534 } break;
5535 default:
5536 break;
5537 }
5538 }
5539
Eric Laurente552edb2014-03-10 17:42:56 -07005540 // if a headset is connected, apply the following rules to ring tones and notifications
5541 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005542 // - always attenuate notifications volume by 6dB
5543 // - attenuate ring tones volume by 6dB unless music is not playing and
5544 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005545 // - if music is playing, always limit the volume to current music volume,
5546 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005547 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005548 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5549 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5550 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005551 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005552 AUDIO_DEVICE_OUT_USB_HEADSET |
5553 AUDIO_DEVICE_OUT_HEARING_AID)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005554 ((stream_strategy == STRATEGY_SONIFICATION)
5555 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005556 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005557 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005558 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005559 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005560 // when the phone is ringing we must consider that music could have been paused just before
5561 // by the music application and behave as if music was active if the last music track was
5562 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005563 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005564 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005565 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005566 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005567 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005568 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5569 musicDevice),
5570 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005571 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5572 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005573 if (volumeDB > minVolDB) {
5574 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005575 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005576 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005577 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5578 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5579 // on A2DP, also ensure notification volume is not too low compared to media when
5580 // intended to be played
5581 if ((volumeDB > -96.0f) &&
5582 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5583 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5584 stream, device,
5585 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5586 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5587 }
5588 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005589 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5590 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005591 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005592 }
5593 }
5594
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005595 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005596}
5597
Eric Laurent3839bc02018-07-10 18:33:34 -07005598int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
5599 audio_stream_type_t srcStream,
5600 audio_stream_type_t dstStream)
5601{
5602 if (srcStream == dstStream) {
5603 return srcIndex;
5604 }
5605 float minSrc = (float)mVolumeCurves->getVolumeIndexMin(srcStream);
5606 float maxSrc = (float)mVolumeCurves->getVolumeIndexMax(srcStream);
5607 float minDst = (float)mVolumeCurves->getVolumeIndexMin(dstStream);
5608 float maxDst = (float)mVolumeCurves->getVolumeIndexMax(dstStream);
5609
5610 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
5611}
5612
Eric Laurente0720872014-03-11 09:30:41 -07005613status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005614 int index,
5615 const sp<AudioOutputDescriptor>& outputDesc,
5616 audio_devices_t device,
5617 int delayMs,
5618 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005619{
Eric Laurente552edb2014-03-10 17:42:56 -07005620 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005621 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005622 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005623 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005624 return NO_ERROR;
5625 }
François Gaffie2110e042015-03-24 08:41:51 +01005626 audio_policy_forced_cfg_t forceUseForComm =
5627 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005628 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005629 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5630 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005631 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005632 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005633 return INVALID_OPERATION;
5634 }
5635
Eric Laurentc75307b2015-03-17 15:29:32 -07005636 if (device == AUDIO_DEVICE_NONE) {
5637 device = outputDesc->device();
5638 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005639
Eric Laurentffbc80f2015-03-18 18:30:19 -07005640 float volumeDb = computeVolume(stream, index, device);
HW Leeda7581e2018-05-22 18:31:34 +08005641 if (outputDesc->isFixedVolume(device) ||
5642 // Force VoIP volume to max for bluetooth SCO
5643 ((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
5644 (device & AUDIO_DEVICE_OUT_ALL_SCO) != 0)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005645 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005646 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005647
Eric Laurentffbc80f2015-03-18 18:30:19 -07005648 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005649
Eric Laurent3b73df72014-03-11 09:06:29 -07005650 if (stream == AUDIO_STREAM_VOICE_CALL ||
5651 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005652 float voiceVolume;
5653 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005654 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurent3839bc02018-07-10 18:33:34 -07005655 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005656 } else {
5657 voiceVolume = 1.0;
5658 }
5659
Eric Laurent18fba842016-03-31 14:41:26 -07005660 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005661 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5662 mLastVoiceVolume = voiceVolume;
5663 }
5664 }
5665
5666 return NO_ERROR;
5667}
5668
Eric Laurentc75307b2015-03-17 15:29:32 -07005669void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5670 audio_devices_t device,
5671 int delayMs,
5672 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005673{
Eric Laurentc75307b2015-03-17 15:29:32 -07005674 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005675
Eric Laurent794fde22016-03-11 09:50:45 -08005676 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005677 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005678 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005679 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005680 device,
5681 delayMs,
5682 force);
5683 }
5684}
5685
Eric Laurente0720872014-03-11 09:30:41 -07005686void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005687 bool on,
5688 const sp<AudioOutputDescriptor>& outputDesc,
5689 int delayMs,
5690 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005691{
Eric Laurent72249d52015-06-08 11:12:15 -07005692 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5693 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005694 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005695 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005696 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005697 }
5698 }
5699}
5700
Eric Laurente0720872014-03-11 09:30:41 -07005701void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005702 bool on,
5703 const sp<AudioOutputDescriptor>& outputDesc,
5704 int delayMs,
5705 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005706{
Eric Laurente552edb2014-03-10 17:42:56 -07005707 if (device == AUDIO_DEVICE_NONE) {
5708 device = outputDesc->device();
5709 }
5710
Eric Laurentc75307b2015-03-17 15:29:32 -07005711 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5712 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005713
5714 if (on) {
5715 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005716 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005717 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005718 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005719 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005720 }
5721 }
5722 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5723 outputDesc->mMuteCount[stream]++;
5724 } else {
5725 if (outputDesc->mMuteCount[stream] == 0) {
5726 ALOGV("setStreamMute() unmuting non muted stream!");
5727 return;
5728 }
5729 if (--outputDesc->mMuteCount[stream] == 0) {
5730 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005731 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005732 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005733 device,
5734 delayMs);
5735 }
5736 }
5737}
5738
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005739audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5740{
5741 // flags to stream type mapping
5742 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5743 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5744 }
5745 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5746 return AUDIO_STREAM_BLUETOOTH_SCO;
5747 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005748 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5749 return AUDIO_STREAM_TTS;
5750 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005751
Ari Hausman-Cohen5c00d012018-06-26 17:09:11 -07005752 return audio_usage_to_stream_type(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005753}
Eric Laurente83b55d2014-11-14 10:06:21 -08005754
François Gaffie53615e22015-03-19 09:24:12 +01005755bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5756{
Eric Laurente83b55d2014-11-14 10:06:21 -08005757 // has flags that map to a strategy?
5758 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5759 return true;
5760 }
5761
5762 // has known usage?
5763 switch (paa->usage) {
5764 case AUDIO_USAGE_UNKNOWN:
5765 case AUDIO_USAGE_MEDIA:
5766 case AUDIO_USAGE_VOICE_COMMUNICATION:
5767 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5768 case AUDIO_USAGE_ALARM:
5769 case AUDIO_USAGE_NOTIFICATION:
5770 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5771 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5772 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5773 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5774 case AUDIO_USAGE_NOTIFICATION_EVENT:
5775 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5776 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5777 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5778 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005779 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005780 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005781 break;
5782 default:
5783 return false;
5784 }
5785 return true;
5786}
5787
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005788bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005789 routing_strategy strategy, uint32_t inPastMs,
5790 nsecs_t sysTime) const
5791{
5792 if ((sysTime == 0) && (inPastMs != 0)) {
5793 sysTime = systemTime();
5794 }
Eric Laurent794fde22016-03-11 09:50:45 -08005795 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005796 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurent97ac8712018-07-27 18:59:02 -07005797 (STRATEGY_NONE == strategy)) &&
François Gaffiead3183e2015-03-18 16:55:35 +01005798 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5799 return true;
5800 }
5801 }
5802 return false;
5803}
5804
Eric Laurent484e9272018-06-07 17:29:23 -07005805bool AudioPolicyManager::isStrategyActiveOnSameModule(const sp<AudioOutputDescriptor>& outputDesc,
5806 routing_strategy strategy, uint32_t inPastMs,
5807 nsecs_t sysTime) const
5808{
5809 for (size_t i = 0; i < mOutputs.size(); i++) {
5810 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5811 if (outputDesc->sharesHwModuleWith(desc)
5812 && isStrategyActive(desc, strategy, inPastMs, sysTime)) {
5813 return true;
5814 }
5815 }
5816 return false;
5817}
5818
François Gaffie2110e042015-03-24 08:41:51 +01005819audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5820{
5821 return mEngine->getForceUse(usage);
5822}
5823
5824bool AudioPolicyManager::isInCall()
5825{
5826 return isStateInCall(mEngine->getPhoneState());
5827}
5828
5829bool AudioPolicyManager::isStateInCall(int state)
5830{
5831 return is_state_in_call(state);
5832}
5833
Eric Laurentd60560a2015-04-10 11:31:20 -07005834void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5835{
5836 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005837 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5838 if (sourceDesc->srcDevice()->equals(deviceDesc)) {
5839 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->portId());
5840 stopAudioSource(sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005841 }
5842 }
5843
5844 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5845 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5846 bool release = false;
5847 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5848 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5849 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5850 source->ext.device.type == deviceDesc->type()) {
5851 release = true;
5852 }
5853 }
5854 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5855 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5856 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5857 sink->ext.device.type == deviceDesc->type()) {
5858 release = true;
5859 }
5860 }
5861 if (release) {
5862 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5863 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5864 }
5865 }
5866}
5867
Phil Burk09bc4612016-02-24 15:58:15 -08005868// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005869void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5870 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005871 // TODO Set this based on Config properties.
5872 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005873
5874 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5875 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005876 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005877
jiabin81772902018-04-02 17:52:27 -07005878 // If MANUAL, keep the supported surround sound formats as current enabled ones.
5879 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
5880 formats.clear();
5881 for (auto it = mSurroundFormats.begin(); it != mSurroundFormats.end(); it++) {
5882 formats.add(*it);
Phil Burk09bc4612016-02-24 15:58:15 -08005883 }
jiabin81772902018-04-02 17:52:27 -07005884 // Always enable IEC61937 when in MANUAL mode.
5885 formats.add(AUDIO_FORMAT_IEC61937);
5886 } else { // NEVER, AUTO or ALWAYS
5887 // Analyze original support for various formats.
5888 bool supportsAC3 = false;
5889 bool supportsOtherSurround = false;
5890 bool supportsIEC61937 = false;
5891 mSurroundFormats.clear();
5892 for (ssize_t formatIndex = 0; formatIndex < (ssize_t)formats.size(); formatIndex++) {
5893 audio_format_t format = formats[formatIndex];
5894 switch (format) {
5895 case AUDIO_FORMAT_AC3:
5896 supportsAC3 = true;
5897 break;
5898 case AUDIO_FORMAT_E_AC3:
5899 case AUDIO_FORMAT_DTS:
5900 case AUDIO_FORMAT_DTS_HD:
5901 // If ALWAYS, remove all other surround formats here
5902 // since we will add them later.
5903 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5904 formats.removeAt(formatIndex);
5905 formatIndex--;
5906 }
5907 supportsOtherSurround = true;
5908 break;
5909 case AUDIO_FORMAT_IEC61937:
5910 supportsIEC61937 = true;
5911 break;
5912 default:
5913 break;
5914 }
5915 }
Phil Burk09bc4612016-02-24 15:58:15 -08005916
jiabin81772902018-04-02 17:52:27 -07005917 // Modify formats based on surround preferences.
5918 // If NEVER, remove support for surround formats.
5919 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5920 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5921 // Remove surround sound related formats.
5922 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5923 audio_format_t format = formats[formatIndex];
5924 switch(format) {
5925 case AUDIO_FORMAT_AC3:
5926 case AUDIO_FORMAT_E_AC3:
5927 case AUDIO_FORMAT_DTS:
5928 case AUDIO_FORMAT_DTS_HD:
5929 case AUDIO_FORMAT_IEC61937:
5930 formats.removeAt(formatIndex);
5931 break;
5932 default:
5933 formatIndex++; // keep it
5934 break;
5935 }
5936 }
5937 supportsAC3 = false;
5938 supportsOtherSurround = false;
5939 supportsIEC61937 = false;
5940 }
5941 } else { // AUTO or ALWAYS
5942 // Most TVs support AC3 even if they do not report it in the EDID.
5943 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
5944 && !supportsAC3) {
5945 formats.add(AUDIO_FORMAT_AC3);
5946 supportsAC3 = true;
5947 }
5948
5949 // If ALWAYS, add support for raw surround formats if all are missing.
5950 // This assumes that if any of these formats are reported by the HAL
5951 // then the report is valid and should not be modified.
5952 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5953 formats.add(AUDIO_FORMAT_E_AC3);
5954 formats.add(AUDIO_FORMAT_DTS);
5955 formats.add(AUDIO_FORMAT_DTS_HD);
5956 supportsOtherSurround = true;
5957 }
5958
5959 // Add support for IEC61937 if any raw surround supported.
5960 // The HAL could do this but add it here, just in case.
5961 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
5962 formats.add(AUDIO_FORMAT_IEC61937);
5963 supportsIEC61937 = true;
5964 }
5965
5966 // Add reported surround sound formats to enabled surround formats.
5967 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
Phil Burk07ac1142016-03-25 13:39:29 -07005968 audio_format_t format = formats[formatIndex];
5969 switch(format) {
5970 case AUDIO_FORMAT_AC3:
5971 case AUDIO_FORMAT_E_AC3:
5972 case AUDIO_FORMAT_DTS:
5973 case AUDIO_FORMAT_DTS_HD:
jiabin81772902018-04-02 17:52:27 -07005974 case AUDIO_FORMAT_AAC_LC:
5975 case AUDIO_FORMAT_DOLBY_TRUEHD:
5976 case AUDIO_FORMAT_E_AC3_JOC:
5977 mSurroundFormats.insert(format);
Phil Burk07ac1142016-03-25 13:39:29 -07005978 default:
Phil Burk07ac1142016-03-25 13:39:29 -07005979 break;
5980 }
Phil Burk09bc4612016-02-24 15:58:15 -08005981 }
Phil Burk07ac1142016-03-25 13:39:29 -07005982 }
Phil Burk09bc4612016-02-24 15:58:15 -08005983 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005984}
5985
5986// Modify the list of channel masks supported.
5987void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
5988 ChannelsVector &channelMasks = *channelMasksPtr;
5989 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5990 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5991
5992 // If NEVER, then remove support for channelMasks > stereo.
5993 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5994 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5995 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5996 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5997 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5998 channelMasks.removeAt(maskIndex);
5999 } else {
6000 maskIndex++;
6001 }
6002 }
jiabin81772902018-04-02 17:52:27 -07006003 // If ALWAYS or MANUAL, then make sure we at least support 5.1
6004 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
6005 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006006 bool supports5dot1 = false;
6007 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006008 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006009 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
6010 supports5dot1 = true;
6011 break;
6012 }
6013 }
6014 // If not then add 5.1 support.
6015 if (!supports5dot1) {
6016 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
6017 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
6018 }
Phil Burk09bc4612016-02-24 15:58:15 -08006019 }
6020}
6021
Phil Burk00eeb322016-03-31 12:41:00 -07006022void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
6023 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01006024 AudioProfileVector &profiles)
6025{
6026 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07006027
François Gaffie112b0af2015-11-19 16:13:25 +01006028 // Format MUST be checked first to update the list of AudioProfile
6029 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006030 reply = mpClientInterface->getParameters(
6031 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07006032 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006033 AudioParameter repliedParameters(reply);
6034 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006035 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01006036 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
6037 return;
6038 }
Phil Burk09bc4612016-02-24 15:58:15 -08006039 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07006040 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006041 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07006042 }
Phil Burk09bc4612016-02-24 15:58:15 -08006043 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01006044 }
François Gaffie112b0af2015-11-19 16:13:25 +01006045
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006046 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08006047 ChannelsVector channelMasks;
6048 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01006049 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07006050 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01006051
6052 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006053 reply = mpClientInterface->getParameters(
6054 ioHandle,
6055 requestedParameters.toString() + ";" +
6056 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01006057 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006058 AudioParameter repliedParameters(reply);
6059 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006060 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006061 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01006062 }
6063 }
6064 if (profiles.hasDynamicChannelsFor(format)) {
6065 reply = mpClientInterface->getParameters(ioHandle,
6066 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07006067 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01006068 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006069 AudioParameter repliedParameters(reply);
6070 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006071 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006072 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07006073 if (device == AUDIO_DEVICE_OUT_HDMI) {
6074 filterSurroundChannelMasks(&channelMasks);
6075 }
François Gaffie112b0af2015-11-19 16:13:25 +01006076 }
6077 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08006078 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006079 }
6080}
Eric Laurentd60560a2015-04-10 11:31:20 -07006081
Mikhail Naganovdc769682018-05-04 15:34:08 -07006082status_t AudioPolicyManager::installPatch(const char *caller,
6083 audio_patch_handle_t *patchHandle,
6084 AudioIODescriptorInterface *ioDescriptor,
6085 const struct audio_patch *patch,
6086 int delayMs)
6087{
6088 ssize_t index = mAudioPatches.indexOfKey(
6089 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6090 *patchHandle : ioDescriptor->getPatchHandle());
6091 sp<AudioPatch> patchDesc;
6092 status_t status = installPatch(
6093 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6094 if (status == NO_ERROR) {
6095 ioDescriptor->setPatchHandle(patchDesc->mHandle);
6096 }
6097 return status;
6098}
6099
6100status_t AudioPolicyManager::installPatch(const char *caller,
6101 ssize_t index,
6102 audio_patch_handle_t *patchHandle,
6103 const struct audio_patch *patch,
6104 int delayMs,
6105 uid_t uid,
6106 sp<AudioPatch> *patchDescPtr)
6107{
6108 sp<AudioPatch> patchDesc;
6109 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6110 if (index >= 0) {
6111 patchDesc = mAudioPatches.valueAt(index);
6112 afPatchHandle = patchDesc->mAfPatchHandle;
6113 }
6114
6115 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6116 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6117 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6118 if (status == NO_ERROR) {
6119 if (index < 0) {
6120 patchDesc = new AudioPatch(patch, uid);
6121 addAudioPatch(patchDesc->mHandle, patchDesc);
6122 } else {
6123 patchDesc->mPatch = *patch;
6124 }
6125 patchDesc->mAfPatchHandle = afPatchHandle;
6126 if (patchHandle) {
6127 *patchHandle = patchDesc->mHandle;
6128 }
6129 nextAudioPortGeneration();
6130 mpClientInterface->onAudioPatchListUpdate();
6131 }
6132 if (patchDescPtr) *patchDescPtr = patchDesc;
6133 return status;
6134}
6135
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006136} // namespace android