blob: 47e17f113f43a4dabd542bfa2e809a802fe7117c [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070017#define LOG_TAG "APM_AudioPolicyManager"
Eric Laurente552edb2014-03-10 17:42:56 -070018//#define LOG_NDEBUG 0
19
20//#define VERY_VERBOSE_LOGGING
21#ifdef VERY_VERBOSE_LOGGING
22#define ALOGVV ALOGV
23#else
24#define ALOGVV(a...) do { } while(0)
25#endif
26
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +090027#define AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH 128
28#define AUDIO_POLICY_XML_CONFIG_FILE_NAME "audio_policy_configuration.xml"
Petri Gyntherf497f292018-04-17 18:46:10 -070029#define AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME \
30 "audio_policy_configuration_a2dp_offload_disabled.xml"
François Gaffief4ad6e52015-11-19 16:59:57 +010031
Eric Laurentd4692962014-05-05 18:13:44 -070032#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070033#include <math.h>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110034#include <vector>
Eric Laurentd4692962014-05-05 18:13:44 -070035
François Gaffie2110e042015-03-24 08:41:51 +010036#include <AudioPolicyManagerInterface.h>
37#include <AudioPolicyEngineInstance.h>
Eric Laurente552edb2014-03-10 17:42:56 -070038#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070039#include <utils/Log.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070040#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080041#include <media/AudioPolicyHelper.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070042#include <private/android_filesystem_config.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070043#include <soundtrigger/SoundTrigger.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070044#include <system/audio.h>
Mikhail Naganov9ee05402016-10-13 15:58:17 -070045#include <audio_policy_conf.h>
Eric Laurentd4692962014-05-05 18:13:44 -070046#include "AudioPolicyManager.h"
François Gaffied1ab2bd2015-12-02 18:20:06 +010047#ifndef USE_XML_AUDIO_POLICY_CONF
François Gaffie53615e22015-03-19 09:24:12 +010048#include <ConfigParsingUtils.h>
François Gaffied1ab2bd2015-12-02 18:20:06 +010049#include <StreamDescriptor.h>
François Gaffief4ad6e52015-11-19 16:59:57 +010050#endif
François Gaffied1ab2bd2015-12-02 18:20:06 +010051#include <Serializer.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010052#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010053#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070054
Eric Laurent3b73df72014-03-11 09:06:29 -070055namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070056
Eric Laurentdc462862016-07-19 12:29:53 -070057//FIXME: workaround for truncated touch sounds
58// to be removed when the problem is handled by system UI
59#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070060
61// Largest difference in dB on earpiece in call between the voice volume and another
62// media / notification / system volume.
63constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
64
jiabin81772902018-04-02 17:52:27 -070065#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
66// Array of all surround formats.
67static const audio_format_t SURROUND_FORMATS[] = {
68 AUDIO_FORMAT_AC3,
69 AUDIO_FORMAT_E_AC3,
70 AUDIO_FORMAT_DTS,
71 AUDIO_FORMAT_DTS_HD,
72 AUDIO_FORMAT_AAC_LC,
73 AUDIO_FORMAT_DOLBY_TRUEHD,
74 AUDIO_FORMAT_E_AC3_JOC,
75};
76// Array of all AAC formats. When AAC is enabled by users, all AAC formats should be enabled.
77static const audio_format_t AAC_FORMATS[] = {
78 AUDIO_FORMAT_AAC_LC,
79 AUDIO_FORMAT_AAC_HE_V1,
80 AUDIO_FORMAT_AAC_HE_V2,
81 AUDIO_FORMAT_AAC_ELD,
82 AUDIO_FORMAT_AAC_XHE,
83};
84
Mikhail Naganov15be9d22017-11-08 14:18:13 +110085// Compressed formats for MSD module, ordered from most preferred to least preferred.
86static const std::vector<audio_format_t> compressedFormatsOrder = {{
87 AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
88 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
89// Channel masks for MSD module, 3D > 2D > 1D ordering (most preferred to least preferred).
90static const std::vector<audio_channel_mask_t> surroundChannelMasksOrder = {{
91 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
92 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
93 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
94
Eric Laurente552edb2014-03-10 17:42:56 -070095// ----------------------------------------------------------------------------
96// AudioPolicyInterface implementation
97// ----------------------------------------------------------------------------
98
Eric Laurente0720872014-03-11 09:30:41 -070099status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -0800100 audio_policy_dev_state_t state,
101 const char *device_address,
102 const char *device_name)
Eric Laurente552edb2014-03-10 17:42:56 -0700103{
jiabina7b43792018-02-15 16:04:46 -0800104 status_t status = setDeviceConnectionStateInt(device, state, device_address, device_name);
105 nextAudioPortGeneration();
106 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800107}
108
François Gaffie44481e72016-04-20 07:49:57 +0200109void AudioPolicyManager::broadcastDeviceConnectionState(audio_devices_t device,
110 audio_policy_dev_state_t state,
111 const String8 &device_address)
112{
113 AudioParameter param(device_address);
114 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganov388360c2016-10-17 17:09:41 -0700115 AudioParameter::keyStreamConnect : AudioParameter::keyStreamDisconnect);
François Gaffie44481e72016-04-20 07:49:57 +0200116 param.addInt(key, device);
117 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
118}
119
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800120status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800121 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -0800122 const char *device_address,
123 const char *device_name)
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800124{
Paul McLeane743a472015-01-28 11:07:31 -0800125 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s",
Mikhail Naganov7e22e942017-12-07 10:04:29 -0800126 device, state, device_address, device_name);
Eric Laurente552edb2014-03-10 17:42:56 -0700127
128 // connect/disconnect only 1 device at a time
129 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
130
François Gaffie53615e22015-03-19 09:24:12 +0100131 sp<DeviceDescriptor> devDesc =
132 mHwModules.getDeviceDescriptor(device, device_address, device_name);
Paul McLeane743a472015-01-28 11:07:31 -0800133
Eric Laurente552edb2014-03-10 17:42:56 -0700134 // handle output devices
135 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700136 SortedVector <audio_io_handle_t> outputs;
137
Eric Laurent3a4311c2014-03-17 12:00:47 -0700138 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
139
Eric Laurente552edb2014-03-10 17:42:56 -0700140 // save a copy of the opened output descriptors before any output is opened or closed
141 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
142 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700143 switch (state)
144 {
145 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800146 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700147 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700148 ALOGW("setDeviceConnectionState() device already connected: %x", device);
149 return INVALID_OPERATION;
150 }
151 ALOGV("setDeviceConnectionState() connecting device %x", device);
152
Eric Laurente552edb2014-03-10 17:42:56 -0700153 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700154 index = mAvailableOutputDevices.add(devDesc);
155 if (index >= 0) {
François Gaffie53615e22015-03-19 09:24:12 +0100156 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700157 if (module == 0) {
158 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
159 device);
160 mAvailableOutputDevices.remove(devDesc);
161 return INVALID_OPERATION;
162 }
Paul McLeane743a472015-01-28 11:07:31 -0800163 mAvailableOutputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700164 } else {
165 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700166 }
167
François Gaffie44481e72016-04-20 07:49:57 +0200168 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
169 // parameters on newly connected devices (instead of opening the outputs...)
170 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
171
Eric Laurenta1d525f2015-01-29 13:36:45 -0800172 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700173 mAvailableOutputDevices.remove(devDesc);
François Gaffie44481e72016-04-20 07:49:57 +0200174
175 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
176 devDesc->mAddress);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700177 return INVALID_OPERATION;
178 }
François Gaffie2110e042015-03-24 08:41:51 +0100179 // Propagate device availability to Engine
180 mEngine->setDeviceConnectionState(devDesc, state);
181
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700182 // outputs should never be empty here
183 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
184 "checkOutputsForDevice() returned no outputs but status OK");
185 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
186 outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800187
Eric Laurent3ae5f312015-02-03 17:12:08 -0800188 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700189 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700190 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700191 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700192 ALOGW("setDeviceConnectionState() device not connected: %x", device);
193 return INVALID_OPERATION;
194 }
195
Paul McLean5c477aa2014-08-20 16:47:57 -0700196 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
197
Paul McLeane743a472015-01-28 11:07:31 -0800198 // Send Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200199 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700200
Eric Laurente552edb2014-03-10 17:42:56 -0700201 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700202 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700203
Eric Laurenta1d525f2015-01-29 13:36:45 -0800204 checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress);
François Gaffie2110e042015-03-24 08:41:51 +0100205
206 // Propagate device availability to Engine
207 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700208 } break;
209
210 default:
211 ALOGE("setDeviceConnectionState() invalid state: %x", state);
212 return BAD_VALUE;
213 }
214
Mikhail Naganov37977152018-07-11 15:54:44 -0700215 checkForDeviceAndOutputChanges([&]() {
216 // outputs must be closed after checkOutputForAllStrategies() is executed
217 if (!outputs.isEmpty()) {
218 for (audio_io_handle_t output : outputs) {
219 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
220 // close unused outputs after device disconnection or direct outputs that have been
221 // opened by checkOutputsForDevice() to query dynamic parameters
222 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
223 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
224 (desc->mDirectOpenCount == 0))) {
225 closeOutput(output);
226 }
Eric Laurente552edb2014-03-10 17:42:56 -0700227 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700228 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
229 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700230 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700231 return false;
232 });
Eric Laurente552edb2014-03-10 17:42:56 -0700233
Eric Laurent87ffa392015-05-22 10:32:38 -0700234 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700235 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
236 updateCallRouting(newDevice);
237 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100238 const audio_devices_t msdOutDevice = getMsdAudioOutDeviceTypes();
Eric Laurente552edb2014-03-10 17:42:56 -0700239 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700240 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
241 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
242 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700243 // do not force device change on duplicated output because if device is 0, it will
244 // also force a device 0 for the two outputs it is duplicated to which may override
245 // a valid device selection on those outputs.
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100246 bool force = (msdOutDevice == AUDIO_DEVICE_NONE || msdOutDevice != desc->device())
247 && !desc->isDuplicated()
François Gaffie53615e22015-03-19 09:24:12 +0100248 && (!device_distinguishes_on_address(device)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700249 // always force when disconnecting (a non-duplicated device)
250 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
Eric Laurentc75307b2015-03-17 15:29:32 -0700251 setOutputDevice(desc, newDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700252 }
Eric Laurente552edb2014-03-10 17:42:56 -0700253 }
254
Eric Laurentd60560a2015-04-10 11:31:20 -0700255 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
256 cleanUpForDevice(devDesc);
257 }
258
Eric Laurent72aa32f2014-05-30 18:51:48 -0700259 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700260 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700261 } // end if is output device
262
Eric Laurente552edb2014-03-10 17:42:56 -0700263 // handle input devices
264 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700265 SortedVector <audio_io_handle_t> inputs;
266
Eric Laurent3a4311c2014-03-17 12:00:47 -0700267 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700268 switch (state)
269 {
270 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700271 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700272 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700273 ALOGW("setDeviceConnectionState() device already connected: %d", device);
274 return INVALID_OPERATION;
275 }
François Gaffie53615e22015-03-19 09:24:12 +0100276 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700277 if (module == NULL) {
278 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
279 device);
280 return INVALID_OPERATION;
281 }
François Gaffie44481e72016-04-20 07:49:57 +0200282
283 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
284 // parameters on newly connected devices (instead of opening the inputs...)
285 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
286
Paul McLean9080a4c2015-06-18 08:24:02 -0700287 if (checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress) != NO_ERROR) {
François Gaffie44481e72016-04-20 07:49:57 +0200288 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
289 devDesc->mAddress);
Eric Laurentd4692962014-05-05 18:13:44 -0700290 return INVALID_OPERATION;
291 }
292
Eric Laurent3a4311c2014-03-17 12:00:47 -0700293 index = mAvailableInputDevices.add(devDesc);
294 if (index >= 0) {
Paul McLeane743a472015-01-28 11:07:31 -0800295 mAvailableInputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700296 } else {
297 return NO_MEMORY;
298 }
Eric Laurent3ae5f312015-02-03 17:12:08 -0800299
François Gaffie2110e042015-03-24 08:41:51 +0100300 // Propagate device availability to Engine
301 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700302 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700303
304 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700305 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700306 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700307 ALOGW("setDeviceConnectionState() device not connected: %d", device);
308 return INVALID_OPERATION;
309 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700310
311 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
312
313 // Set Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200314 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700315
Paul McLean9080a4c2015-06-18 08:24:02 -0700316 checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700317 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700318
François Gaffie2110e042015-03-24 08:41:51 +0100319 // Propagate device availability to Engine
320 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700321 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700322
323 default:
324 ALOGE("setDeviceConnectionState() invalid state: %x", state);
325 return BAD_VALUE;
326 }
327
Eric Laurentd4692962014-05-05 18:13:44 -0700328 closeAllInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700329 // As the input device list can impact the output device selection, update
330 // getDeviceForStrategy() cache
331 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700332
Eric Laurent87ffa392015-05-22 10:32:38 -0700333 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700334 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
335 updateCallRouting(newDevice);
336 }
337
Eric Laurentd60560a2015-04-10 11:31:20 -0700338 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
339 cleanUpForDevice(devDesc);
340 }
341
Eric Laurentb52c1522014-05-20 11:27:36 -0700342 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700343 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700344 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700345
346 ALOGW("setDeviceConnectionState() invalid device: %x", device);
347 return BAD_VALUE;
348}
349
Eric Laurente0720872014-03-11 09:30:41 -0700350audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100351 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700352{
Eric Laurent634b7142016-04-20 13:48:02 -0700353 sp<DeviceDescriptor> devDesc =
354 mHwModules.getDeviceDescriptor(device, device_address, "",
355 (strlen(device_address) != 0)/*matchAddress*/);
356
357 if (devDesc == 0) {
358 ALOGW("getDeviceConnectionState() undeclared device, type %08x, address: %s",
359 device, device_address);
360 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
361 }
François Gaffie53615e22015-03-19 09:24:12 +0100362
Eric Laurent3a4311c2014-03-17 12:00:47 -0700363 DeviceVector *deviceVector;
364
Eric Laurente552edb2014-03-10 17:42:56 -0700365 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700366 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700367 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700368 deviceVector = &mAvailableInputDevices;
369 } else {
370 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
371 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700372 }
Eric Laurent634b7142016-04-20 13:48:02 -0700373
374 return (deviceVector->getDevice(device, String8(device_address)) != 0) ?
375 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800376}
377
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800378status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
379 const char *device_address,
380 const char *device_name)
381{
382 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700383 String8 reply;
384 AudioParameter param;
385 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800386
387 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s",
388 device, device_address, device_name);
389
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800390 // connect/disconnect only 1 device at a time
391 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
392
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800393 // Check if the device is currently connected
394 sp<DeviceDescriptor> devDesc =
395 mHwModules.getDeviceDescriptor(device, device_address, device_name);
396 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
397 if (index < 0) {
398 // Nothing to do: device is not connected
399 return NO_ERROR;
400 }
401
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700402 // For offloaded A2DP, Hw modules may have the capability to
403 // configure codecs. Check if any of the loaded hw modules
404 // supports this.
405 // If supported, send a set parameter to configure A2DP codecs
406 // and return. No need to toggle device state.
407 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
408 reply = mpClientInterface->getParameters(
409 AUDIO_IO_HANDLE_NONE,
410 String8(AudioParameter::keyReconfigA2dpSupported));
411 AudioParameter repliedParameters(reply);
412 repliedParameters.getInt(
413 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
414 if (isReconfigA2dpSupported) {
415 const String8 key(AudioParameter::keyReconfigA2dp);
416 param.add(key, String8("true"));
417 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
418 return NO_ERROR;
419 }
420 }
421
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800422 // Toggle the device state: UNAVAILABLE -> AVAILABLE
423 // This will force reading again the device configuration
424 status = setDeviceConnectionState(device,
425 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
426 device_address, device_name);
427 if (status != NO_ERROR) {
428 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
429 status);
430 return status;
431 }
432
433 status = setDeviceConnectionState(device,
434 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
435 device_address, device_name);
436 if (status != NO_ERROR) {
437 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
438 status);
439 return status;
440 }
441
442 return NO_ERROR;
443}
444
Eric Laurentdc462862016-07-19 12:29:53 -0700445uint32_t AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700446{
447 bool createTxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700448 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700449
Andy Hunga76c7de2016-12-13 19:14:31 -0800450 if(!hasPrimaryOutput() || mPrimaryOutput->device() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurentdc462862016-07-19 12:29:53 -0700451 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700452 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800453 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700454 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
455
456 // release existing RX patch if any
457 if (mCallRxPatch != 0) {
458 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
459 mCallRxPatch.clear();
460 }
461 // release TX patch if any
462 if (mCallTxPatch != 0) {
463 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
464 mCallTxPatch.clear();
465 }
466
467 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
468 // via setOutputDevice() on primary output.
469 // Otherwise, create two audio patches for TX and RX path.
470 if (availablePrimaryOutputDevices() & rxDevice) {
Eric Laurentdc462862016-07-19 12:29:53 -0700471 muteWaitMs = setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700472 // If the TX device is also on the primary HW module, setOutputDevice() will take care
473 // of it due to legacy implementation. If not, create a patch.
474 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
475 == AUDIO_DEVICE_NONE) {
476 createTxPatch = true;
477 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700478 } else { // create RX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800479 mCallRxPatch = createTelephonyPatch(true /*isRx*/, rxDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700480 createTxPatch = true;
481 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700482 if (createTxPatch) { // create TX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800483 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txDevice, delayMs);
484 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700485
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800486 return muteWaitMs;
487}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700488
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800489sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
490 bool isRx, audio_devices_t device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700491 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700492
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800493 sp<DeviceDescriptor> txSourceDeviceDesc;
494 if (isRx) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700495 patchBuilder.addSink(findDevice(mAvailableOutputDevices, device)).
496 addSource(findDevice(mAvailableInputDevices, AUDIO_DEVICE_IN_TELEPHONY_RX));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800497 } else {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700498 patchBuilder.addSource(txSourceDeviceDesc = findDevice(mAvailableInputDevices, device)).
499 addSink(findDevice(mAvailableOutputDevices, AUDIO_DEVICE_OUT_TELEPHONY_TX));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800500 }
501
502 audio_devices_t outputDevice = isRx ? device : AUDIO_DEVICE_OUT_TELEPHONY_TX;
503 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(outputDevice, mOutputs);
504 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
505 // request to reuse existing output stream if one is already opened to reach the target device
506 if (output != AUDIO_IO_HANDLE_NONE) {
507 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
508 ALOG_ASSERT(!outputDesc->isDuplicated(),
509 "%s() %#x device output %d is duplicated", __func__, outputDevice, output);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700510 patchBuilder.addSource(outputDesc, { .stream = AUDIO_STREAM_PATCH });
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800511 }
512
513 if (!isRx) {
Eric Laurentc0a889f2015-10-14 14:36:34 -0700514 // terminate active capture if on the same HW module as the call TX source device
515 // FIXME: would be better to refine to only inputs whose profile connects to the
516 // call TX device but this information is not in the audio patch and logic here must be
517 // symmetric to the one in startInput()
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800518 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800519 if (activeDesc->hasSameHwModuleAs(txSourceDeviceDesc)) {
Eric Laurent8fc147b2018-07-22 19:13:55 -0700520 closeSessions(activeDesc, true /*activeOnly*/);
Eric Laurentc0a889f2015-10-14 14:36:34 -0700521 }
522 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700523 }
Eric Laurentdc462862016-07-19 12:29:53 -0700524
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800525 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Mikhail Naganovdc769682018-05-04 15:34:08 -0700526 status_t status = mpClientInterface->createAudioPatch(
527 patchBuilder.patch(), &afPatchHandle, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800528 ALOGW_IF(status != NO_ERROR,
529 "%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
530 sp<AudioPatch> audioPatch;
531 if (status == NO_ERROR) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700532 audioPatch = new AudioPatch(patchBuilder.patch(), mUidCached);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800533 audioPatch->mAfPatchHandle = afPatchHandle;
534 audioPatch->mUid = mUidCached;
535 }
536 return audioPatch;
537}
538
Mikhail Naganovdc769682018-05-04 15:34:08 -0700539sp<DeviceDescriptor> AudioPolicyManager::findDevice(
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100540 const DeviceVector& devices, audio_devices_t device) const {
Mikhail Naganov708e0382018-05-30 09:53:04 -0700541 DeviceVector deviceList = devices.getDevicesFromTypeMask(device);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800542 ALOG_ASSERT(!deviceList.isEmpty(),
543 "%s() selected device type %#x is not in devices list", __func__, device);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700544 return deviceList.itemAt(0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700545}
546
Eric Laurente0720872014-03-11 09:30:41 -0700547void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700548{
549 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100550 // store previous phone state for management of sonification strategy below
551 int oldState = mEngine->getPhoneState();
552
553 if (mEngine->setPhoneState(state) != NO_ERROR) {
554 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700555 return;
556 }
François Gaffie2110e042015-03-24 08:41:51 +0100557 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700558 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700559 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700560 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800561 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700562 }
563
François Gaffie2110e042015-03-24 08:41:51 +0100564 /**
565 * Switching to or from incall state or switching between telephony and VoIP lead to force
566 * routing command.
567 */
568 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
569 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700570
571 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700572 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700573
Eric Laurente552edb2014-03-10 17:42:56 -0700574 int delayMs = 0;
575 if (isStateInCall(state)) {
576 nsecs_t sysTime = systemTime();
577 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700578 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700579 // mute media and sonification strategies and delay device switch by the largest
580 // latency of any output where either strategy is active.
581 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100582 if ((isStrategyActive(desc, STRATEGY_MEDIA,
583 SONIFICATION_HEADSET_MUSIC_DELAY,
584 sysTime) ||
585 isStrategyActive(desc, STRATEGY_SONIFICATION,
586 SONIFICATION_HEADSET_MUSIC_DELAY,
587 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700588 (delayMs < (int)desc->latency()*2)) {
589 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700590 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700591 setStrategyMute(STRATEGY_MEDIA, true, desc);
592 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700593 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700594 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
595 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700596 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
597 }
598 }
599
Eric Laurent87ffa392015-05-22 10:32:38 -0700600 if (hasPrimaryOutput()) {
601 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
602 // the device returned is not necessarily reachable via this output
603 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
604 // force routing command to audio hardware when ending call
605 // even if no device change is needed
606 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
607 rxDevice = mPrimaryOutput->device();
608 }
Eric Laurente552edb2014-03-10 17:42:56 -0700609
Eric Laurent87ffa392015-05-22 10:32:38 -0700610 if (state == AUDIO_MODE_IN_CALL) {
611 updateCallRouting(rxDevice, delayMs);
612 } else if (oldState == AUDIO_MODE_IN_CALL) {
613 if (mCallRxPatch != 0) {
614 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
615 mCallRxPatch.clear();
616 }
617 if (mCallTxPatch != 0) {
618 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
619 mCallTxPatch.clear();
620 }
621 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
622 } else {
623 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700624 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700625 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700626
627 // reevaluate routing on all outputs in case tracks have been started during the call
628 for (size_t i = 0; i < mOutputs.size(); i++) {
629 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
630 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
631 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
Yung Ti Suf60c8242018-05-10 18:07:26 +0800632 setOutputDevice(desc, newDevice, (newDevice != AUDIO_DEVICE_NONE), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700633 }
634 }
635
Eric Laurente552edb2014-03-10 17:42:56 -0700636 if (isStateInCall(state)) {
637 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700638 // force reevaluating accessibility routing when call starts
639 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700640 }
641
642 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700643 if (state == AUDIO_MODE_RINGTONE &&
644 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700645 mLimitRingtoneVolume = true;
646 } else {
647 mLimitRingtoneVolume = false;
648 }
649}
650
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700651audio_mode_t AudioPolicyManager::getPhoneState() {
652 return mEngine->getPhoneState();
653}
654
Eric Laurente0720872014-03-11 09:30:41 -0700655void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700656 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700657{
François Gaffie2110e042015-03-24 08:41:51 +0100658 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700659 if (config == mEngine->getForceUse(usage)) {
660 return;
661 }
Eric Laurente552edb2014-03-10 17:42:56 -0700662
François Gaffie2110e042015-03-24 08:41:51 +0100663 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
664 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
665 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700666 }
François Gaffie2110e042015-03-24 08:41:51 +0100667 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
668 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
669 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700670
671 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700672 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800673
Eric Laurentdc462862016-07-19 12:29:53 -0700674 //FIXME: workaround for truncated touch sounds
675 // to be removed when the problem is handled by system UI
676 uint32_t delayMs = 0;
677 uint32_t waitMs = 0;
678 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
679 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
680 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700681 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700682 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
Eric Laurentdc462862016-07-19 12:29:53 -0700683 waitMs = updateCallRouting(newDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700684 }
Eric Laurente552edb2014-03-10 17:42:56 -0700685 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700686 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
687 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
688 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700689 waitMs = setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE),
690 delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700691 }
Eric Laurente552edb2014-03-10 17:42:56 -0700692 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700693 applyStreamVolumes(outputDesc, newDevice, waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700694 }
695 }
696
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800697 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800698 audio_devices_t newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700699 // Force new input selection if the new device can not be reached via current input
Eric Laurentfb66dd92016-01-28 18:32:03 -0800700 if (activeDesc->mProfile->getSupportedDevices().types() &
701 (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
702 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700703 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800704 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700705 }
Eric Laurente552edb2014-03-10 17:42:56 -0700706 }
Eric Laurente552edb2014-03-10 17:42:56 -0700707}
708
Eric Laurente0720872014-03-11 09:30:41 -0700709void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700710{
711 ALOGV("setSystemProperty() property %s, value %s", property, value);
712}
713
714// Find a direct output profile compatible with the parameters passed, even if the input flags do
715// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800716sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700717 audio_devices_t device,
718 uint32_t samplingRate,
719 audio_format_t format,
720 audio_channel_mask_t channelMask,
721 audio_output_flags_t flags)
722{
Eric Laurent861a6282015-05-18 15:40:16 -0700723 // only retain flags that will drive the direct output profile selection
724 // if explicitly requested
725 static const uint32_t kRelevantFlags =
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700726 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
727 AUDIO_OUTPUT_FLAG_VOIP_RX);
Eric Laurent861a6282015-05-18 15:40:16 -0700728 flags =
729 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
730
731 sp<IOProfile> profile;
732
Mikhail Naganovd4120142017-12-06 15:49:22 -0800733 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800734 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent861a6282015-05-18 15:40:16 -0700735 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700736 samplingRate, NULL /*updatedSamplingRate*/,
737 format, NULL /*updatedFormat*/,
738 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700739 flags)) {
740 continue;
741 }
742 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100743 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700744 continue;
745 }
746 // if several profiles are compatible, give priority to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100747 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700748 continue;
749 }
750 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100751 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700752 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700753 }
Eric Laurente552edb2014-03-10 17:42:56 -0700754 }
755 }
Eric Laurent861a6282015-05-18 15:40:16 -0700756 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700757}
758
Eric Laurentf4e63452017-11-06 19:31:46 +0000759audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700760{
Eric Laurent3b73df72014-03-11 09:06:29 -0700761 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700762 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800763
764 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
765 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
766 // format, flags, etc. This may result in some discrepancy for functions that utilize
767 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
768 // and AudioSystem::getOutputSamplingRate().
769
Eric Laurentf4e63452017-11-06 19:31:46 +0000770 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
771 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
Eric Laurente552edb2014-03-10 17:42:56 -0700772
Eric Laurentf4e63452017-11-06 19:31:46 +0000773 ALOGV("getOutput() stream %d selected device %08x, output %d", stream, device, output);
774 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700775}
776
Eric Laurente83b55d2014-11-14 10:06:21 -0800777status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
778 audio_io_handle_t *output,
779 audio_session_t session,
780 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700781 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800782 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200783 audio_output_flags_t *flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700784 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800785 audio_port_handle_t *portId)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700786{
Eric Laurente83b55d2014-11-14 10:06:21 -0800787 audio_attributes_t attributes;
Eric Laurent8fc147b2018-07-22 19:13:55 -0700788 DeviceVector outputDevices;
789 routing_strategy strategy;
790 audio_devices_t device;
791 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100792 audio_devices_t msdDevice = getMsdAudioOutDeviceTypes();
Eric Laurent8fc147b2018-07-22 19:13:55 -0700793
Eric Laurente83b55d2014-11-14 10:06:21 -0800794 if (attr != NULL) {
795 if (!isValidAttributes(attr)) {
796 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
797 attr->usage, attr->content_type, attr->flags,
798 attr->tags);
799 return BAD_VALUE;
800 }
801 attributes = *attr;
802 } else {
803 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
804 ALOGE("getOutputForAttr(): invalid stream type");
805 return BAD_VALUE;
806 }
807 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700808 }
Eric Laurent20b9ef02016-12-05 11:03:16 -0800809
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700810 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
811 " session %d selectedDeviceId %d",
812 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700813 session, *selectedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700814
Scott Randolph7b1fd232018-06-18 15:33:03 -0700815 // TODO: check for existing client for this port ID
816 if (*portId == AUDIO_PORT_HANDLE_NONE) {
817 *portId = AudioPort::getNextUniqueId();
818 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700819
Scott Randolph7b1fd232018-06-18 15:33:03 -0700820 // First check for explicit routing (eg. setPreferredDevice)
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700821 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -0700822 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800823 deviceDesc = mAvailableOutputDevices.getDeviceFromId(*selectedDeviceId);
Scott Randolph7b1fd232018-06-18 15:33:03 -0700824 } else {
825 // If no explict route, is there a matching dynamic policy that applies?
826 sp<SwAudioOutputDescriptor> desc;
827 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
828 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
829 if (!audio_has_proportional_frames(config->format)) {
830 return BAD_VALUE;
831 }
832 *stream = streamTypefromAttributesInt(&attributes);
833 *output = desc->mIoHandle;
834 ALOGV("getOutputForAttr() returns output %d", *output);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700835 goto exit;
Scott Randolph7b1fd232018-06-18 15:33:03 -0700836 }
837
838 // Virtual sources must always be dynamicaly or explicitly routed
839 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
840 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
841 return BAD_VALUE;
842 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700843 }
Scott Randolph7b1fd232018-06-18 15:33:03 -0700844
845 // Virtual sources must always be dynamicaly or explicitly routed
846 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
847 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
848 return BAD_VALUE;
849 }
850
851 *stream = streamTypefromAttributesInt(&attributes);
852
853 // TODO: Should this happen only if an explicit route is active?
854 // the previous code structure meant that this would always happen which
855 // would appear to result in adding a null deviceDesc when not using an
856 // explicit route. Is that the intended and necessary behavior?
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700857 mOutputRoutes.addRoute(session, *stream, SessionRoute::SOURCE_TYPE_NA, deviceDesc, uid);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700858
Eric Laurent8fc147b2018-07-22 19:13:55 -0700859 strategy = (routing_strategy) getStrategyForAttr(&attributes);
860 device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700861
Eric Laurente83b55d2014-11-14 10:06:21 -0800862 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200863 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -0700864 }
865
Nadav Barb2f18162018-07-18 13:01:53 +0300866 // Set incall music only if device was explicitly set, and fallback to the device which is
867 // chosen by the engine if not.
868 // FIXME: provide a more generic approach which is not device specific and move this back
869 // to getOutputForDevice.
870 if (device == AUDIO_DEVICE_OUT_TELEPHONY_TX &&
871 *stream == AUDIO_STREAM_MUSIC &&
872 audio_is_linear_pcm(config->format) &&
873 isInCall()) {
874 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
875 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
876 } else {
877 device = mEngine->getDeviceForStrategy(strategy);
878 }
879 }
880
Glenn Kasten49f36ba2017-12-06 13:02:02 -0800881 ALOGV("getOutputForAttr() device 0x%x, sampling rate %d, format %#x, channel mask %#x, "
882 "flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +0200883 device, config->sample_rate, config->format, config->channel_mask, *flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700884
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100885 *output = AUDIO_IO_HANDLE_NONE;
886 if (msdDevice != AUDIO_DEVICE_NONE) {
887 *output = getOutputForDevice(msdDevice, session, *stream, config, flags);
888 if (*output != AUDIO_IO_HANDLE_NONE && setMsdPatch(device) == NO_ERROR) {
889 ALOGV("%s() Using MSD device 0x%x instead of device 0x%x",
890 __func__, msdDevice, device);
891 device = msdDevice;
892 } else {
893 *output = AUDIO_IO_HANDLE_NONE;
894 }
895 }
896 if (*output == AUDIO_IO_HANDLE_NONE) {
897 *output = getOutputForDevice(device, session, *stream, config, flags);
898 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800899 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700900 mOutputRoutes.removeRoute(session);
Eric Laurente83b55d2014-11-14 10:06:21 -0800901 return INVALID_OPERATION;
902 }
Paul McLeanaa981192015-03-21 09:55:15 -0700903
Eric Laurent8fc147b2018-07-22 19:13:55 -0700904 outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -0700905 *selectedDeviceId = outputDevices.size() > 0 ? outputDevices.itemAt(0)->getId()
906 : AUDIO_PORT_HANDLE_NONE;
907
Eric Laurent8fc147b2018-07-22 19:13:55 -0700908exit:
909 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
910 .format = config->format,
911 .channel_mask = config->channel_mask };
912 sp<TrackClientDescriptor> clientDesc =
913 new TrackClientDescriptor(*portId, uid, session,
914 attributes, clientConfig, requestedDeviceId, *stream, *flags);
915 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
916 outputDesc->clients().emplace(*portId, clientDesc);
917
918 ALOGV(" getOutputForAttr() returns output %d selectedDeviceId %d for port ID %d",
919 *output, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -0700920
Eric Laurente83b55d2014-11-14 10:06:21 -0800921 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700922}
923
924audio_io_handle_t AudioPolicyManager::getOutputForDevice(
925 audio_devices_t device,
Kevin Rocard169753c2017-03-06 14:18:23 -0800926 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700927 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -0800928 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200929 audio_output_flags_t *flags)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700930{
Andy Hungc88b0642018-04-27 15:42:35 -0700931 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700932 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700933
Eric Laurente552edb2014-03-10 17:42:56 -0700934 // open a direct output if required by specified parameters
935 //force direct flag if offload flag is set: offloading implies a direct output stream
936 // and all common behaviors are driven by checking only the direct flag
937 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +0200938 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
939 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700940 }
Nadav Bar766fb022018-01-07 12:18:03 +0200941 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
942 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -0700943 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800944 // only allow deep buffering for music stream type
945 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +0200946 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700947 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +0200948 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700949 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
950 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +0200951 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800952 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700953 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +0200954 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700955 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Eric Laurentfe231122017-11-17 17:48:06 -0800956 audio_is_linear_pcm(config->format)) {
Nadav Bar766fb022018-01-07 12:18:03 +0200957 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700958 AUDIO_OUTPUT_FLAG_DIRECT);
959 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700960 }
Eric Laurente552edb2014-03-10 17:42:56 -0700961
Nadav Bar766fb022018-01-07 12:18:03 +0200962
Eric Laurentb732cf52014-09-24 19:08:21 -0700963 sp<IOProfile> profile;
964
965 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700966 // and not explicitly requested
Nadav Bar766fb022018-01-07 12:18:03 +0200967 if (((*flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Eric Laurentfe231122017-11-17 17:48:06 -0800968 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
969 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
Eric Laurentb732cf52014-09-24 19:08:21 -0700970 goto non_direct_output;
971 }
972
Andy Hung2ddee192015-12-18 17:34:44 -0800973 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
974 // This prevents creating an offloaded track and tearing it down immediately after start
975 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700976 // FIXME: We should check the audio session here but we do not have it in this context.
977 // This may prevent offloading in rare situations where effects are left active by apps
978 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700979
Nadav Bar766fb022018-01-07 12:18:03 +0200980 if (((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800981 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700982 profile = getProfileForDirectOutput(device,
Eric Laurentfe231122017-11-17 17:48:06 -0800983 config->sample_rate,
984 config->format,
985 config->channel_mask,
Nadav Bar766fb022018-01-07 12:18:03 +0200986 (audio_output_flags_t)*flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700987 }
988
Eric Laurent1c333e22014-05-20 10:48:17 -0700989 if (profile != 0) {
Andy Hungc88b0642018-04-27 15:42:35 -0700990 // exclusive outputs for MMAP and Offload are enforced by different session ids.
991 for (size_t i = 0; i < mOutputs.size(); i++) {
992 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
993 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
994 // reuse direct output if currently open by the same client
995 // and configured with same parameters
996 if ((config->sample_rate == desc->mSamplingRate) &&
Andy Hung5659ed52018-04-30 10:31:26 -0700997 (config->format == desc->mFormat) &&
Andy Hungc88b0642018-04-27 15:42:35 -0700998 (config->channel_mask == desc->mChannelMask) &&
999 (session == desc->mDirectClientSession)) {
1000 desc->mDirectOpenCount++;
1001 ALOGI("getOutputForDevice() reusing direct output %d for session %d",
1002 mOutputs.keyAt(i), session);
1003 return mOutputs.keyAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001004 }
1005 }
1006 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08001007
1008 if (!profile->canOpenNewIo()) {
1009 goto non_direct_output;
Eric Laurente552edb2014-03-10 17:42:56 -07001010 }
Eric Laurent861a6282015-05-18 15:40:16 -07001011
Eric Laurent3974e3b2017-12-07 17:58:43 -08001012 sp<SwAudioOutputDescriptor> outputDesc =
1013 new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurent53b810e2017-12-10 17:25:10 -08001014
Mikhail Naganov708e0382018-05-30 09:53:04 -07001015 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -08001016 String8 address = outputDevices.size() > 0 ? outputDevices.itemAt(0)->mAddress
1017 : String8("");
1018
Nadav Bar766fb022018-01-07 12:18:03 +02001019 status = outputDesc->open(config, device, address, stream, *flags, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07001020
1021 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001022 if (status != NO_ERROR ||
Eric Laurentfe231122017-11-17 17:48:06 -08001023 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
Andy Hung5659ed52018-04-30 10:31:26 -07001024 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->mFormat) ||
Eric Laurentfe231122017-11-17 17:48:06 -08001025 (config->channel_mask != 0 && config->channel_mask != outputDesc->mChannelMask)) {
1026 ALOGV("getOutputForDevice() failed opening direct output: output %d sample rate %d %d,"
1027 "format %d %d, channel mask %04x %04x", output, config->sample_rate,
1028 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
1029 config->channel_mask, outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001030 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001031 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07001032 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001033 // fall back to mixer output if possible when the direct output could not be open
Eric Laurentfe231122017-11-17 17:48:06 -08001034 if (audio_is_linear_pcm(config->format) &&
1035 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -08001036 goto non_direct_output;
1037 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001038 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001039 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001040 outputDesc->mRefCount[stream] = 0;
1041 outputDesc->mStopTime[stream] = 0;
1042 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -08001043 outputDesc->mDirectClientSession = session;
1044
Eric Laurente552edb2014-03-10 17:42:56 -07001045 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001046 mPreviousOutputs = mOutputs;
Eric Laurentf4e63452017-11-06 19:31:46 +00001047 ALOGV("getOutputForDevice() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001048 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001049 return output;
1050 }
1051
Eric Laurentb732cf52014-09-24 19:08:21 -07001052non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001053
1054 // A request for HW A/V sync cannot fallback to a mixed output because time
1055 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001056 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001057 return AUDIO_IO_HANDLE_NONE;
1058 }
1059
Eric Laurente552edb2014-03-10 17:42:56 -07001060 // ignoring channel mask due to downmix capability in mixer
1061
1062 // open a non direct output
1063
1064 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001065 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001066 // get which output is suitable for the specified stream. The actual
1067 // routing change will happen when startOutput() will be called
1068 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1069
Eric Laurent8838a382014-09-08 16:44:28 -07001070 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001071 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1072 output = selectOutput(outputs, *flags, config->format);
Eric Laurente552edb2014-03-10 17:42:56 -07001073 }
Eric Laurentf4e63452017-11-06 19:31:46 +00001074 ALOGW_IF((output == 0), "getOutputForDevice() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001075 "sampling rate %d, format %#x, channels %#x, flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +02001076 stream, config->sample_rate, config->format, config->channel_mask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001077
Eric Laurente552edb2014-03-10 17:42:56 -07001078 return output;
1079}
1080
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001081sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
1082 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1083 if (msdModule != 0) {
1084 DeviceVector msdInputDevices = mAvailableInputDevices.getDevicesFromHwModule(
1085 msdModule->getHandle());
1086 if (!msdInputDevices.isEmpty()) return msdInputDevices.itemAt(0);
1087 }
1088 return 0;
1089}
1090
1091audio_devices_t AudioPolicyManager::getMsdAudioOutDeviceTypes() const {
1092 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1093 if (msdModule != 0) {
1094 return mAvailableOutputDevices.getDeviceTypesFromHwModule(msdModule->getHandle());
1095 }
1096 return AUDIO_DEVICE_NONE;
1097}
1098
1099const AudioPatchCollection AudioPolicyManager::getMsdPatches() const {
1100 AudioPatchCollection msdPatches;
1101 audio_module_handle_t msdModuleHandle = mHwModules.getModuleFromName(
1102 AUDIO_HARDWARE_MODULE_ID_MSD)->getHandle();
1103 if (msdModuleHandle == AUDIO_MODULE_HANDLE_NONE) return msdPatches;
1104 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1105 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1106 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1107 const struct audio_port_config *source = &patch->mPatch.sources[j];
1108 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1109 source->ext.device.hw_module == msdModuleHandle) {
1110 msdPatches.addAudioPatch(patch->mHandle, patch);
1111 }
1112 }
1113 }
1114 return msdPatches;
1115}
1116
1117status_t AudioPolicyManager::getBestMsdAudioProfileFor(audio_devices_t outputDevice,
1118 bool hwAvSync, audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1119{
1120 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1121 if (msdModule == nullptr) {
1122 ALOGE("%s() unable to get MSD module", __func__);
1123 return NO_INIT;
1124 }
1125 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(outputDevice);
1126 if (deviceModule == nullptr) {
1127 ALOGE("%s() unable to get module for %#x", __func__, outputDevice);
1128 return NO_INIT;
1129 }
1130 const InputProfileCollection &inputProfiles = msdModule->getInputProfiles();
1131 if (inputProfiles.isEmpty()) {
1132 ALOGE("%s() no input profiles for MSD module", __func__);
1133 return NO_INIT;
1134 }
1135 const OutputProfileCollection &outputProfiles = deviceModule->getOutputProfiles();
1136 if (outputProfiles.isEmpty()) {
1137 ALOGE("%s() no output profiles for device %#x", __func__, outputDevice);
1138 return NO_INIT;
1139 }
1140 AudioProfileVector msdProfiles;
1141 // Each IOProfile represents a MixPort from audio_policy_configuration.xml
1142 for (const auto &inProfile : inputProfiles) {
1143 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0)) {
1144 msdProfiles.appendVector(inProfile->getAudioProfiles());
1145 }
1146 }
1147 AudioProfileVector deviceProfiles;
1148 for (const auto &outProfile : outputProfiles) {
1149 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0)) {
1150 deviceProfiles.appendVector(outProfile->getAudioProfiles());
1151 }
1152 }
1153 struct audio_config_base bestSinkConfig;
1154 status_t result = msdProfiles.findBestMatchingOutputConfig(deviceProfiles,
1155 compressedFormatsOrder, surroundChannelMasksOrder, true /*preferHigherSamplingRates*/,
1156 &bestSinkConfig);
1157 if (result != NO_ERROR) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001158 ALOGD("%s() no matching profiles found for device: %#x, hwAvSync: %d",
1159 __func__, outputDevice, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001160 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001161 }
1162 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1163 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1164 sinkConfig->format = bestSinkConfig.format;
1165 // For encoded streams force direct flag to prevent downstream mixing.
1166 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1167 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
1168 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1169 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1170 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1171 sourceConfig->format = bestSinkConfig.format;
1172 // Copy input stream directly without any processing (e.g. resampling).
1173 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1174 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1175 if (hwAvSync) {
1176 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1177 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1178 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1179 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1180 }
1181 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1182 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1183 sinkConfig->config_mask |= config_mask;
1184 sourceConfig->config_mask |= config_mask;
1185 return NO_ERROR;
1186}
1187
1188PatchBuilder AudioPolicyManager::buildMsdPatch(audio_devices_t outputDevice) const
1189{
1190 PatchBuilder patchBuilder;
1191 patchBuilder.addSource(getMsdAudioInDevice()).
1192 addSink(findDevice(mAvailableOutputDevices, outputDevice));
1193 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1194 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
1195 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1196 // For now, we just forcefully try with HwAvSync first.
1197 status_t res = getBestMsdAudioProfileFor(outputDevice, true /*hwAvSync*/,
1198 &sourceConfig, &sinkConfig) == NO_ERROR ? NO_ERROR :
1199 getBestMsdAudioProfileFor(
1200 outputDevice, false /*hwAvSync*/, &sourceConfig, &sinkConfig);
1201 if (res == NO_ERROR) {
1202 // Found a matching profile for encoded audio. Re-create PatchBuilder with this config.
1203 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1204 }
1205 ALOGV("%s() no matching profile found. Fall through to default PCM patch"
1206 " supporting PCM format conversion.", __func__);
1207 return patchBuilder;
1208}
1209
1210status_t AudioPolicyManager::setMsdPatch(audio_devices_t outputDevice) {
1211 ALOGV("%s() for outputDevice %#x", __func__, outputDevice);
1212 if (outputDevice == AUDIO_DEVICE_NONE) {
1213 // Use media strategy for unspecified output device. This should only
1214 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1215 // therefore invalidate explicit routing requests.
1216 outputDevice = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
1217 }
1218 PatchBuilder patchBuilder = buildMsdPatch(outputDevice);
1219 const struct audio_patch* patch = patchBuilder.patch();
1220 const AudioPatchCollection msdPatches = getMsdPatches();
1221 if (!msdPatches.isEmpty()) {
1222 LOG_ALWAYS_FATAL_IF(msdPatches.size() > 1,
1223 "The current MSD prototype only supports one output patch");
1224 sp<AudioPatch> currentPatch = msdPatches.valueAt(0);
1225 if (audio_patches_are_equal(&currentPatch->mPatch, patch)) {
1226 return NO_ERROR;
1227 }
1228 releaseAudioPatch(currentPatch->mHandle, mUidCached);
1229 }
1230 status_t status = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1231 patch, 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1232 ALOGE_IF(status != NO_ERROR, "%s() error %d creating MSD audio patch", __func__, status);
1233 ALOGI_IF(status == NO_ERROR, "%s() Patch created from MSD_IN to "
1234 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__, outputDevice,
1235 patch->sources[0].format, patch->sources[0].channel_mask, patch->sources[0].sample_rate);
1236 return status;
1237}
1238
Eric Laurente0720872014-03-11 09:30:41 -07001239audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001240 audio_output_flags_t flags,
1241 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001242{
1243 // select one output among several that provide a path to a particular device or set of
1244 // devices (the list was previously build by getOutputsForDevice()).
1245 // The priority is as follows:
1246 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001247 // 2: the output with the bit depth the closest to the requested one
1248 // 3: the primary output
1249 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001250
1251 if (outputs.size() == 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001252 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001253 }
1254 if (outputs.size() == 1) {
1255 return outputs[0];
1256 }
1257
1258 int maxCommonFlags = 0;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001259 audio_io_handle_t outputForFlags = AUDIO_IO_HANDLE_NONE;
1260 audio_io_handle_t outputForPrimary = AUDIO_IO_HANDLE_NONE;
1261 audio_io_handle_t outputForFormat = AUDIO_IO_HANDLE_NONE;
Eric Laurente6930022016-02-11 10:20:40 -08001262 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1263 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001264
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001265 for (audio_io_handle_t output : outputs) {
1266 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001267 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001268 // if a valid format is specified, skip output if not compatible
1269 if (format != AUDIO_FORMAT_INVALID) {
1270 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Andy Hung5659ed52018-04-30 10:31:26 -07001271 if (format != outputDesc->mFormat) {
Eric Laurent8838a382014-09-08 16:44:28 -07001272 continue;
1273 }
1274 } else if (!audio_is_linear_pcm(format)) {
1275 continue;
1276 }
Eric Laurente6930022016-02-11 10:20:40 -08001277 if (AudioPort::isBetterFormatMatch(
1278 outputDesc->mFormat, bestFormat, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001279 outputForFormat = output;
Eric Laurente6930022016-02-11 10:20:40 -08001280 bestFormat = outputDesc->mFormat;
1281 }
Eric Laurent8838a382014-09-08 16:44:28 -07001282 }
1283
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001284 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001285 if (commonFlags >= maxCommonFlags) {
1286 if (commonFlags == maxCommonFlags) {
Andy Hungc9901522017-11-10 20:07:54 -08001287 if (format != AUDIO_FORMAT_INVALID
1288 && AudioPort::isBetterFormatMatch(
1289 outputDesc->mFormat, bestFormatForFlags, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001290 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001291 bestFormatForFlags = outputDesc->mFormat;
1292 }
1293 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001294 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001295 maxCommonFlags = commonFlags;
1296 bestFormatForFlags = outputDesc->mFormat;
1297 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001298 ALOGV("selectOutput() commonFlags for output %d, %04x", output, commonFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001299 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001300 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001301 outputForPrimary = output;
Eric Laurente552edb2014-03-10 17:42:56 -07001302 }
1303 }
1304 }
1305
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001306 if (outputForFlags != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001307 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001308 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001309 if (outputForFormat != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001310 return outputForFormat;
1311 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001312 if (outputForPrimary != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001313 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001314 }
1315
1316 return outputs[0];
1317}
1318
Eric Laurent8fc147b2018-07-22 19:13:55 -07001319status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001320{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001321 ALOGV("%s portId %d", __FUNCTION__, portId);
1322
1323 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1324 if (outputDesc == 0) {
1325 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001326 return BAD_VALUE;
1327 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001328 sp<TrackClientDescriptor> client = outputDesc->clients()[portId];
1329 audio_stream_type_t stream = client->stream();
1330 audio_session_t session = client->session();
Eric Laurente552edb2014-03-10 17:42:56 -07001331
Eric Laurent8fc147b2018-07-22 19:13:55 -07001332 ALOGV("startOutput() output %d, stream %d, session %d",
1333 outputDesc->mIoHandle, stream, session);
Eric Laurentc75307b2015-03-17 15:29:32 -07001334
Eric Laurent733ce942017-12-07 12:18:25 -08001335 status_t status = outputDesc->start();
1336 if (status != NO_ERROR) {
1337 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001338 }
1339
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001340 // Routing?
1341 mOutputRoutes.incRouteActivity(session);
1342
Eric Laurentc75307b2015-03-17 15:29:32 -07001343 audio_devices_t newDevice;
Eric Laurentc40d9692016-04-13 19:14:13 -07001344 AudioMix *policyMix = NULL;
1345 const char *address = NULL;
Eric Laurentc75307b2015-03-17 15:29:32 -07001346 if (outputDesc->mPolicyMix != NULL) {
Eric Laurentc40d9692016-04-13 19:14:13 -07001347 policyMix = outputDesc->mPolicyMix;
1348 address = policyMix->mDeviceAddress.string();
1349 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1350 newDevice = policyMix->mDeviceType;
1351 } else {
1352 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1353 }
Eric Laurent2157f5b2018-04-25 18:33:02 -07001354 } else if (mOutputRoutes.getAndClearRouteChanged(session)) {
Eric Laurent493404d2015-04-21 15:07:36 -07001355 newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurentf3a5a602018-05-22 18:42:55 -07001356 if (newDevice != outputDesc->device()) {
Eric Laurent8fc147b2018-07-22 19:13:55 -07001357 checkStrategyRoute(getStrategy(stream), outputDesc->mIoHandle);
Eric Laurentf3a5a602018-05-22 18:42:55 -07001358 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001359 } else {
1360 newDevice = AUDIO_DEVICE_NONE;
1361 }
1362
1363 uint32_t delayMs = 0;
1364
Eric Laurent733ce942017-12-07 12:18:25 -08001365 status = startSource(outputDesc, stream, newDevice, address, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001366
1367 if (status != NO_ERROR) {
1368 mOutputRoutes.decRouteActivity(session);
Eric Laurent733ce942017-12-07 12:18:25 -08001369 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001370 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001371 }
1372 // Automatically enable the remote submix input when output is started on a re routing mix
1373 // of type MIX_TYPE_RECORDERS
Eric Laurentc40d9692016-04-13 19:14:13 -07001374 if (audio_is_remote_submix_device(newDevice) && policyMix != NULL &&
1375 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001376 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1377 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Eric Laurentc40d9692016-04-13 19:14:13 -07001378 address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001379 "remote-submix");
1380 }
1381
1382 if (delayMs != 0) {
1383 usleep(delayMs * 1000);
1384 }
1385
1386 return status;
1387}
1388
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001389status_t AudioPolicyManager::startSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurentc75307b2015-03-17 15:29:32 -07001390 audio_stream_type_t stream,
1391 audio_devices_t device,
Eric Laurentc40d9692016-04-13 19:14:13 -07001392 const char *address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001393 uint32_t *delayMs)
1394{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001395 // cannot start playback of STREAM_TTS if any other output is being used
1396 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001397
1398 *delayMs = 0;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001399 if (stream == AUDIO_STREAM_TTS) {
1400 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001401 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001402 return INVALID_OPERATION;
1403 } else {
1404 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1405 }
1406 } else {
1407 // some playback other than beacon starts
1408 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1409 }
1410
Eric Laurent77305a62016-07-25 16:39:22 -07001411 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001412 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001413 bool force = !outputDesc->isActive() &&
1414 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001415
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001416 // requiresMuteCheck is false when we can bypass mute strategy.
1417 // It covers a common case when there is no materially active audio
1418 // and muting would result in unnecessary delay and dropped audio.
1419 const uint32_t outputLatencyMs = outputDesc->latency();
1420 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1421
Eric Laurente552edb2014-03-10 17:42:56 -07001422 // increment usage count for this stream on the requested output:
1423 // NOTE that the usage count is the same for duplicated output and hardware output which is
1424 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1425 outputDesc->changeRefCount(stream, 1);
1426
Eric Laurent36829f92017-04-07 19:04:42 -07001427 if (stream == AUDIO_STREAM_MUSIC) {
1428 selectOutputForMusicEffects();
1429 }
1430
Eric Laurent493404d2015-04-21 15:07:36 -07001431 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001432 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001433 if (device == AUDIO_DEVICE_NONE) {
1434 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001435 }
Eric Laurent36829f92017-04-07 19:04:42 -07001436
Eric Laurente552edb2014-03-10 17:42:56 -07001437 routing_strategy strategy = getStrategy(stream);
1438 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001439 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1440 (beaconMuteLatency > 0);
1441 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001442 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001443 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001444 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001445 // An output has a shared device if
1446 // - managed by the same hw module
1447 // - supports the currently selected device
1448 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
1449 && (desc->supportedDevices() & device) != AUDIO_DEVICE_NONE;
1450
Eric Laurent77305a62016-07-25 16:39:22 -07001451 // force a device change if any other output is:
1452 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001453 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001454 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001455 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001456 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001457 // change the device currently selected by the other output.
1458 if (sharedDevice &&
Eric Laurent77305a62016-07-25 16:39:22 -07001459 desc->device() != device &&
Eric Laurent77305a62016-07-25 16:39:22 -07001460 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001461 force = true;
1462 }
1463 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001464 // a notification so that audio focus effect can propagate, or that a mute/unmute
1465 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001466 const uint32_t latencyMs = desc->latency();
1467 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1468
1469 if (shouldWait && isActive && (waitMs < latencyMs)) {
1470 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001471 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001472
1473 // Require mute check if another output is on a shared device
1474 // and currently active to have proper drain and avoid pops.
1475 // Note restoring AudioTracks onto this output needs to invoke
1476 // a volume ramp if there is no mute.
1477 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001478 }
1479 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001480
1481 const uint32_t muteWaitMs =
1482 setOutputDevice(outputDesc, device, force, 0, NULL, address, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001483
Eric Laurente552edb2014-03-10 17:42:56 -07001484 // apply volume rules for current stream and device if necessary
1485 checkAndSetVolume(stream,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001486 mVolumeCurves->getVolumeIndex(stream, outputDesc->device()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001487 outputDesc,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001488 outputDesc->device());
Eric Laurente552edb2014-03-10 17:42:56 -07001489
1490 // update the outputs if starting an output with a stream that can affect notification
1491 // routing
1492 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001493
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001494 // force reevaluating accessibility routing when ringtone or alarm starts
1495 if (strategy == STRATEGY_SONIFICATION) {
1496 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1497 }
Eric Laurentdc462862016-07-19 12:29:53 -07001498
1499 if (waitMs > muteWaitMs) {
1500 *delayMs = waitMs - muteWaitMs;
1501 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001502
1503 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1504 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1505 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1506 // change occurs after the MixerThread starts and causes a stream volume
1507 // glitch.
1508 //
1509 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001510 }
Eric Laurentdc462862016-07-19 12:29:53 -07001511
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001512 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1513 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1514 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1515 }
1516
Tomoharu Kasaharaa81f0982018-01-18 20:55:02 +09001517 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1518 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1519 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1520 }
1521
Eric Laurente552edb2014-03-10 17:42:56 -07001522 return NO_ERROR;
1523}
1524
Eric Laurent8fc147b2018-07-22 19:13:55 -07001525status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001526{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001527 ALOGV("%s portId %d", __FUNCTION__, portId);
1528
1529 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1530 if (outputDesc == 0) {
1531 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001532 return BAD_VALUE;
1533 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001534 sp<TrackClientDescriptor> client = outputDesc->clients()[portId];
1535 audio_stream_type_t stream = client->stream();
1536 audio_session_t session = client->session();
Eric Laurente552edb2014-03-10 17:42:56 -07001537
Eric Laurent8fc147b2018-07-22 19:13:55 -07001538 ALOGV("stopOutput() output %d, stream %d, session %d", outputDesc->mIoHandle, stream, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001539
Eric Laurentc75307b2015-03-17 15:29:32 -07001540 if (outputDesc->mRefCount[stream] == 1) {
1541 // Automatically disable the remote submix input when output is stopped on a
1542 // re routing mix of type MIX_TYPE_RECORDERS
1543 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1544 outputDesc->mPolicyMix != NULL &&
1545 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1546 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1547 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001548 outputDesc->mPolicyMix->mDeviceAddress,
Eric Laurentc75307b2015-03-17 15:29:32 -07001549 "remote-submix");
1550 }
1551 }
1552
1553 // Routing?
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001554 bool forceDeviceUpdate = false;
Eric Laurentc75307b2015-03-17 15:29:32 -07001555 if (outputDesc->mRefCount[stream] > 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001556 int activityCount = mOutputRoutes.decRouteActivity(session);
1557 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1558
1559 if (forceDeviceUpdate) {
1560 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1561 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001562 }
1563
Eric Laurent3974e3b2017-12-07 17:58:43 -08001564 status_t status = stopSource(outputDesc, stream, forceDeviceUpdate);
1565
Eric Laurent733ce942017-12-07 12:18:25 -08001566 if (status == NO_ERROR ) {
1567 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001568 }
1569 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001570}
1571
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001572status_t AudioPolicyManager::stopSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001573 audio_stream_type_t stream,
1574 bool forceDeviceUpdate)
Eric Laurentc75307b2015-03-17 15:29:32 -07001575{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001576 // always handle stream stop, check which stream type is stopping
1577 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1578
Eric Laurente552edb2014-03-10 17:42:56 -07001579 if (outputDesc->mRefCount[stream] > 0) {
1580 // decrement usage count of this stream on the output
1581 outputDesc->changeRefCount(stream, -1);
Paul McLeanaa981192015-03-21 09:55:15 -07001582
Eric Laurente552edb2014-03-10 17:42:56 -07001583 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001584 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001585 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001586 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001587 // delay the device switch by twice the latency because stopOutput() is executed when
1588 // the track stop() command is received and at that time the audio track buffer can
1589 // still contain data that needs to be drained. The latency only covers the audio HAL
1590 // and kernel buffers. Also the latency does not always include additional delay in the
1591 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001592 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001593
1594 // force restoring the device selection on other active outputs if it differs from the
1595 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001596 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001597 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001598 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001599 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001600 desc->isActive() &&
1601 outputDesc->sharesHwModuleWith(desc) &&
1602 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001603 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1604 bool force = desc->device() != newDevice2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001605
Eric Laurentc75307b2015-03-17 15:29:32 -07001606 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001607 newDevice2,
1608 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001609 delayMs);
1610 // re-apply device specific volume if not done by setOutputDevice()
1611 if (!force) {
1612 applyStreamVolumes(desc, newDevice2, delayMs);
1613 }
Eric Laurente552edb2014-03-10 17:42:56 -07001614 }
1615 }
1616 // update the outputs if stopping one with a stream that can affect notification routing
1617 handleNotificationRoutingForStream(stream);
1618 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001619
1620 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1621 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1622 setStrategyMute(STRATEGY_SONIFICATION, false, outputDesc);
1623 }
1624
Eric Laurent36829f92017-04-07 19:04:42 -07001625 if (stream == AUDIO_STREAM_MUSIC) {
1626 selectOutputForMusicEffects();
1627 }
Eric Laurente552edb2014-03-10 17:42:56 -07001628 return NO_ERROR;
1629 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001630 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001631 return INVALID_OPERATION;
1632 }
1633}
1634
Eric Laurent8fc147b2018-07-22 19:13:55 -07001635void AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001636{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001637 ALOGV("%s portId %d", __FUNCTION__, portId);
1638
1639 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1640 if (outputDesc == 0) {
1641 ALOGW("releaseOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001642 return;
1643 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001644 sp<TrackClientDescriptor> client = outputDesc->clients()[portId];
1645 audio_session_t session = client->session();
1646
1647 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001648
Paul McLeanaa981192015-03-21 09:55:15 -07001649 // Routing
1650 mOutputRoutes.removeRoute(session);
1651
Eric Laurent8fc147b2018-07-22 19:13:55 -07001652 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1653 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001654 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07001655 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001656 return;
1657 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001658 if (--outputDesc->mDirectOpenCount == 0) {
1659 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07001660 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001661 }
1662 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001663 outputDesc->clients().erase(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001664}
1665
1666
Eric Laurentcaf7f482014-11-25 17:50:47 -08001667status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1668 audio_io_handle_t *input,
1669 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001670 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001671 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001672 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001673 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001674 input_type_t *inputType,
1675 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001676{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001677 ALOGV("getInputForAttr() source %d, sampling rate %d, format %#x, channel mask %#x,"
Eric Laurentcaf7f482014-11-25 17:50:47 -08001678 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001679 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001680
Eric Laurentad2e7b92017-09-14 20:06:42 -07001681 status_t status = NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -08001682 // handle legacy remote submix case where the address was not always specified
1683 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001684 audio_source_t halInputSource;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001685 audio_source_t inputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001686 AudioMix *policyMix = NULL;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001687 DeviceVector inputDevices;
Eric Laurent8fc147b2018-07-22 19:13:55 -07001688 sp<AudioInputDescriptor> inputDesc;
1689 sp<RecordClientDescriptor> clientDesc;
1690 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Eric Laurent20b9ef02016-12-05 11:03:16 -08001691
Eric Laurentfe231122017-11-17 17:48:06 -08001692 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1693 inputSource = AUDIO_SOURCE_MIC;
1694 }
1695
Paul McLean466dc8e2015-04-17 13:15:36 -06001696 // Explicit routing?
1697 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -07001698 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
jiabinc0c831a2018-01-29 17:55:15 -08001699 deviceDesc = mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001700 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001701 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
Paul McLean466dc8e2015-04-17 13:15:36 -06001702
Eric Laurentad2e7b92017-09-14 20:06:42 -07001703 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1704 // possible
1705 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1706 *input != AUDIO_IO_HANDLE_NONE) {
1707 ssize_t index = mInputs.indexOfKey(*input);
1708 if (index < 0) {
1709 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1710 status = BAD_VALUE;
1711 goto error;
1712 }
1713 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1714 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1715 if (audioSession == 0) {
1716 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1717 status = BAD_VALUE;
1718 goto error;
1719 }
1720 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1721 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001722 // corresponds to a new client and is only permitted from the same UID.
1723 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurentad2e7b92017-09-14 20:06:42 -07001724 if (audioSession->openCount() == 1) {
1725 audioSession->setUid(uid);
1726 } else if (audioSession->uid() != uid) {
Eric Laurent331679c2018-04-16 17:03:16 -07001727 if (!audioSession->isSilenced()) {
1728 ALOGW("getInputForAttr() bad uid %d for session %d uid %d",
1729 uid, session, audioSession->uid());
1730 status = INVALID_OPERATION;
1731 goto error;
1732 }
1733 audioSession->setUid(uid);
1734 audioSession->setSilenced(false);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001735 }
1736 audioSession->changeOpenCount(1);
1737 *inputType = API_INPUT_LEGACY;
1738 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1739 *portId = AudioPort::getNextUniqueId();
1740 }
Mikhail Naganov708e0382018-05-30 09:53:04 -07001741 inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(inputDesc->mDevice);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001742 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1743 : AUDIO_PORT_HANDLE_NONE;
1744 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
1745
Eric Laurent8fc147b2018-07-22 19:13:55 -07001746 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001747 }
1748
1749 *input = AUDIO_IO_HANDLE_NONE;
1750 *inputType = API_INPUT_INVALID;
1751
Eric Laurentad2e7b92017-09-14 20:06:42 -07001752 halInputSource = inputSource;
1753
1754 // TODO: check for existing client for this port ID
1755 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1756 *portId = AudioPort::getNextUniqueId();
1757 }
1758
1759 audio_devices_t device;
1760
Eric Laurentc447ded2015-01-06 08:47:05 -08001761 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001762 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001763 status = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
1764 if (status != NO_ERROR) {
1765 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001766 }
1767 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001768 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1769 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001770 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001771 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001772 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001773 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001774 status = BAD_VALUE;
1775 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001776 }
Eric Laurentc722f302014-12-10 11:21:49 -08001777 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001778 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001779 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1780 // there is an external policy, but this input is attached to a mix of recorders,
1781 // meaning it receives audio injected into the framework, so the recorder doesn't
1782 // know about it and is therefore considered "legacy"
1783 *inputType = API_INPUT_LEGACY;
1784 } else {
1785 // recording a mix of players defined by an external policy, we're rerouting for
1786 // an external policy
1787 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1788 }
Eric Laurentc722f302014-12-10 11:21:49 -08001789 } else if (audio_is_remote_submix_device(device)) {
1790 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001791 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001792 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1793 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001794 } else {
1795 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001796 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001797
Eric Laurent599c7582015-12-07 18:05:55 -08001798 }
1799
1800 *input = getInputForDevice(device, address, session, uid, inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001801 config, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001802 policyMix);
1803 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001804 status = INVALID_OPERATION;
1805 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001806 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001807
Mikhail Naganov708e0382018-05-30 09:53:04 -07001808 inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -07001809 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1810 : AUDIO_PORT_HANDLE_NONE;
1811
Eric Laurent8fc147b2018-07-22 19:13:55 -07001812exit:
1813 clientDesc = new RecordClientDescriptor(*portId, uid, session,
1814 *attr, *config, requestedDeviceId, inputSource, flags);
1815 inputDesc = mInputs.valueFor(*input);
1816 inputDesc->clients().emplace(*portId, clientDesc);
1817
1818 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
1819 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001820
Eric Laurent599c7582015-12-07 18:05:55 -08001821 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001822
1823error:
1824 mInputRoutes.removeRoute(session);
1825 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001826}
1827
1828
1829audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1830 String8 address,
1831 audio_session_t session,
1832 uid_t uid,
1833 audio_source_t inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001834 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08001835 audio_input_flags_t flags,
1836 AudioMix *policyMix)
1837{
1838 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1839 audio_source_t halInputSource = inputSource;
1840 bool isSoundTrigger = false;
1841
1842 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1843 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1844 if (index >= 0) {
1845 input = mSoundTriggerSessions.valueFor(session);
1846 isSoundTrigger = true;
1847 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1848 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1849 } else {
1850 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001851 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001852 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08001853 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001854 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001855 }
1856
Andy Hungf129b032015-04-07 13:45:50 -07001857 // find a compatible input profile (not necessarily identical in parameters)
1858 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08001859 // sampling rate and flags may be updated by getInputProfile
1860 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
1861 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07001862 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08001863 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07001864 audio_input_flags_t profileFlags = flags;
1865 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07001866 profileFormat = config->format; // reset each time through loop, in case it is updated
Eric Laurent275e8e92014-11-30 15:14:47 -08001867 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001868 profileSamplingRate, profileFormat, profileChannelMask,
1869 profileFlags);
1870 if (profile != 0) {
1871 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001872 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1873 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001874 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1875 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1876 } else { // fail
Glenn Kastenfaa10a62017-05-25 15:52:05 -07001877 ALOGW("getInputForDevice() could not find profile for device 0x%X, "
Eric Laurentfe231122017-11-17 17:48:06 -08001878 "sampling rate %u, format %#x, channel mask 0x%X, flags %#x",
1879 device, config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001880 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001881 }
Eric Laurente552edb2014-03-10 17:42:56 -07001882 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001883 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08001884 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08001885 if (samplingRate == 0) {
1886 samplingRate = profileSamplingRate;
1887 }
Eric Laurente552edb2014-03-10 17:42:56 -07001888
Eric Laurent322b4d22015-04-03 15:57:54 -07001889 if (profile->getModuleHandle() == 0) {
1890 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001891 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001892 }
1893
Eric Laurent599c7582015-12-07 18:05:55 -08001894 sp<AudioSession> audioSession = new AudioSession(session,
Eric Laurentfe231122017-11-17 17:48:06 -08001895 inputSource,
1896 config->format,
1897 samplingRate,
1898 config->channel_mask,
1899 flags,
1900 uid,
Eric Laurenta18dced2018-07-20 15:14:54 -07001901 isSoundTrigger);
Eric Laurent599c7582015-12-07 18:05:55 -08001902
Eric Laurent3974e3b2017-12-07 17:58:43 -08001903 if (!profile->canOpenNewIo()) {
1904 return AUDIO_IO_HANDLE_NONE;
1905 }
1906
Eric Laurentfe231122017-11-17 17:48:06 -08001907 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001908
Eric Laurentfe231122017-11-17 17:48:06 -08001909 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
1910 lConfig.sample_rate = profileSamplingRate;
1911 lConfig.channel_mask = profileChannelMask;
1912 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07001913
Eric Laurent53b810e2017-12-10 17:25:10 -08001914 if (address == "") {
Mikhail Naganov708e0382018-05-30 09:53:04 -07001915 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -08001916 // the inputs vector must be of size >= 1, but we don't want to crash here
1917 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress : String8("");
1918 }
1919
Eric Laurentfe231122017-11-17 17:48:06 -08001920 status_t status = inputDesc->open(&lConfig, device, address,
1921 halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001922
1923 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001924 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08001925 (profileSamplingRate != lConfig.sample_rate) ||
1926 !audio_formats_match(profileFormat, lConfig.format) ||
1927 (profileChannelMask != lConfig.channel_mask)) {
1928 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001929 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08001930 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001931 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001932 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07001933 }
Eric Laurent599c7582015-12-07 18:05:55 -08001934 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001935 }
1936
Eric Laurentc722f302014-12-10 11:21:49 -08001937 inputDesc->mPolicyMix = policyMix;
Eric Laurent599c7582015-12-07 18:05:55 -08001938 inputDesc->addAudioSession(session, audioSession);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001939
Eric Laurent599c7582015-12-07 18:05:55 -08001940 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001941 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001942
Eric Laurent599c7582015-12-07 18:05:55 -08001943 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001944}
1945
Eric Laurentbb948092017-01-23 18:33:30 -08001946//static
1947bool AudioPolicyManager::isConcurrentSource(audio_source_t source)
1948{
1949 return (source == AUDIO_SOURCE_HOTWORD) ||
1950 (source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
1951 (source == AUDIO_SOURCE_FM_TUNER);
1952}
1953
Eric Laurentfb66dd92016-01-28 18:32:03 -08001954bool AudioPolicyManager::isConcurentCaptureAllowed(const sp<AudioInputDescriptor>& inputDesc,
1955 const sp<AudioSession>& audioSession)
1956{
1957 // Do not allow capture if an active voice call is using a software patch and
1958 // the call TX source device is on the same HW module.
1959 // FIXME: would be better to refine to only inputs whose profile connects to the
1960 // call TX device but this information is not in the audio patch
1961 if (mCallTxPatch != 0 &&
1962 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1963 return false;
1964 }
1965
1966 // starting concurrent capture is enabled if:
1967 // 1) capturing for re-routing
1968 // 2) capturing for HOTWORD source
1969 // 3) capturing for FM TUNER source
1970 // 3) All other active captures are either for re-routing or HOTWORD
1971
1972 if (is_virtual_input_device(inputDesc->mDevice) ||
Eric Laurentbb948092017-01-23 18:33:30 -08001973 isConcurrentSource(audioSession->inputSource())) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001974 return true;
1975 }
1976
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001977 for (const auto& activeInput : mInputs.getActiveInputs()) {
Eric Laurentbb948092017-01-23 18:33:30 -08001978 if (!isConcurrentSource(activeInput->inputSource(true)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001979 !is_virtual_input_device(activeInput->mDevice)) {
1980 return false;
1981 }
1982 }
1983
1984 return true;
1985}
1986
Chris Thornton2b864642017-06-27 21:26:07 -07001987// FIXME: remove when concurrent capture is ready. This is a hack to work around bug b/63083537.
1988bool AudioPolicyManager::soundTriggerSupportsConcurrentCapture() {
1989 if (!mHasComputedSoundTriggerSupportsConcurrentCapture) {
1990 bool soundTriggerSupportsConcurrentCapture = false;
1991 unsigned int numModules = 0;
1992 struct sound_trigger_module_descriptor* nModules = NULL;
1993
1994 status_t status = SoundTrigger::listModules(nModules, &numModules);
1995 if (status == NO_ERROR && numModules != 0) {
1996 nModules = (struct sound_trigger_module_descriptor*) calloc(
1997 numModules, sizeof(struct sound_trigger_module_descriptor));
1998 if (nModules == NULL) {
1999 // We failed to malloc the buffer, so just say no for now, and hope that we have more
2000 // ram the next time this function is called.
2001 ALOGE("Failed to allocate buffer for module descriptors");
2002 return false;
2003 }
2004
2005 status = SoundTrigger::listModules(nModules, &numModules);
2006 if (status == NO_ERROR) {
2007 soundTriggerSupportsConcurrentCapture = true;
2008 for (size_t i = 0; i < numModules; ++i) {
2009 soundTriggerSupportsConcurrentCapture &=
2010 nModules[i].properties.concurrent_capture;
2011 }
2012 }
2013 free(nModules);
2014 }
2015 mSoundTriggerSupportsConcurrentCapture = soundTriggerSupportsConcurrentCapture;
2016 mHasComputedSoundTriggerSupportsConcurrentCapture = true;
2017 }
2018 return mSoundTriggerSupportsConcurrentCapture;
2019}
2020
Eric Laurentfb66dd92016-01-28 18:32:03 -08002021
Eric Laurent8fc147b2018-07-22 19:13:55 -07002022status_t AudioPolicyManager::startInput(audio_port_handle_t portId,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002023 bool silenced,
Eric Laurentfb66dd92016-01-28 18:32:03 -08002024 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07002025{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002026 *concurrency = API_INPUT_CONCURRENCY_NONE;
2027
2028 ALOGV("%s portId %d", __FUNCTION__, portId);
2029
2030 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2031 if (inputDesc == 0) {
2032 ALOGW("startInput() no input for client %d", portId);
2033 return BAD_VALUE;
2034 }
2035 sp<RecordClientDescriptor> client = inputDesc->clients()[portId];
2036 audio_session_t session = client->session();
2037 audio_io_handle_t input = inputDesc->mIoHandle;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002038
2039 ALOGV("AudioPolicyManager::startInput(input:%d, session:%d, silenced:%d, concurrency:%d)",
2040 input, session, silenced, *concurrency);
2041
Eric Laurent599c7582015-12-07 18:05:55 -08002042 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
2043 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07002044 ALOGW("startInput() unknown session %d on input %d", session, input);
2045 return BAD_VALUE;
2046 }
2047
Eric Laurent74708e72017-04-07 17:13:42 -07002048 if (!is_virtual_input_device(inputDesc->mDevice)) {
2049 if (mCallTxPatch != 0 &&
2050 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
2051 ALOGW("startInput(%d) failed: call in progress", input);
Ray Essick84e84a52018-05-03 18:45:07 -07002052 *concurrency |= API_INPUT_CONCURRENCY_CALL;
Eric Laurent74708e72017-04-07 17:13:42 -07002053 return INVALID_OPERATION;
2054 }
2055
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002056 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002057
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002058 // If a UID is idle and records silence and another not silenced recording starts
2059 // from another UID (idle or active) we stop the current idle UID recording in
2060 // favor of the new one - "There can be only one" TM
2061 if (!silenced) {
2062 for (const auto& activeDesc : activeInputs) {
2063 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
2064 activeDesc->getId() == inputDesc->getId()) {
2065 continue;
2066 }
2067
2068 AudioSessionCollection activeSessions = activeDesc->getAudioSessions(
2069 true /*activeOnly*/);
2070 sp<AudioSession> activeSession = activeSessions.valueAt(0);
2071 if (activeSession->isSilenced()) {
Eric Laurent8fc147b2018-07-22 19:13:55 -07002072 closeSession(activeDesc, activeSession);
2073 ALOGV("startInput() session %d stopping silenced session %d", session, activeSession->session());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002074 activeInputs = mInputs.getActiveInputs();
2075 }
2076 }
2077 }
2078
2079 for (const auto& activeDesc : activeInputs) {
Eric Laurentcb4dae22017-07-01 19:39:32 -07002080 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
2081 activeDesc->getId() == inputDesc->getId()) {
2082 continue;
2083 }
2084
Eric Laurent74708e72017-04-07 17:13:42 -07002085 audio_source_t activeSource = activeDesc->inputSource(true);
2086 if (audioSession->inputSource() == AUDIO_SOURCE_HOTWORD) {
2087 if (activeSource == AUDIO_SOURCE_HOTWORD) {
2088 if (activeDesc->hasPreemptedSession(session)) {
2089 ALOGW("startInput(%d) failed for HOTWORD: "
2090 "other input %d already started for HOTWORD",
2091 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07002092 *concurrency |= API_INPUT_CONCURRENCY_HOTWORD;
Eric Laurent74708e72017-04-07 17:13:42 -07002093 return INVALID_OPERATION;
2094 }
2095 } else {
2096 ALOGV("startInput(%d) failed for HOTWORD: other input %d already started",
2097 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07002098 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07002099 return INVALID_OPERATION;
2100 }
2101 } else {
2102 if (activeSource != AUDIO_SOURCE_HOTWORD) {
2103 ALOGW("startInput(%d) failed: other input %d already started",
2104 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07002105 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07002106 return INVALID_OPERATION;
2107 }
2108 }
2109 }
2110
Chris Thornton2b864642017-06-27 21:26:07 -07002111 // We only need to check if the sound trigger session supports concurrent capture if the
2112 // input is also a sound trigger input. Otherwise, we should preempt any hotword stream
2113 // that's running.
2114 const bool allowConcurrentWithSoundTrigger =
2115 inputDesc->isSoundTrigger() ? soundTriggerSupportsConcurrentCapture() : false;
2116
Eric Laurent74708e72017-04-07 17:13:42 -07002117 // if capture is allowed, preempt currently active HOTWORD captures
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002118 for (const auto& activeDesc : activeInputs) {
Chris Thornton2b864642017-06-27 21:26:07 -07002119 if (allowConcurrentWithSoundTrigger && activeDesc->isSoundTrigger()) {
2120 continue;
2121 }
2122
Eric Laurent74708e72017-04-07 17:13:42 -07002123 audio_source_t activeSource = activeDesc->inputSource(true);
2124 if (activeSource == AUDIO_SOURCE_HOTWORD) {
2125 AudioSessionCollection activeSessions =
2126 activeDesc->getAudioSessions(true /*activeOnly*/);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002127 sp<AudioSession> activeSession = activeSessions[0];
Eric Laurent74708e72017-04-07 17:13:42 -07002128 SortedVector<audio_session_t> sessions = activeDesc->getPreemptedSessions();
Ray Essick84e84a52018-05-03 18:45:07 -07002129 *concurrency |= API_INPUT_CONCURRENCY_PREEMPT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002130 sessions.add(activeSession->session());
Eric Laurent74708e72017-04-07 17:13:42 -07002131 inputDesc->setPreemptedSessions(sessions);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002132 closeSession(inputDesc, activeSession);
Eric Laurent74708e72017-04-07 17:13:42 -07002133 ALOGV("startInput(%d) for HOTWORD preempting HOTWORD input %d",
2134 input, activeDesc->mIoHandle);
2135 }
2136 }
2137 }
Eric Laurente552edb2014-03-10 17:42:56 -07002138
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002139 // Make sure we start with the correct silence state
2140 audioSession->setSilenced(silenced);
2141
Eric Laurent313d1e72016-01-29 09:56:57 -08002142 // increment activity count before calling getNewInputDevice() below as only active sessions
2143 // are considered for device selection
Eric Laurenta18dced2018-07-20 15:14:54 -07002144 inputDesc->changeRefCount(session, 1);
Eric Laurent313d1e72016-01-29 09:56:57 -08002145
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002146 // Routing?
2147 mInputRoutes.incRouteActivity(session);
2148
Eric Laurent2157f5b2018-04-25 18:33:02 -07002149 if (audioSession->activeCount() == 1 || mInputRoutes.getAndClearRouteChanged(session)) {
Eric Laurent271a93e2016-09-29 14:47:06 -07002150 // indicate active capture to sound trigger service if starting capture from a mic on
2151 // primary HW module
Eric Laurentf7c50102016-09-30 15:19:43 -07002152 audio_devices_t device = getNewInputDevice(inputDesc);
Eric Laurent271a93e2016-09-29 14:47:06 -07002153 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002154
Eric Laurent733ce942017-12-07 12:18:25 -08002155 status_t status = inputDesc->start();
2156 if (status != NO_ERROR) {
2157 mInputRoutes.decRouteActivity(session);
Eric Laurenta18dced2018-07-20 15:14:54 -07002158 inputDesc->changeRefCount(session, -1);
Eric Laurent733ce942017-12-07 12:18:25 -08002159 return status;
2160 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002161
Eric Laurent733ce942017-12-07 12:18:25 -08002162 if (inputDesc->getAudioSessionCount(true/*activeOnly*/) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002163 // if input maps to a dynamic policy with an activity listener, notify of state change
2164 if ((inputDesc->mPolicyMix != NULL)
2165 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2166 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2167 MIX_STATE_MIXING);
Eric Laurentc722f302014-12-10 11:21:49 -08002168 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002169
Eric Laurentf7c50102016-09-30 15:19:43 -07002170 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2171 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Eric Laurent05b345e2016-11-18 12:36:27 -08002172 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002173 SoundTrigger::setCaptureState(true);
2174 }
2175
2176 // automatically enable the remote submix output when input is started if not
2177 // used by a policy mix of type MIX_TYPE_RECORDERS
2178 // For remote submix (a virtual device), we open only one input per capture request.
2179 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2180 String8 address = String8("");
2181 if (inputDesc->mPolicyMix == NULL) {
2182 address = String8("0");
2183 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2184 address = inputDesc->mPolicyMix->mDeviceAddress;
2185 }
2186 if (address != "") {
2187 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2188 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2189 address, "remote-submix");
2190 }
Eric Laurentc722f302014-12-10 11:21:49 -08002191 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002192 }
Eric Laurente552edb2014-03-10 17:42:56 -07002193 }
2194
Eric Laurent599c7582015-12-07 18:05:55 -08002195 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
Eric Laurente552edb2014-03-10 17:42:56 -07002196
Eric Laurente552edb2014-03-10 17:42:56 -07002197 return NO_ERROR;
2198}
2199
Eric Laurent8fc147b2018-07-22 19:13:55 -07002200status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002201{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002202 ALOGV("%s portId %d", __FUNCTION__, portId);
2203
2204 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2205 if (inputDesc == 0) {
2206 ALOGW("stopInput() no input for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002207 return BAD_VALUE;
2208 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002209 sp<RecordClientDescriptor> client = inputDesc->clients()[portId];
2210 audio_session_t session = client->session();
2211 audio_io_handle_t input = inputDesc->mIoHandle;
2212
2213 ALOGV("stopInput() input %d", input);
Eric Laurente552edb2014-03-10 17:42:56 -07002214
Eric Laurent599c7582015-12-07 18:05:55 -08002215 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07002216
Eric Laurent599c7582015-12-07 18:05:55 -08002217 if (audioSession->activeCount() == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002218 ALOGW("stopInput() input %d already stopped", input);
2219 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002220 }
2221
Eric Laurenta18dced2018-07-20 15:14:54 -07002222 inputDesc->changeRefCount(session, -1);
Paul McLean466dc8e2015-04-17 13:15:36 -06002223
2224 // Routing?
2225 mInputRoutes.decRouteActivity(session);
2226
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002227 if (audioSession->activeCount() == 0) {
Eric Laurent733ce942017-12-07 12:18:25 -08002228 inputDesc->stop();
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002229 if (inputDesc->isActive()) {
2230 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2231 } else {
2232 // if input maps to a dynamic policy with an activity listener, notify of state change
2233 if ((inputDesc->mPolicyMix != NULL)
2234 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2235 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2236 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002237 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002238
2239 // automatically disable the remote submix output when input is stopped if not
2240 // used by a policy mix of type MIX_TYPE_RECORDERS
2241 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2242 String8 address = String8("");
2243 if (inputDesc->mPolicyMix == NULL) {
2244 address = String8("0");
2245 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2246 address = inputDesc->mPolicyMix->mDeviceAddress;
2247 }
2248 if (address != "") {
2249 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2250 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2251 address, "remote-submix");
2252 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002253 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002254
Eric Laurentf7c50102016-09-30 15:19:43 -07002255 audio_devices_t device = inputDesc->mDevice;
Eric Laurentfb66dd92016-01-28 18:32:03 -08002256 resetInputDevice(input);
Eric Laurent84332aa2016-01-28 22:19:18 +00002257
Eric Laurentf7c50102016-09-30 15:19:43 -07002258 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2259 // primary HW module
2260 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2261 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2262 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08002263 SoundTrigger::setCaptureState(false);
2264 }
2265 inputDesc->clearPreemptedSessions();
Eric Laurent84332aa2016-01-28 22:19:18 +00002266 }
Eric Laurente552edb2014-03-10 17:42:56 -07002267 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002268 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002269}
2270
Eric Laurent8fc147b2018-07-22 19:13:55 -07002271void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002272{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002273 ALOGV("%s portId %d", __FUNCTION__, portId);
2274
2275 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2276 if (inputDesc == 0) {
2277 ALOGW("releaseInput() no input for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002278 return;
2279 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002280 sp<RecordClientDescriptor> client = inputDesc->clients()[portId];
2281 audio_session_t session = client->session();
2282 audio_io_handle_t input = inputDesc->mIoHandle;
2283
2284 ALOGV("releaseInput() %d", input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002285
2286 // Routing
2287 mInputRoutes.removeRoute(session);
2288
Eric Laurent599c7582015-12-07 18:05:55 -08002289 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
vivek mehta587b8df2017-01-31 14:58:44 -08002290 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07002291 ALOGW("releaseInput() unknown session %d on input %d", session, input);
2292 return;
2293 }
Eric Laurent599c7582015-12-07 18:05:55 -08002294
2295 if (audioSession->openCount() == 0) {
2296 ALOGW("releaseInput() invalid open count %d on session %d",
2297 audioSession->openCount(), session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002298 return;
2299 }
Eric Laurent599c7582015-12-07 18:05:55 -08002300
2301 if (audioSession->changeOpenCount(-1) == 0) {
2302 inputDesc->removeAudioSession(session);
2303 }
2304
Jean-Michel Trivi65bfe912015-12-04 15:56:47 -08002305 if (inputDesc->getOpenRefCount() > 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002306 ALOGV("releaseInput() exit > 0");
2307 return;
2308 }
2309
Eric Laurent05b90f82014-08-27 15:32:29 -07002310 closeInput(input);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002311 inputDesc->clients().erase(portId);
Eric Laurentb52c1522014-05-20 11:27:36 -07002312 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002313 ALOGV("releaseInput() exit");
2314}
2315
Eric Laurent8fc147b2018-07-22 19:13:55 -07002316void AudioPolicyManager::closeSessions(const sp<AudioInputDescriptor>& input, bool activeOnly)
2317{
2318 AudioSessionCollection sessions = input->getAudioSessions(activeOnly /*activeOnly*/);
2319 for (size_t i = 0; i < sessions.size(); i++) {
2320 closeSession(input, sessions[i]);
2321 }
2322}
2323
2324void AudioPolicyManager::closeSession(const sp<AudioInputDescriptor>& input,
2325 const sp<AudioSession>& session)
2326{
2327 RecordClientVector clients = input->getClientsForSession(session->session());
2328
2329 for (const auto& client : clients) {
2330 stopInput(client->portId());
2331 releaseInput(client->portId());
2332 }
2333}
2334
2335
Eric Laurentd4692962014-05-05 18:13:44 -07002336void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002337 bool patchRemoved = false;
2338
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002339 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002340 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002341 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002342 if (patch_index >= 0) {
2343 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002344 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002345 mAudioPatches.removeItemsAt(patch_index);
2346 patchRemoved = true;
2347 }
Eric Laurentfe231122017-11-17 17:48:06 -08002348 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002349 }
jiabin829a00b2018-04-04 16:28:32 -07002350 mInputRoutes.clear();
Eric Laurentd4692962014-05-05 18:13:44 -07002351 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002352 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002353 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002354
2355 if (patchRemoved) {
2356 mpClientInterface->onAudioPatchListUpdate();
2357 }
Eric Laurentd4692962014-05-05 18:13:44 -07002358}
2359
Eric Laurente0720872014-03-11 09:30:41 -07002360void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002361 int indexMin,
2362 int indexMax)
2363{
2364 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002365 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002366
2367 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002368 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2369 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002370 continue;
2371 }
2372 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002373 }
Eric Laurente552edb2014-03-10 17:42:56 -07002374}
2375
Eric Laurente0720872014-03-11 09:30:41 -07002376status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002377 int index,
2378 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002379{
2380
Nadav Bar7c605f62017-12-25 00:01:52 +02002381 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2382 // app that has MODIFY_PHONE_STATE permission.
2383 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
2384 !(stream == AUDIO_STREAM_VOICE_CALL && index == 0)) ||
François Gaffied1ab2bd2015-12-02 18:20:06 +01002385 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002386 return BAD_VALUE;
2387 }
2388 if (!audio_is_output_device(device)) {
2389 return BAD_VALUE;
2390 }
2391
2392 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002393 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002394
Eric Laurent1fd372e2016-04-06 14:23:53 -07002395 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002396 stream, device, index);
2397
Eric Laurent28d09f02016-03-08 10:43:05 -08002398 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002399 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2400 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002401 continue;
2402 }
2403 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2404 }
Eric Laurente552edb2014-03-10 17:42:56 -07002405
Eric Laurent1fd372e2016-04-06 14:23:53 -07002406 // update volume on all outputs and streams matching the following:
2407 // - The requested stream (or a stream matching for volume control) is active on the output
2408 // - The device (or devices) selected by the strategy corresponding to this stream includes
2409 // the requested device
2410 // - For non default requested device, currently selected device on the output is either the
2411 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002412 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2413 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002414 status_t status = NO_ERROR;
2415 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002416 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2417 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08002418 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
Eric Laurent3839bc02018-07-10 18:33:34 -07002419 if (!(streamsMatchForvolume(stream, (audio_stream_type_t)curStream))) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002420 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002421 }
Eric Laurentdcd4ab12018-06-29 17:45:13 -07002422 if (!(desc->isStreamActive((audio_stream_type_t)curStream) || isInCall())) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002423 continue;
2424 }
Eric Laurent794fde22016-03-11 09:50:45 -08002425 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002426 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2427 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002428 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2429 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002430 continue;
2431 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002432 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002433 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002434 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07002435 applyVolume = (curDevice & curStreamDevice) != 0;
2436 } else {
2437 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002438 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002439 }
Eric Laurent3839bc02018-07-10 18:33:34 -07002440 // rescale index before applying to curStream as ranges may be different for
2441 // stream and curStream
2442 int idx = rescaleVolumeIndex(index, stream, (audio_stream_type_t)curStream);
Eric Laurente76f29c2016-09-14 17:17:53 -07002443 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002444 //FIXME: workaround for truncated touch sounds
2445 // delayed volume change for system stream to be removed when the problem is
2446 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002447 status_t volStatus =
Eric Laurent3839bc02018-07-10 18:33:34 -07002448 checkAndSetVolume((audio_stream_type_t)curStream, idx, desc, curDevice,
Eric Laurentdc462862016-07-19 12:29:53 -07002449 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002450 if (volStatus != NO_ERROR) {
2451 status = volStatus;
2452 }
2453 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002454 }
Eric Laurente552edb2014-03-10 17:42:56 -07002455 }
2456 return status;
2457}
2458
Eric Laurente0720872014-03-11 09:30:41 -07002459status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002460 int *index,
2461 audio_devices_t device)
2462{
2463 if (index == NULL) {
2464 return BAD_VALUE;
2465 }
2466 if (!audio_is_output_device(device)) {
2467 return BAD_VALUE;
2468 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002469 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002470 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002471 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002472 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2473 }
François Gaffiedfd74092015-03-19 12:10:59 +01002474 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002475
François Gaffied1ab2bd2015-12-02 18:20:06 +01002476 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002477 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2478 return NO_ERROR;
2479}
2480
Eric Laurent36829f92017-04-07 19:04:42 -07002481audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002482{
2483 // select one output among several suitable for global effects.
2484 // The priority is as follows:
2485 // 1: An offloaded output. If the effect ends up not being offloadable,
2486 // AudioFlinger will invalidate the track and the offloaded output
2487 // will be closed causing the effect to be moved to a PCM output.
2488 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002489 // 3: The primary output
2490 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002491
Eric Laurent3b73df72014-03-11 09:06:29 -07002492 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002493 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent36829f92017-04-07 19:04:42 -07002494 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002495
Eric Laurent36829f92017-04-07 19:04:42 -07002496 if (outputs.size() == 0) {
2497 return AUDIO_IO_HANDLE_NONE;
2498 }
Eric Laurente552edb2014-03-10 17:42:56 -07002499
Eric Laurent36829f92017-04-07 19:04:42 -07002500 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2501 bool activeOnly = true;
2502
2503 while (output == AUDIO_IO_HANDLE_NONE) {
2504 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2505 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2506 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2507
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002508 for (audio_io_handle_t output : outputs) {
2509 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002510 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2511 continue;
2512 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002513 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2514 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002515 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002516 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002517 }
2518 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002519 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002520 }
2521 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002522 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002523 }
2524 }
2525 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2526 output = outputOffloaded;
2527 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2528 output = outputDeepBuffer;
2529 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2530 output = outputPrimary;
2531 } else {
2532 output = outputs[0];
2533 }
2534 activeOnly = false;
2535 }
2536
2537 if (output != mMusicEffectOutput) {
2538 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2539 mMusicEffectOutput = output;
2540 }
2541
2542 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002543 return output;
2544}
2545
Eric Laurent36829f92017-04-07 19:04:42 -07002546audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2547{
2548 return selectOutputForMusicEffects();
2549}
2550
Eric Laurente0720872014-03-11 09:30:41 -07002551status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002552 audio_io_handle_t io,
2553 uint32_t strategy,
2554 int session,
2555 int id)
2556{
2557 ssize_t index = mOutputs.indexOfKey(io);
2558 if (index < 0) {
2559 index = mInputs.indexOfKey(io);
2560 if (index < 0) {
2561 ALOGW("registerEffect() unknown io %d", io);
2562 return INVALID_OPERATION;
2563 }
2564 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002565 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002566}
2567
Eric Laurentc75307b2015-03-17 15:29:32 -07002568bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2569{
Eric Laurent28d09f02016-03-08 10:43:05 -08002570 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002571 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2572 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002573 continue;
2574 }
2575 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2576 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002577 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002578}
2579
2580bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2581{
2582 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2583}
2584
Eric Laurente0720872014-03-11 09:30:41 -07002585bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002586{
2587 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002588 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002589 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002590 return true;
2591 }
2592 }
2593 return false;
2594}
2595
Eric Laurent275e8e92014-11-30 15:14:47 -08002596// Register a list of custom mixes with their attributes and format.
2597// When a mix is registered, corresponding input and output profiles are
2598// added to the remote submix hw module. The profile contains only the
2599// parameters (sampling rate, format...) specified by the mix.
2600// The corresponding input remote submix device is also connected.
2601//
2602// When a remote submix device is connected, the address is checked to select the
2603// appropriate profile and the corresponding input or output stream is opened.
2604//
2605// When capture starts, getInputForAttr() will:
2606// - 1 look for a mix matching the address passed in attribtutes tags if any
2607// - 2 if none found, getDeviceForInputSource() will:
2608// - 2.1 look for a mix matching the attributes source
2609// - 2.2 if none found, default to device selection by policy rules
2610// At this time, the corresponding output remote submix device is also connected
2611// and active playback use cases can be transferred to this mix if needed when reconnecting
2612// after AudioTracks are invalidated
2613//
2614// When playback starts, getOutputForAttr() will:
2615// - 1 look for a mix matching the address passed in attribtutes tags if any
2616// - 2 if none found, look for a mix matching the attributes usage
2617// - 3 if none found, default to device and output selection by policy rules.
2618
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002619status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002620{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002621 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2622 status_t res = NO_ERROR;
2623
2624 sp<HwModule> rSubmixModule;
2625 // examine each mix's route type
2626 for (size_t i = 0; i < mixes.size(); i++) {
2627 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
2628 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
2629 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002630 break;
2631 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002632 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002633 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002634 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002635 rSubmixModule = mHwModules.getModuleFromName(
2636 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2637 if (rSubmixModule == 0) {
2638 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2639 i);
2640 res = INVALID_OPERATION;
2641 break;
2642 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002643 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002644
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002645 String8 address = mixes[i].mDeviceAddress;
François Gaffie036e1e92015-03-19 10:16:24 +01002646
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002647 if (mPolicyMixes.registerMix(address, mixes[i], 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002648 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002649 res = INVALID_OPERATION;
2650 break;
2651 }
2652 audio_config_t outputConfig = mixes[i].mFormat;
2653 audio_config_t inputConfig = mixes[i].mFormat;
2654 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2655 // stereo and let audio flinger do the channel conversion if needed.
2656 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2657 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2658 rSubmixModule->addOutputProfile(address, &outputConfig,
2659 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2660 rSubmixModule->addInputProfile(address, &inputConfig,
2661 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002662
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002663 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
2664 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2665 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2666 address.string(), "remote-submix");
2667 } else {
2668 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2669 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2670 address.string(), "remote-submix");
2671 }
2672 } else if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002673 String8 address = mixes[i].mDeviceAddress;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002674 audio_devices_t device = mixes[i].mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002675 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2676 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002677
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002678 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002679 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2680 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2681 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2682 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2683 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2684 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002685 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2686 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002687 if (mPolicyMixes.registerMix(address, mixes[i], desc) != NO_ERROR) {
2688 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002689 } else {
2690 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002691 }
2692 break;
2693 }
2694 }
2695
2696 if (res != NO_ERROR) {
2697 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002698 i, device, address.string());
2699 res = INVALID_OPERATION;
2700 break;
2701 } else if (!foundOutput) {
2702 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2703 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002704 res = INVALID_OPERATION;
2705 break;
2706 }
Eric Laurentc722f302014-12-10 11:21:49 -08002707 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002708 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002709 if (res != NO_ERROR) {
2710 unregisterPolicyMixes(mixes);
2711 }
2712 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002713}
2714
2715status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2716{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002717 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002718 status_t res = NO_ERROR;
2719 sp<HwModule> rSubmixModule;
2720 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002721 for (const auto& mix : mixes) {
2722 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002723
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002724 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002725 rSubmixModule = mHwModules.getModuleFromName(
2726 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2727 if (rSubmixModule == 0) {
2728 res = INVALID_OPERATION;
2729 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002730 }
2731 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002732
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002733 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002734
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002735 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2736 res = INVALID_OPERATION;
2737 continue;
2738 }
2739
2740 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2741 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2742 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2743 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2744 address.string(), "remote-submix");
2745 }
2746 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2747 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2748 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2749 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2750 address.string(), "remote-submix");
2751 }
2752 rSubmixModule->removeOutputProfile(address);
2753 rSubmixModule->removeInputProfile(address);
2754
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002755 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2756 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002757 res = INVALID_OPERATION;
2758 continue;
2759 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002760 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002761 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002762 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002763}
2764
Eric Laurente552edb2014-03-10 17:42:56 -07002765
Eric Laurente0720872014-03-11 09:30:41 -07002766status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002767{
Eric Laurente552edb2014-03-10 17:42:56 -07002768 String8 result;
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002769 result.appendFormat("\nAudioPolicyManager Dump: %p\n", this);
2770 result.appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07002771 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002772 std::string stateLiteral;
2773 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002774 result.appendFormat(" Phone state: %s\n", stateLiteral.c_str());
2775 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
2776 "communications", "media", "record", "dock", "system",
2777 "HDMI system audio", "encoded surround output", "vibrate ringing" };
2778 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
2779 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
2780 result.appendFormat(" Force use for %s: %d\n",
2781 forceUses[i], mEngine->getForceUse(i));
2782 }
2783 result.appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
2784 result.appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
2785 result.appendFormat(" Config source: %s\n", getConfig().getSource().c_str());
François Gaffie2110e042015-03-24 08:41:51 +01002786 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002787
François Gaffie112b0af2015-11-19 16:13:25 +01002788 mAvailableOutputDevices.dump(fd, String8("Available output"));
2789 mAvailableInputDevices.dump(fd, String8("Available input"));
Mikhail Naganovd4120142017-12-06 15:49:22 -08002790 mHwModulesAll.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002791 mOutputs.dump(fd);
2792 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002793 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002794 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002795 mAudioPatches.dump(fd);
Mikhail Naganov44344b02016-12-13 11:21:02 -08002796 mPolicyMixes.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002797
2798 return NO_ERROR;
2799}
2800
2801// This function checks for the parameters which can be offloaded.
2802// This can be enhanced depending on the capability of the DSP and policy
2803// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002804bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002805{
2806 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002807 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002808 offloadInfo.sample_rate, offloadInfo.channel_mask,
2809 offloadInfo.format,
2810 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2811 offloadInfo.has_video);
2812
Andy Hung2ddee192015-12-18 17:34:44 -08002813 if (mMasterMono) {
2814 return false; // no offloading if mono is set.
2815 }
2816
Eric Laurente552edb2014-03-10 17:42:56 -07002817 // Check if offload has been disabled
2818 char propValue[PROPERTY_VALUE_MAX];
2819 if (property_get("audio.offload.disable", propValue, "0")) {
2820 if (atoi(propValue) != 0) {
2821 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2822 return false;
2823 }
2824 }
2825
2826 // Check if stream type is music, then only allow offload as of now.
2827 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2828 {
2829 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2830 return false;
2831 }
2832
2833 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002834 const bool allowOffloadWithVideo =
2835 property_get_bool("audio.offload.video", false /* default_value */);
2836 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002837 ALOGV("isOffloadSupported: has_video == true, returning false");
2838 return false;
2839 }
2840
2841 //If duration is less than minimum value defined in property, return false
2842 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2843 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2844 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2845 return false;
2846 }
2847 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2848 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2849 return false;
2850 }
2851
2852 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2853 // creating an offloaded track and tearing it down immediately after start when audioflinger
2854 // detects there is an active non offloadable effect.
2855 // FIXME: We should check the audio session here but we do not have it in this context.
2856 // This may prevent offloading in rare situations where effects are left active by apps
2857 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002858 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002859 return false;
2860 }
2861
2862 // See if there is a profile to support this.
2863 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002864 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002865 offloadInfo.sample_rate,
2866 offloadInfo.format,
2867 offloadInfo.channel_mask,
2868 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002869 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2870 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002871}
2872
Eric Laurent6a94d692014-05-20 11:18:06 -07002873status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2874 audio_port_type_t type,
2875 unsigned int *num_ports,
2876 struct audio_port *ports,
2877 unsigned int *generation)
2878{
2879 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2880 generation == NULL) {
2881 return BAD_VALUE;
2882 }
2883 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2884 if (ports == NULL) {
2885 *num_ports = 0;
2886 }
2887
2888 size_t portsWritten = 0;
2889 size_t portsMax = *num_ports;
2890 *num_ports = 0;
2891 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002892 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2893 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002894 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002895 for (const auto& dev : mAvailableOutputDevices) {
2896 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002897 continue;
2898 }
2899 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002900 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002901 }
2902 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002903 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002904 }
2905 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002906 for (const auto& dev : mAvailableInputDevices) {
2907 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002908 continue;
2909 }
2910 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002911 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002912 }
2913 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002914 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002915 }
2916 }
2917 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2918 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2919 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2920 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2921 }
2922 *num_ports += mInputs.size();
2923 }
2924 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002925 size_t numOutputs = 0;
2926 for (size_t i = 0; i < mOutputs.size(); i++) {
2927 if (!mOutputs[i]->isDuplicated()) {
2928 numOutputs++;
2929 if (portsWritten < portsMax) {
2930 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2931 }
2932 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002933 }
Eric Laurent84c70242014-06-23 08:46:27 -07002934 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002935 }
2936 }
2937 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002938 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002939 return NO_ERROR;
2940}
2941
Eric Laurent99fcae42018-05-17 16:59:18 -07002942status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07002943{
Eric Laurent99fcae42018-05-17 16:59:18 -07002944 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
2945 return BAD_VALUE;
2946 }
2947 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
2948 if (dev != 0) {
2949 dev->toAudioPort(port);
2950 return NO_ERROR;
2951 }
2952 dev = mAvailableInputDevices.getDeviceFromId(port->id);
2953 if (dev != 0) {
2954 dev->toAudioPort(port);
2955 return NO_ERROR;
2956 }
2957 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
2958 if (out != 0) {
2959 out->toAudioPort(port);
2960 return NO_ERROR;
2961 }
2962 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
2963 if (in != 0) {
2964 in->toAudioPort(port);
2965 return NO_ERROR;
2966 }
2967 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002968}
2969
Eric Laurent6a94d692014-05-20 11:18:06 -07002970status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2971 audio_patch_handle_t *handle,
2972 uid_t uid)
2973{
2974 ALOGV("createAudioPatch()");
2975
2976 if (handle == NULL || patch == NULL) {
2977 return BAD_VALUE;
2978 }
2979 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2980
Mikhail Naganovac9858b2018-06-15 13:12:37 -07002981 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07002982 return BAD_VALUE;
2983 }
2984 // only one source per audio patch supported for now
2985 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002986 return INVALID_OPERATION;
2987 }
Eric Laurent874c42872014-08-08 15:13:39 -07002988
2989 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002990 return INVALID_OPERATION;
2991 }
Eric Laurent874c42872014-08-08 15:13:39 -07002992 for (size_t i = 0; i < patch->num_sinks; i++) {
2993 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2994 return INVALID_OPERATION;
2995 }
2996 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002997
2998 sp<AudioPatch> patchDesc;
2999 ssize_t index = mAudioPatches.indexOfKey(*handle);
3000
Eric Laurent6a94d692014-05-20 11:18:06 -07003001 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
3002 patch->sources[0].role,
3003 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003004#if LOG_NDEBUG == 0
3005 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08003006 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07003007 patch->sinks[i].role,
3008 patch->sinks[i].type);
3009 }
3010#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07003011
3012 if (index >= 0) {
3013 patchDesc = mAudioPatches.valueAt(index);
3014 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3015 mUidCached, patchDesc->mUid, uid);
3016 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3017 return INVALID_OPERATION;
3018 }
3019 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07003020 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003021 }
3022
3023 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003024 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003025 if (outputDesc == NULL) {
3026 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
3027 return BAD_VALUE;
3028 }
Eric Laurent84c70242014-06-23 08:46:27 -07003029 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
3030 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003031 if (patchDesc != 0) {
3032 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
3033 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
3034 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
3035 return BAD_VALUE;
3036 }
3037 }
Eric Laurent874c42872014-08-08 15:13:39 -07003038 DeviceVector devices;
3039 for (size_t i = 0; i < patch->num_sinks; i++) {
3040 // Only support mix to devices connection
3041 // TODO add support for mix to mix connection
3042 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3043 ALOGV("createAudioPatch() source mix but sink is not a device");
3044 return INVALID_OPERATION;
3045 }
3046 sp<DeviceDescriptor> devDesc =
3047 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3048 if (devDesc == 0) {
3049 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
3050 return BAD_VALUE;
3051 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003052
François Gaffie53615e22015-03-19 09:24:12 +01003053 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08003054 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07003055 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01003056 NULL, // updatedSamplingRate
3057 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003058 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01003059 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003060 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01003061 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07003062 ALOGV("createAudioPatch() profile not supported for device %08x",
3063 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07003064 return INVALID_OPERATION;
3065 }
3066 devices.add(devDesc);
3067 }
3068 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003069 return INVALID_OPERATION;
3070 }
Eric Laurent874c42872014-08-08 15:13:39 -07003071
Eric Laurent6a94d692014-05-20 11:18:06 -07003072 // TODO: reconfigure output format and channels here
3073 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07003074 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07003075 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003076 index = mAudioPatches.indexOfKey(*handle);
3077 if (index >= 0) {
3078 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3079 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
3080 }
3081 patchDesc = mAudioPatches.valueAt(index);
3082 patchDesc->mUid = uid;
3083 ALOGV("createAudioPatch() success");
3084 } else {
3085 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
3086 return INVALID_OPERATION;
3087 }
3088 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3089 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3090 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003091 // only one sink supported when connecting an input device to a mix
3092 if (patch->num_sinks > 1) {
3093 return INVALID_OPERATION;
3094 }
François Gaffie53615e22015-03-19 09:24:12 +01003095 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003096 if (inputDesc == NULL) {
3097 return BAD_VALUE;
3098 }
3099 if (patchDesc != 0) {
3100 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3101 return BAD_VALUE;
3102 }
3103 }
3104 sp<DeviceDescriptor> devDesc =
3105 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
3106 if (devDesc == 0) {
3107 return BAD_VALUE;
3108 }
3109
François Gaffie53615e22015-03-19 09:24:12 +01003110 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08003111 devDesc->mAddress,
3112 patch->sinks[0].sample_rate,
3113 NULL, /*updatedSampleRate*/
3114 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003115 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003116 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003117 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003118 // FIXME for the parameter type,
3119 // and the NONE
3120 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003121 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003122 return INVALID_OPERATION;
3123 }
3124 // TODO: reconfigure output format and channels here
3125 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01003126 devDesc->type(), inputDesc->mIoHandle);
3127 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003128 index = mAudioPatches.indexOfKey(*handle);
3129 if (index >= 0) {
3130 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3131 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
3132 }
3133 patchDesc = mAudioPatches.valueAt(index);
3134 patchDesc->mUid = uid;
3135 ALOGV("createAudioPatch() success");
3136 } else {
3137 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
3138 return INVALID_OPERATION;
3139 }
3140 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3141 // device to device connection
3142 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003143 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003144 return BAD_VALUE;
3145 }
3146 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003147 sp<DeviceDescriptor> srcDeviceDesc =
3148 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07003149 if (srcDeviceDesc == 0) {
3150 return BAD_VALUE;
3151 }
Eric Laurent874c42872014-08-08 15:13:39 -07003152
Eric Laurent6a94d692014-05-20 11:18:06 -07003153 //update source and sink with our own data as the data passed in the patch may
3154 // be incomplete.
3155 struct audio_patch newPatch = *patch;
3156 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003157
Eric Laurent874c42872014-08-08 15:13:39 -07003158 for (size_t i = 0; i < patch->num_sinks; i++) {
3159 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3160 ALOGV("createAudioPatch() source device but one sink is not a device");
3161 return INVALID_OPERATION;
3162 }
3163
3164 sp<DeviceDescriptor> sinkDeviceDesc =
3165 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3166 if (sinkDeviceDesc == 0) {
3167 return BAD_VALUE;
3168 }
3169 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
3170
Eric Laurent3bcf8592015-04-03 12:13:24 -07003171 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003172 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003173 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08003174 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003175 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003176 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003177 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003178 return INVALID_OPERATION;
3179 }
Eric Laurent874c42872014-08-08 15:13:39 -07003180 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01003181 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003182 // if the sink device is reachable via an opened output stream, request to go via
3183 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07003184 audio_io_handle_t output = selectOutput(outputs,
3185 AUDIO_OUTPUT_FLAG_NONE,
3186 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07003187 if (output != AUDIO_IO_HANDLE_NONE) {
3188 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3189 if (outputDesc->isDuplicated()) {
3190 return INVALID_OPERATION;
3191 }
3192 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003193 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003194 newPatch.num_sources = 2;
3195 }
Eric Laurent83b88082014-06-20 18:31:16 -07003196 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003197 }
3198 // TODO: check from routing capabilities in config file and other conflicting patches
3199
Mikhail Naganovdc769682018-05-04 15:34:08 -07003200 status_t status = installPatch(__func__, index, handle, &newPatch, 0, uid, &patchDesc);
3201 if (status != NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003202 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3203 status);
3204 return INVALID_OPERATION;
3205 }
3206 } else {
3207 return BAD_VALUE;
3208 }
3209 } else {
3210 return BAD_VALUE;
3211 }
3212 return NO_ERROR;
3213}
3214
3215status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3216 uid_t uid)
3217{
3218 ALOGV("releaseAudioPatch() patch %d", handle);
3219
3220 ssize_t index = mAudioPatches.indexOfKey(handle);
3221
3222 if (index < 0) {
3223 return BAD_VALUE;
3224 }
3225 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3226 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3227 mUidCached, patchDesc->mUid, uid);
3228 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3229 return INVALID_OPERATION;
3230 }
3231
3232 struct audio_patch *patch = &patchDesc->mPatch;
3233 patchDesc->mUid = mUidCached;
3234 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003235 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003236 if (outputDesc == NULL) {
3237 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3238 return BAD_VALUE;
3239 }
3240
Eric Laurentc75307b2015-03-17 15:29:32 -07003241 setOutputDevice(outputDesc,
3242 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07003243 true,
3244 0,
3245 NULL);
3246 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3247 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003248 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003249 if (inputDesc == NULL) {
3250 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3251 return BAD_VALUE;
3252 }
3253 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003254 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003255 true,
3256 NULL);
3257 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003258 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3259 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3260 status, patchDesc->mAfPatchHandle);
3261 removeAudioPatch(patchDesc->mHandle);
3262 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003263 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003264 } else {
3265 return BAD_VALUE;
3266 }
3267 } else {
3268 return BAD_VALUE;
3269 }
3270 return NO_ERROR;
3271}
3272
3273status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3274 struct audio_patch *patches,
3275 unsigned int *generation)
3276{
François Gaffie53615e22015-03-19 09:24:12 +01003277 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003278 return BAD_VALUE;
3279 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003280 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003281 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003282}
3283
Eric Laurente1715a42014-05-20 11:30:42 -07003284status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003285{
Eric Laurente1715a42014-05-20 11:30:42 -07003286 ALOGV("setAudioPortConfig()");
3287
3288 if (config == NULL) {
3289 return BAD_VALUE;
3290 }
3291 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3292 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003293 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3294 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003295 }
3296
Eric Laurenta121f902014-06-03 13:32:54 -07003297 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003298 if (config->type == AUDIO_PORT_TYPE_MIX) {
3299 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003300 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003301 if (outputDesc == NULL) {
3302 return BAD_VALUE;
3303 }
Eric Laurent84c70242014-06-23 08:46:27 -07003304 ALOG_ASSERT(!outputDesc->isDuplicated(),
3305 "setAudioPortConfig() called on duplicated output %d",
3306 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003307 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003308 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003309 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003310 if (inputDesc == NULL) {
3311 return BAD_VALUE;
3312 }
Eric Laurenta121f902014-06-03 13:32:54 -07003313 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003314 } else {
3315 return BAD_VALUE;
3316 }
3317 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3318 sp<DeviceDescriptor> deviceDesc;
3319 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3320 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3321 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3322 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3323 } else {
3324 return BAD_VALUE;
3325 }
3326 if (deviceDesc == NULL) {
3327 return BAD_VALUE;
3328 }
Eric Laurenta121f902014-06-03 13:32:54 -07003329 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003330 } else {
3331 return BAD_VALUE;
3332 }
3333
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003334 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003335 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3336 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003337 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003338 audioPortConfig->toAudioPortConfig(&newConfig, config);
3339 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003340 }
Eric Laurenta121f902014-06-03 13:32:54 -07003341 if (status != NO_ERROR) {
3342 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003343 }
Eric Laurente1715a42014-05-20 11:30:42 -07003344
3345 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003346}
3347
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003348void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3349{
Eric Laurentd60560a2015-04-10 11:31:20 -07003350 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003351 clearAudioPatches(uid);
3352 clearSessionRoutes(uid);
3353}
3354
Eric Laurent6a94d692014-05-20 11:18:06 -07003355void AudioPolicyManager::clearAudioPatches(uid_t uid)
3356{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003357 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003358 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3359 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003360 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003361 }
3362 }
3363}
3364
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003365void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3366 audio_io_handle_t ouptutToSkip)
3367{
3368 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3369 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3370 for (size_t j = 0; j < mOutputs.size(); j++) {
3371 if (mOutputs.keyAt(j) == ouptutToSkip) {
3372 continue;
3373 }
3374 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3375 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3376 continue;
3377 }
3378 // If the default device for this strategy is on another output mix,
3379 // invalidate all tracks in this strategy to force re connection.
3380 // Otherwise select new device on the output mix.
3381 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003382 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003383 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3384 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3385 }
3386 }
3387 } else {
3388 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3389 setOutputDevice(outputDesc, newDevice, false);
3390 }
3391 }
3392}
3393
3394void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3395{
3396 // remove output routes associated with this uid
3397 SortedVector<routing_strategy> affectedStrategies;
3398 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
3399 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
3400 if (route->mUid == uid) {
3401 mOutputRoutes.removeItemsAt(i);
3402 if (route->mDeviceDescriptor != 0) {
3403 affectedStrategies.add(getStrategy(route->mStreamType));
3404 }
3405 }
3406 }
3407 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003408 for (const auto& strategy : affectedStrategies) {
3409 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003410 }
3411
3412 // remove input routes associated with this uid
3413 SortedVector<audio_source_t> affectedSources;
3414 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
3415 sp<SessionRoute> route = mInputRoutes.valueAt(i);
3416 if (route->mUid == uid) {
3417 mInputRoutes.removeItemsAt(i);
3418 if (route->mDeviceDescriptor != 0) {
3419 affectedSources.add(route->mSource);
3420 }
3421 }
3422 }
3423 // reroute inputs if necessary
3424 SortedVector<audio_io_handle_t> inputsToClose;
3425 for (size_t i = 0; i < mInputs.size(); i++) {
3426 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003427 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003428 inputsToClose.add(inputDesc->mIoHandle);
3429 }
3430 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003431 for (const auto& input : inputsToClose) {
3432 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003433 }
3434}
3435
Eric Laurentd60560a2015-04-10 11:31:20 -07003436void AudioPolicyManager::clearAudioSources(uid_t uid)
3437{
3438 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
3439 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3440 if (sourceDesc->mUid == uid) {
3441 stopAudioSource(mAudioSources.keyAt(i));
3442 }
3443 }
3444}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003445
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003446status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3447 audio_io_handle_t *ioHandle,
3448 audio_devices_t *device)
3449{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003450 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3451 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003452 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003453
François Gaffiedf372692015-03-19 10:43:27 +01003454 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003455}
3456
Eric Laurentd60560a2015-04-10 11:31:20 -07003457status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
3458 const audio_attributes_t *attributes,
Glenn Kasten559d4392016-03-29 13:42:57 -07003459 audio_patch_handle_t *handle,
Eric Laurentd60560a2015-04-10 11:31:20 -07003460 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003461{
Eric Laurentd60560a2015-04-10 11:31:20 -07003462 ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle);
3463 if (source == NULL || attributes == NULL || handle == NULL) {
3464 return BAD_VALUE;
3465 }
3466
Glenn Kasten559d4392016-03-29 13:42:57 -07003467 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003468
3469 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3470 source->type != AUDIO_PORT_TYPE_DEVICE) {
3471 ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type);
3472 return INVALID_OPERATION;
3473 }
3474
3475 sp<DeviceDescriptor> srcDeviceDesc =
3476 mAvailableInputDevices.getDevice(source->ext.device.type,
3477 String8(source->ext.device.address));
3478 if (srcDeviceDesc == 0) {
3479 ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
3480 return BAD_VALUE;
3481 }
3482 sp<AudioSourceDescriptor> sourceDesc =
3483 new AudioSourceDescriptor(srcDeviceDesc, attributes, uid);
3484
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003485 struct audio_patch dummyPatch = {};
Eric Laurentd60560a2015-04-10 11:31:20 -07003486 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
3487 sourceDesc->mPatchDesc = patchDesc;
3488
3489 status_t status = connectAudioSource(sourceDesc);
3490 if (status == NO_ERROR) {
3491 mAudioSources.add(sourceDesc->getHandle(), sourceDesc);
3492 *handle = sourceDesc->getHandle();
3493 }
3494 return status;
3495}
3496
3497status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3498{
3499 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3500
3501 // make sure we only have one patch per source.
3502 disconnectAudioSource(sourceDesc);
3503
3504 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
Eric Laurent28d09f02016-03-08 10:43:05 -08003505 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003506 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice;
3507
3508 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3509 sp<DeviceDescriptor> sinkDeviceDesc =
3510 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3511
3512 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003513
3514 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3515 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003516 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003517 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3518 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3519 // create patch between src device and output device
3520 // create Hwoutput and add to mHwOutputs
3521 } else {
3522 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3523 audio_io_handle_t output =
3524 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3525 if (output == AUDIO_IO_HANDLE_NONE) {
3526 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3527 return INVALID_OPERATION;
3528 }
3529 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3530 if (outputDesc->isDuplicated()) {
3531 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3532 return INVALID_OPERATION;
3533 }
Eric Laurent733ce942017-12-07 12:18:25 -08003534 status_t status = outputDesc->start();
3535 if (status != NO_ERROR) {
3536 return status;
3537 }
3538
Eric Laurentd60560a2015-04-10 11:31:20 -07003539 // create a special patch with no sink and two sources:
3540 // - the second source indicates to PatchPanel through which output mix this patch should
3541 // be connected as well as the stream type for volume control
3542 // - the sink is defined by whatever output device is currently selected for the output
3543 // though which this patch is routed.
Mikhail Naganovdc769682018-05-04 15:34:08 -07003544 PatchBuilder patchBuilder;
3545 patchBuilder.addSource(srcDeviceDesc).addSource(outputDesc, { .stream = stream });
3546 status = mpClientInterface->createAudioPatch(patchBuilder.patch(),
Eric Laurentd60560a2015-04-10 11:31:20 -07003547 &afPatchHandle,
3548 0);
3549 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3550 status, afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07003551 sourceDesc->mPatchDesc->mPatch = *patchBuilder.patch();
Eric Laurentd60560a2015-04-10 11:31:20 -07003552 if (status != NO_ERROR) {
3553 ALOGW("%s patch panel could not connect device patch, error %d",
3554 __FUNCTION__, status);
3555 return INVALID_OPERATION;
3556 }
3557 uint32_t delayMs = 0;
Eric Laurentc40d9692016-04-13 19:14:13 -07003558 status = startSource(outputDesc, stream, sinkDevice, NULL, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003559
3560 if (status != NO_ERROR) {
3561 mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0);
3562 return status;
3563 }
3564 sourceDesc->mSwOutput = outputDesc;
3565 if (delayMs != 0) {
3566 usleep(delayMs * 1000);
3567 }
3568 }
3569
3570 sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle;
3571 addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc);
3572
3573 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003574}
3575
Mikhail Naganov9de8bd12018-07-23 16:41:31 -07003576status_t AudioPolicyManager::stopAudioSource(audio_patch_handle_t handle)
Eric Laurent554a2772015-04-10 11:29:24 -07003577{
Eric Laurentd60560a2015-04-10 11:31:20 -07003578 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle);
3579 ALOGV("%s handle %d", __FUNCTION__, handle);
3580 if (sourceDesc == 0) {
3581 ALOGW("%s unknown source for handle %d", __FUNCTION__, handle);
3582 return BAD_VALUE;
3583 }
3584 status_t status = disconnectAudioSource(sourceDesc);
3585
3586 mAudioSources.removeItem(handle);
3587 return status;
3588}
3589
Andy Hung2ddee192015-12-18 17:34:44 -08003590status_t AudioPolicyManager::setMasterMono(bool mono)
3591{
3592 if (mMasterMono == mono) {
3593 return NO_ERROR;
3594 }
3595 mMasterMono = mono;
3596 // if enabling mono we close all offloaded devices, which will invalidate the
3597 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3598 // for recreating the new AudioTrack as non-offloaded PCM.
3599 //
3600 // If disabling mono, we leave all tracks as is: we don't know which clients
3601 // and tracks are able to be recreated as offloaded. The next "song" should
3602 // play back offloaded.
3603 if (mMasterMono) {
3604 Vector<audio_io_handle_t> offloaded;
3605 for (size_t i = 0; i < mOutputs.size(); ++i) {
3606 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3607 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3608 offloaded.push(desc->mIoHandle);
3609 }
3610 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003611 for (const auto& handle : offloaded) {
3612 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003613 }
3614 }
3615 // update master mono for all remaining outputs
3616 for (size_t i = 0; i < mOutputs.size(); ++i) {
3617 updateMono(mOutputs.keyAt(i));
3618 }
3619 return NO_ERROR;
3620}
3621
3622status_t AudioPolicyManager::getMasterMono(bool *mono)
3623{
3624 *mono = mMasterMono;
3625 return NO_ERROR;
3626}
3627
Eric Laurentac9cef52017-06-09 15:46:26 -07003628float AudioPolicyManager::getStreamVolumeDB(
3629 audio_stream_type_t stream, int index, audio_devices_t device)
3630{
3631 return computeVolume(stream, index, device);
3632}
3633
jiabin81772902018-04-02 17:52:27 -07003634status_t AudioPolicyManager::getSupportedFormats(audio_io_handle_t ioHandle,
3635 FormatVector& formats) {
3636 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
3637 return BAD_VALUE;
3638 }
3639 String8 reply;
3640 reply = mpClientInterface->getParameters(
3641 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
3642 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
3643 AudioParameter repliedParameters(reply);
3644 if (repliedParameters.get(
3645 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
3646 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
3647 return BAD_VALUE;
3648 }
3649 for (auto format : formatsFromString(reply.string())) {
3650 // Only AUDIO_FORMAT_AAC_LC will be used in Settings UI for all AAC formats.
3651 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3652 if (format == AAC_FORMATS[i]) {
3653 format = AUDIO_FORMAT_AAC_LC;
3654 break;
3655 }
3656 }
3657 bool exist = false;
3658 for (size_t i = 0; i < formats.size(); i++) {
3659 if (format == formats[i]) {
3660 exist = true;
3661 break;
3662 }
3663 }
3664 bool isSurroundFormat = false;
3665 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3666 if (SURROUND_FORMATS[i] == format) {
3667 isSurroundFormat = true;
3668 break;
3669 }
3670 }
3671 if (!exist && isSurroundFormat) {
3672 formats.add(format);
3673 }
3674 }
3675 return NO_ERROR;
3676}
3677
3678status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3679 audio_format_t *surroundFormats,
3680 bool *surroundFormatsEnabled,
3681 bool reported)
3682{
3683 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3684 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3685 return BAD_VALUE;
3686 }
3687 ALOGV("getSurroundFormats() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
3688 *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
3689
3690 // Only return value if there is HDMI output.
3691 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3692 return INVALID_OPERATION;
3693 }
3694
3695 size_t formatsWritten = 0;
3696 size_t formatsMax = *numSurroundFormats;
3697 *numSurroundFormats = 0;
3698 FormatVector formats;
3699 if (reported) {
3700 // Only get surround formats which are reported by device.
3701 // First list already open outputs that can be routed to this device
3702 audio_devices_t device = AUDIO_DEVICE_OUT_HDMI;
3703 SortedVector<audio_io_handle_t> outputs;
3704 bool reportedFormatFound = false;
3705 status_t status;
3706 sp<SwAudioOutputDescriptor> desc;
3707 for (size_t i = 0; i < mOutputs.size(); i++) {
3708 desc = mOutputs.valueAt(i);
3709 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
3710 outputs.add(mOutputs.keyAt(i));
3711 }
3712 }
3713 // Open an output to query dynamic parameters.
Mikhail Naganov708e0382018-05-30 09:53:04 -07003714 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003715 AUDIO_DEVICE_OUT_HDMI);
3716 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3717 String8 address = hdmiOutputDevices[i]->mAddress;
3718 for (const auto& hwModule : mHwModules) {
3719 for (size_t i = 0; i < hwModule->getOutputProfiles().size(); i++) {
3720 sp<IOProfile> profile = hwModule->getOutputProfiles()[i];
3721 if (profile->supportDevice(AUDIO_DEVICE_OUT_HDMI) &&
3722 profile->supportDeviceAddress(address)) {
3723 size_t j;
3724 for (j = 0; j < outputs.size(); j++) {
3725 desc = mOutputs.valueFor(outputs.itemAt(j));
3726 if (!desc->isDuplicated() && desc->mProfile == profile) {
3727 break;
3728 }
3729 }
3730 if (j != outputs.size()) {
3731 status = getSupportedFormats(outputs.itemAt(j), formats);
3732 reportedFormatFound |= (status == NO_ERROR);
3733 continue;
3734 }
3735
3736 if (!profile->canOpenNewIo()) {
3737 ALOGW("Max Output number %u already opened for this profile %s",
3738 profile->maxOpenCount, profile->getTagName().c_str());
3739 continue;
3740 }
3741
3742 ALOGV("opening output for device %08x with params %s profile %p name %s",
3743 device, address.string(), profile.get(), profile->getName().string());
3744 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
3745 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3746 status_t status = desc->open(nullptr, device, address,
3747 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE,
3748 &output);
3749
3750 if (status == NO_ERROR) {
3751 status = getSupportedFormats(output, formats);
3752 reportedFormatFound |= (status == NO_ERROR);
3753 desc->close();
3754 output = AUDIO_IO_HANDLE_NONE;
3755 }
3756 }
3757 }
3758 }
3759 }
3760
3761 if (!reportedFormatFound) {
3762 return UNKNOWN_ERROR;
3763 }
3764 } else {
3765 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3766 formats.add(SURROUND_FORMATS[i]);
3767 }
3768 }
3769 for (size_t i = 0; i < formats.size(); i++) {
3770 if (formatsWritten < formatsMax) {
3771 surroundFormats[formatsWritten] = formats[i];
3772 bool formatEnabled = false;
3773 if (formats[i] == AUDIO_FORMAT_AAC_LC) {
3774 for (size_t j = 0; j < ARRAY_SIZE(AAC_FORMATS); j++) {
3775 formatEnabled =
3776 mSurroundFormats.find(AAC_FORMATS[i]) != mSurroundFormats.end();
3777 break;
3778 }
3779 } else {
3780 formatEnabled = mSurroundFormats.find(formats[i]) != mSurroundFormats.end();
3781 }
3782 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3783 }
3784 (*numSurroundFormats)++;
3785 }
3786 return NO_ERROR;
3787}
3788
3789status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3790{
3791 // Check if audio format is a surround formats.
3792 bool isSurroundFormat = false;
3793 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3794 if (audioFormat == SURROUND_FORMATS[i]) {
3795 isSurroundFormat = true;
3796 break;
3797 }
3798 }
3799 if (!isSurroundFormat) {
3800 return BAD_VALUE;
3801 }
3802
3803 // Should only be called when MANUAL.
3804 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3805 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
3806 if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3807 return INVALID_OPERATION;
3808 }
3809
3810 if ((mSurroundFormats.find(audioFormat) != mSurroundFormats.end() && enabled)
3811 || (mSurroundFormats.find(audioFormat) == mSurroundFormats.end() && !enabled)) {
3812 return NO_ERROR;
3813 }
3814
3815 // The operation is valid only when there is HDMI output available.
3816 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3817 return INVALID_OPERATION;
3818 }
3819
3820 if (enabled) {
3821 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3822 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3823 mSurroundFormats.insert(AAC_FORMATS[i]);
3824 }
3825 } else {
3826 mSurroundFormats.insert(audioFormat);
3827 }
3828 } else {
3829 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3830 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3831 mSurroundFormats.erase(AAC_FORMATS[i]);
3832 }
3833 } else {
3834 mSurroundFormats.erase(audioFormat);
3835 }
3836 }
3837
3838 sp<SwAudioOutputDescriptor> outputDesc;
3839 bool profileUpdated = false;
Mikhail Naganov708e0382018-05-30 09:53:04 -07003840 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003841 AUDIO_DEVICE_OUT_HDMI);
3842 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3843 // Simulate reconnection to update enabled surround sound formats.
3844 String8 address = hdmiOutputDevices[i]->mAddress;
3845 String8 name = hdmiOutputDevices[i]->getName();
3846 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3847 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3848 address.c_str(),
3849 name.c_str());
3850 if (status != NO_ERROR) {
3851 continue;
3852 }
3853 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3854 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3855 address.c_str(),
3856 name.c_str());
3857 profileUpdated |= (status == NO_ERROR);
3858 }
Mikhail Naganov708e0382018-05-30 09:53:04 -07003859 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003860 AUDIO_DEVICE_IN_HDMI);
3861 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3862 // Simulate reconnection to update enabled surround sound formats.
3863 String8 address = hdmiInputDevices[i]->mAddress;
3864 String8 name = hdmiInputDevices[i]->getName();
3865 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3866 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3867 address.c_str(),
3868 name.c_str());
3869 if (status != NO_ERROR) {
3870 continue;
3871 }
3872 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3873 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3874 address.c_str(),
3875 name.c_str());
3876 profileUpdated |= (status == NO_ERROR);
3877 }
3878
3879 // Undo the surround formats change due to no audio profiles updated.
3880 if (!profileUpdated) {
3881 if (enabled) {
3882 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3883 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3884 mSurroundFormats.erase(AAC_FORMATS[i]);
3885 }
3886 } else {
3887 mSurroundFormats.erase(audioFormat);
3888 }
3889 } else {
3890 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3891 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3892 mSurroundFormats.insert(AAC_FORMATS[i]);
3893 }
3894 } else {
3895 mSurroundFormats.insert(audioFormat);
3896 }
3897 }
3898 }
3899
3900 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3901}
3902
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003903void AudioPolicyManager::setRecordSilenced(uid_t uid, bool silenced)
3904{
3905 ALOGV("AudioPolicyManager:setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
3906
3907 Vector<sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
3908 for (size_t i = 0; i < activeInputs.size(); i++) {
3909 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
3910 AudioSessionCollection activeSessions = activeDesc->getAudioSessions(true);
3911 for (size_t j = 0; j < activeSessions.size(); j++) {
3912 sp<AudioSession> activeSession = activeSessions.valueAt(j);
3913 if (activeSession->uid() == uid) {
3914 activeSession->setSilenced(silenced);
3915 }
3916 }
3917 }
3918}
3919
Eric Laurentd60560a2015-04-10 11:31:20 -07003920status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3921{
3922 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3923
3924 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle);
3925 if (patchDesc == 0) {
3926 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
3927 sourceDesc->mPatchDesc->mHandle);
3928 return BAD_VALUE;
3929 }
3930 removeAudioPatch(sourceDesc->mPatchDesc->mHandle);
3931
Eric Laurent28d09f02016-03-08 10:43:05 -08003932 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003933 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote();
3934 if (swOutputDesc != 0) {
Eric Laurent733ce942017-12-07 12:18:25 -08003935 status_t status = stopSource(swOutputDesc, stream, false);
3936 if (status == NO_ERROR) {
3937 swOutputDesc->stop();
3938 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003939 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3940 } else {
3941 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote();
3942 if (hwOutputDesc != 0) {
3943 // release patch between src device and output device
3944 // close Hwoutput and remove from mHwOutputs
3945 } else {
3946 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3947 }
3948 }
3949 return NO_ERROR;
3950}
3951
3952sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
3953 audio_io_handle_t output, routing_strategy strategy)
3954{
3955 sp<AudioSourceDescriptor> source;
3956 for (size_t i = 0; i < mAudioSources.size(); i++) {
3957 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3958 routing_strategy sourceStrategy =
3959 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
3960 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote();
3961 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3962 source = sourceDesc;
3963 break;
3964 }
3965 }
3966 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003967}
3968
Eric Laurente552edb2014-03-10 17:42:56 -07003969// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003970// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003971// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003972uint32_t AudioPolicyManager::nextAudioPortGeneration()
3973{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003974 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003975}
3976
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003977#ifdef USE_XML_AUDIO_POLICY_CONF
3978// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3979static const char *kConfigLocationList[] =
3980 {"/odm/etc", "/vendor/etc", "/system/etc"};
3981static const int kConfigLocationListSize =
3982 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3983
3984static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3985 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07003986 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003987 status_t ret;
3988
Petri Gyntherf497f292018-04-17 18:46:10 -07003989 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
3990 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
3991 // A2DP offload supported but disabled: try to use special XML file
3992 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
3993 }
3994 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3995
3996 for (const char* fileName : fileNames) {
3997 for (int i = 0; i < kConfigLocationListSize; i++) {
3998 PolicySerializer serializer;
3999 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
4000 "%s/%s", kConfigLocationList[i], fileName);
4001 ret = serializer.deserialize(audioPolicyXmlConfigFile, config);
4002 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004003 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07004004 return ret;
4005 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004006 }
4007 }
4008 return ret;
4009}
4010#endif
4011
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004012AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
4013 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07004014 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07004015 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004016 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07004017 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07004018 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004019#ifdef USE_XML_AUDIO_POLICY_CONF
4020 mVolumeCurves(new VolumeCurvesCollection()),
4021 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08004022 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004023#else
4024 mVolumeCurves(new StreamDescriptorCollection()),
4025 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
4026 mDefaultOutputDevice),
4027#endif
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004028 mAudioPortGeneration(1),
4029 mBeaconMuteRefCount(0),
4030 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07004031 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08004032 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07004033 mMasterMono(false),
Chris Thornton2b864642017-06-27 21:26:07 -07004034 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE),
4035 mHasComputedSoundTriggerSupportsConcurrentCapture(false)
Eric Laurente552edb2014-03-10 17:42:56 -07004036{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004037}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004038
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004039AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
4040 : AudioPolicyManager(clientInterface, false /*forTesting*/)
4041{
4042 loadConfig();
4043 initialize();
4044}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004045
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004046void AudioPolicyManager::loadConfig() {
François Gaffied1ab2bd2015-12-02 18:20:06 +01004047#ifdef USE_XML_AUDIO_POLICY_CONF
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004048 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01004049#else
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004050 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, getConfig()) != NO_ERROR)
4051 && (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, getConfig()) != NO_ERROR)) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01004052#endif
4053 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004054 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01004055 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004056}
4057
4058status_t AudioPolicyManager::initialize() {
4059 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01004060
4061 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01004062 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
4063 if (!engineInstance) {
4064 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004065 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01004066 }
4067 // Retrieve the Policy Manager Interface
4068 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
4069 if (mEngine == NULL) {
4070 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004071 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01004072 }
4073 mEngine->setObserver(this);
4074 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004075 if (status != NO_ERROR) {
4076 LOG_FATAL("Policy engine not initialized(err=%d)", status);
4077 return status;
4078 }
François Gaffie2110e042015-03-24 08:41:51 +01004079
Eric Laurent3a4311c2014-03-17 12:00:47 -07004080 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07004081 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07004082 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
4083 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Mikhail Naganovd4120142017-12-06 15:49:22 -08004084 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004085 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08004086 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
4087 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07004088 continue;
4089 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08004090 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07004091 // open all output streams needed to access attached devices
4092 // except for direct output streams that are only opened when they are actually
4093 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07004094 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004095 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004096 if (!outProfile->canOpenNewIo()) {
4097 ALOGE("Invalid Output profile max open count %u for profile %s",
4098 outProfile->maxOpenCount, outProfile->getTagName().c_str());
4099 continue;
4100 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004101 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004102 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004103 continue;
4104 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004105 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004106 mTtsOutputAvailable = true;
4107 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004108
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004109 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07004110 continue;
4111 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004112 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01004113 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
4114 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07004115 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004116 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07004117 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004118 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07004119 }
Eric Laurentd78f1532014-09-16 16:38:20 -07004120 if ((profileType & outputDeviceTypes) == 0) {
4121 continue;
4122 }
Eric Laurentc75307b2015-03-17 15:29:32 -07004123 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
4124 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07004125 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov708e0382018-05-30 09:53:04 -07004126 const DeviceVector &devicesForType = supportedDevices.getDevicesFromTypeMask(
4127 profileType);
Eric Laurentc40d9692016-04-13 19:14:13 -07004128 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
4129 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07004130 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004131 status_t status = outputDesc->open(nullptr, profileType, address,
4132 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07004133
4134 if (status != NO_ERROR) {
4135 ALOGW("Cannot open output stream for device %08x on hw module %s",
4136 outputDesc->mDevice,
Mikhail Naganovd4120142017-12-06 15:49:22 -08004137 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07004138 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004139 for (const auto& dev : supportedDevices) {
4140 ssize_t index = mAvailableOutputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07004141 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08004142 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004143 mAvailableOutputDevices[index]->attach(hwModule);
Eric Laurentd78f1532014-09-16 16:38:20 -07004144 }
4145 }
4146 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004147 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004148 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07004149 }
4150 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07004151 setOutputDevice(outputDesc,
Eric Laurentfe231122017-11-17 17:48:06 -08004152 profileType,
Eric Laurentc40d9692016-04-13 19:14:13 -07004153 true,
4154 0,
4155 NULL,
Eric Laurentfe231122017-11-17 17:48:06 -08004156 address);
Eric Laurentd78f1532014-09-16 16:38:20 -07004157 }
Eric Laurente552edb2014-03-10 17:42:56 -07004158 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004159 // open input streams needed to access attached devices to validate
4160 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004161 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004162 if (!inProfile->canOpenNewIo()) {
4163 ALOGE("Invalid Input profile max open count %u for profile %s",
4164 inProfile->maxOpenCount, inProfile->getTagName().c_str());
4165 continue;
4166 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004167 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004168 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004169 continue;
4170 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004171 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07004172 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004173 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
4174
Eric Laurentd78f1532014-09-16 16:38:20 -07004175 if ((profileType & inputDeviceTypes) == 0) {
4176 continue;
4177 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08004178 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08004179 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004180
Mikhail Naganov708e0382018-05-30 09:53:04 -07004181 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(profileType);
Eric Laurent53b810e2017-12-10 17:25:10 -08004182 // the inputs vector must be of size >= 1, but we don't want to crash here
4183 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
4184 : String8("");
4185 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
4186 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
4187
Eric Laurentd78f1532014-09-16 16:38:20 -07004188 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004189 status_t status = inputDesc->open(nullptr,
4190 profileType,
Eric Laurent53b810e2017-12-10 17:25:10 -08004191 address,
Eric Laurentfe231122017-11-17 17:48:06 -08004192 AUDIO_SOURCE_MIC,
4193 AUDIO_INPUT_FLAG_NONE,
4194 &input);
Eric Laurentd78f1532014-09-16 16:38:20 -07004195
4196 if (status == NO_ERROR) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004197 for (const auto& dev : inProfile->getSupportedDevices()) {
4198 ssize_t index = mAvailableInputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07004199 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07004200 if (index >= 0) {
4201 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
4202 if (!devDesc->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004203 devDesc->attach(hwModule);
Eric Laurent83efe1c2017-07-09 16:51:08 -07004204 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07004205 }
Eric Laurentd78f1532014-09-16 16:38:20 -07004206 }
4207 }
Eric Laurentfe231122017-11-17 17:48:06 -08004208 inputDesc->close();
Eric Laurentd78f1532014-09-16 16:38:20 -07004209 } else {
4210 ALOGW("Cannot open input stream for device %08x on hw module %s",
Eric Laurentfe231122017-11-17 17:48:06 -08004211 profileType,
Mikhail Naganovd4120142017-12-06 15:49:22 -08004212 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07004213 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004214 }
4215 }
4216 // make sure all attached devices have been allocated a unique ID
4217 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004218 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004219 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004220 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
4221 continue;
4222 }
François Gaffie2110e042015-03-24 08:41:51 +01004223 // The device is now validated and can be appended to the available devices of the engine
4224 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
4225 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004226 i++;
4227 }
4228 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004229 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01004230 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004231 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
4232 continue;
4233 }
François Gaffie2110e042015-03-24 08:41:51 +01004234 // The device is now validated and can be appended to the available devices of the engine
4235 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
4236 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004237 i++;
4238 }
4239 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004240 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01004241 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004242 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004243 }
jiabin9ff780e2018-03-19 18:19:52 -07004244 // If microphones address is empty, set it according to device type
4245 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
4246 if (mAvailableInputDevices[i]->mAddress.isEmpty()) {
4247 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
4248 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
4249 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
4250 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BACK_MICROPHONE_ADDRESS);
4251 }
4252 }
4253 }
Eric Laurente552edb2014-03-10 17:42:56 -07004254
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004255 if (mPrimaryOutput == 0) {
4256 ALOGE("Failed to open primary output");
4257 status = NO_INIT;
4258 }
Eric Laurente552edb2014-03-10 17:42:56 -07004259
4260 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004261 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004262}
4263
Eric Laurente0720872014-03-11 09:30:41 -07004264AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004265{
Eric Laurente552edb2014-03-10 17:42:56 -07004266 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004267 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004268 }
4269 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004270 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004271 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004272 mAvailableOutputDevices.clear();
4273 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004274 mOutputs.clear();
4275 mInputs.clear();
4276 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004277 mHwModulesAll.clear();
jiabin81772902018-04-02 17:52:27 -07004278 mSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004279}
4280
Eric Laurente0720872014-03-11 09:30:41 -07004281status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004282{
Eric Laurent87ffa392015-05-22 10:32:38 -07004283 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004284}
4285
Eric Laurente552edb2014-03-10 17:42:56 -07004286// ---
4287
Eric Laurent98e38192018-02-15 18:31:53 -08004288void AudioPolicyManager::addOutput(audio_io_handle_t output,
4289 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004290{
Eric Laurent1c333e22014-05-20 10:48:17 -07004291 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08004292 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004293 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004294 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004295 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004296}
4297
François Gaffie53615e22015-03-19 09:24:12 +01004298void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4299{
4300 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004301 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004302}
4303
Eric Laurent98e38192018-02-15 18:31:53 -08004304void AudioPolicyManager::addInput(audio_io_handle_t input,
4305 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004306{
Eric Laurent1c333e22014-05-20 10:48:17 -07004307 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004308 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004309}
Eric Laurente552edb2014-03-10 17:42:56 -07004310
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004311void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08004312 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004313 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004314 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08004315 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004316 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08004317 if (devDesc != 0) {
4318 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
4319 desc->mIoHandle, address.string());
4320 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004321 }
4322}
4323
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004324status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004325 audio_policy_dev_state_t state,
4326 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004327 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07004328{
François Gaffie53615e22015-03-19 09:24:12 +01004329 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07004330 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004331
4332 if (audio_device_is_digital(device)) {
4333 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004334 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004335 }
Eric Laurente552edb2014-03-10 17:42:56 -07004336
Eric Laurent3b73df72014-03-11 09:06:29 -07004337 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004338 // first list already open outputs that can be routed to this device
4339 for (size_t i = 0; i < mOutputs.size(); i++) {
4340 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07004341 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004342 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004343 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
4344 outputs.add(mOutputs.keyAt(i));
4345 } else {
4346 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08004347 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004348 }
Eric Laurente552edb2014-03-10 17:42:56 -07004349 }
4350 }
4351 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004352 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004353 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004354 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4355 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004356 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004357 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004358 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004359 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004360 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4361 j, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004362 }
Eric Laurente552edb2014-03-10 17:42:56 -07004363 }
4364 }
4365 }
4366
Eric Laurent7b279bb2015-12-14 10:18:23 -08004367 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004368
Eric Laurente552edb2014-03-10 17:42:56 -07004369 if (profiles.isEmpty() && outputs.isEmpty()) {
4370 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4371 return BAD_VALUE;
4372 }
4373
4374 // open outputs for matching profiles if needed. Direct outputs are also opened to
4375 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4376 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004377 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004378
4379 // nothing to do if one output is already opened for this profile
4380 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004381 for (j = 0; j < outputs.size(); j++) {
4382 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004383 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004384 // matching profile: save the sample rates, format and channel masks supported
4385 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07004386 if (audio_device_is_digital(device)) {
4387 devDesc->importAudioPort(profile);
4388 }
Eric Laurente552edb2014-03-10 17:42:56 -07004389 break;
4390 }
4391 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004392 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004393 continue;
4394 }
4395
Eric Laurent3974e3b2017-12-07 17:58:43 -08004396 if (!profile->canOpenNewIo()) {
4397 ALOGW("Max Output number %u already opened for this profile %s",
4398 profile->maxOpenCount, profile->getTagName().c_str());
4399 continue;
4400 }
4401
Eric Laurent83efe1c2017-07-09 16:51:08 -07004402 ALOGV("opening output for device %08x with params %s profile %p name %s",
4403 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004404 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004405 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004406 status_t status = desc->open(nullptr, device, address,
4407 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004408
Eric Laurentfe231122017-11-17 17:48:06 -08004409 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004410 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004411 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004412 char *param = audio_device_address_to_parameter(device, address);
4413 mpClientInterface->setParameters(output, String8(param));
4414 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004415 }
Phil Burk00eeb322016-03-31 12:41:00 -07004416 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004417 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004418 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004419 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004420 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004421 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004422 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004423 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004424 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4425 profile->pickAudioProfile(
4426 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004427 config.offload_info.sample_rate = config.sample_rate;
4428 config.offload_info.channel_mask = config.channel_mask;
4429 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004430
4431 status_t status = desc->open(&config, device, address, AUDIO_STREAM_DEFAULT,
4432 AUDIO_OUTPUT_FLAG_NONE, &output);
4433 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004434 output = AUDIO_IO_HANDLE_NONE;
4435 }
Eric Laurentd4692962014-05-05 18:13:44 -07004436 }
4437
Eric Laurentcf2c0212014-07-25 16:20:43 -07004438 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004439 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01004440 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004441 sp<AudioPolicyMix> policyMix;
4442 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004443 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
4444 address.string());
4445 }
François Gaffie036e1e92015-03-19 10:16:24 +01004446 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07004447 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01004448
Eric Laurent87ffa392015-05-22 10:32:38 -07004449 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4450 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004451 // no duplicated output for direct outputs and
4452 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004453 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004454
Eric Laurentd4692962014-05-05 18:13:44 -07004455 //TODO: configure audio effect output stage here
4456
4457 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004458 sp<SwAudioOutputDescriptor> dupOutputDesc =
4459 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4460 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4461 &duplicatedOutput);
4462 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004463 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004464 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004465 } else {
4466 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004467 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004468 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004469 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004470 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004471 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004472 }
Eric Laurente552edb2014-03-10 17:42:56 -07004473 }
4474 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004475 } else {
4476 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004477 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004478 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004479 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004480 profiles.removeAt(profile_index);
4481 profile_index--;
4482 } else {
4483 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004484 // Load digital format info only for digital devices
4485 if (audio_device_is_digital(device)) {
4486 devDesc->importAudioPort(profile);
4487 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004488
François Gaffie53615e22015-03-19 09:24:12 +01004489 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004490 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4491 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004492 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004493 NULL/*patch handle*/, address.string());
4494 }
Eric Laurente552edb2014-03-10 17:42:56 -07004495 ALOGV("checkOutputsForDevice(): adding output %d", output);
4496 }
4497 }
4498
4499 if (profiles.isEmpty()) {
4500 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4501 return BAD_VALUE;
4502 }
Eric Laurentd4692962014-05-05 18:13:44 -07004503 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004504 // check if one opened output is not needed any more after disconnecting one device
4505 for (size_t i = 0; i < mOutputs.size(); i++) {
4506 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004507 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004508 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004509 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004510 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004511 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004512 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004513 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4514 mOutputs.keyAt(i));
4515 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004516 }
Eric Laurente552edb2014-03-10 17:42:56 -07004517 }
4518 }
Eric Laurentd4692962014-05-05 18:13:44 -07004519 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004520 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004521 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4522 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004523 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004524 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004525 "clearing direct output profile %zu on module %s",
4526 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004527 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004528 }
4529 }
4530 }
4531 }
4532 return NO_ERROR;
4533}
4534
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004535status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004536 audio_policy_dev_state_t state,
4537 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004538 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004539{
Paul McLean9080a4c2015-06-18 08:24:02 -07004540 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004541 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004542
4543 if (audio_device_is_digital(device)) {
4544 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004545 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004546 }
4547
Eric Laurentd4692962014-05-05 18:13:44 -07004548 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4549 // first list already open inputs that can be routed to this device
4550 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4551 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004552 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004553 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4554 inputs.add(mInputs.keyAt(input_index));
4555 }
4556 }
4557
4558 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004559 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004560 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004561 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004562 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004563 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004564 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004565
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004566 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004567 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004568 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004569 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004570 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4571 profile_index, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004572 }
Eric Laurentd4692962014-05-05 18:13:44 -07004573 }
4574 }
4575 }
4576
4577 if (profiles.isEmpty() && inputs.isEmpty()) {
4578 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4579 return BAD_VALUE;
4580 }
4581
4582 // open inputs for matching profiles if needed. Direct inputs are also opened to
4583 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4584 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4585
Eric Laurent1c333e22014-05-20 10:48:17 -07004586 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004587
Eric Laurentd4692962014-05-05 18:13:44 -07004588 // nothing to do if one input is already opened for this profile
4589 size_t input_index;
4590 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4591 desc = mInputs.valueAt(input_index);
4592 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004593 if (audio_device_is_digital(device)) {
4594 devDesc->importAudioPort(profile);
4595 }
Eric Laurentd4692962014-05-05 18:13:44 -07004596 break;
4597 }
4598 }
4599 if (input_index != mInputs.size()) {
4600 continue;
4601 }
4602
Eric Laurent3974e3b2017-12-07 17:58:43 -08004603 if (!profile->canOpenNewIo()) {
4604 ALOGW("Max Input number %u already opened for this profile %s",
4605 profile->maxOpenCount, profile->getTagName().c_str());
4606 continue;
4607 }
4608
Eric Laurentfe231122017-11-17 17:48:06 -08004609 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004610 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004611 status_t status = desc->open(nullptr,
4612 device,
4613 address,
4614 AUDIO_SOURCE_MIC,
4615 AUDIO_INPUT_FLAG_NONE,
4616 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004617
Eric Laurentcf2c0212014-07-25 16:20:43 -07004618 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004619 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004620 char *param = audio_device_address_to_parameter(device, address);
4621 mpClientInterface->setParameters(input, String8(param));
4622 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004623 }
Phil Burk00eeb322016-03-31 12:41:00 -07004624 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004625 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004626 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004627 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004628 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004629 }
4630
4631 if (input != 0) {
4632 addInput(input, desc);
4633 }
4634 } // endif input != 0
4635
Eric Laurentcf2c0212014-07-25 16:20:43 -07004636 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004637 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004638 profiles.removeAt(profile_index);
4639 profile_index--;
4640 } else {
4641 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004642 if (audio_device_is_digital(device)) {
4643 devDesc->importAudioPort(profile);
4644 }
Eric Laurentd4692962014-05-05 18:13:44 -07004645 ALOGV("checkInputsForDevice(): adding input %d", input);
4646 }
4647 } // end scan profiles
4648
4649 if (profiles.isEmpty()) {
4650 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4651 return BAD_VALUE;
4652 }
4653 } else {
4654 // Disconnect
4655 // check if one opened input is not needed any more after disconnecting one device
4656 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4657 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004658 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004659 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4660 mInputs.keyAt(input_index));
4661 inputs.add(mInputs.keyAt(input_index));
4662 }
4663 }
4664 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004665 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004666 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004667 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004668 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004669 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004670 if (profile->supportDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004671 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4672 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004673 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004674 }
4675 }
4676 }
4677 } // end disconnect
4678
4679 return NO_ERROR;
4680}
4681
4682
Eric Laurente0720872014-03-11 09:30:41 -07004683void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004684{
4685 ALOGV("closeOutput(%d)", output);
4686
Eric Laurentc75307b2015-03-17 15:29:32 -07004687 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004688 if (outputDesc == NULL) {
4689 ALOGW("closeOutput() unknown output %d", output);
4690 return;
4691 }
François Gaffie036e1e92015-03-19 10:16:24 +01004692 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004693
Eric Laurente552edb2014-03-10 17:42:56 -07004694 // look for duplicated outputs connected to the output being removed.
4695 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004696 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004697 if (dupOutputDesc->isDuplicated() &&
4698 (dupOutputDesc->mOutput1 == outputDesc ||
4699 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004700 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004701 if (dupOutputDesc->mOutput1 == outputDesc) {
4702 outputDesc2 = dupOutputDesc->mOutput2;
4703 } else {
4704 outputDesc2 = dupOutputDesc->mOutput1;
4705 }
4706 // As all active tracks on duplicated output will be deleted,
4707 // and as they were also referenced on the other output, the reference
4708 // count for their stream type must be adjusted accordingly on
4709 // the other output.
Eric Laurent733ce942017-12-07 12:18:25 -08004710 bool wasActive = outputDesc2->isActive();
Eric Laurent3b73df72014-03-11 09:06:29 -07004711 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004712 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07004713 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004714 }
Eric Laurent733ce942017-12-07 12:18:25 -08004715 // stop() will be a no op if the output is still active but is needed in case all
4716 // active streams refcounts where cleared above
4717 if (wasActive) {
4718 outputDesc2->stop();
4719 }
Eric Laurente552edb2014-03-10 17:42:56 -07004720 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4721 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4722
4723 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004724 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004725 }
4726 }
4727
Eric Laurent05b90f82014-08-27 15:32:29 -07004728 nextAudioPortGeneration();
4729
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004730 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004731 if (index >= 0) {
4732 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004733 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004734 mAudioPatches.removeItemsAt(index);
4735 mpClientInterface->onAudioPatchListUpdate();
4736 }
4737
Eric Laurentfe231122017-11-17 17:48:06 -08004738 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004739
François Gaffie53615e22015-03-19 09:24:12 +01004740 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004741 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004742}
4743
4744void AudioPolicyManager::closeInput(audio_io_handle_t input)
4745{
4746 ALOGV("closeInput(%d)", input);
4747
4748 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4749 if (inputDesc == NULL) {
4750 ALOGW("closeInput() unknown input %d", input);
4751 return;
4752 }
4753
Eric Laurent6a94d692014-05-20 11:18:06 -07004754 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004755
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004756 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004757 if (index >= 0) {
4758 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004759 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004760 mAudioPatches.removeItemsAt(index);
4761 mpClientInterface->onAudioPatchListUpdate();
4762 }
4763
Eric Laurentfe231122017-11-17 17:48:06 -08004764 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004765 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004766}
4767
Eric Laurentc75307b2015-03-17 15:29:32 -07004768SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4769 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004770 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004771{
4772 SortedVector<audio_io_handle_t> outputs;
4773
4774 ALOGVV("getOutputsForDevice() device %04x", device);
4775 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004776 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004777 i, openOutputs.valueAt(i)->isDuplicated(),
4778 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004779 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4780 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4781 outputs.add(openOutputs.keyAt(i));
4782 }
4783 }
4784 return outputs;
4785}
4786
Mikhail Naganov37977152018-07-11 15:54:44 -07004787void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
4788{
4789 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
4790 // output is suspended before any tracks are moved to it
4791 checkA2dpSuspend();
4792 checkOutputForAllStrategies();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004793 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07004794 updateDevicesAndOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004795 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
4796 setMsdPatch();
4797 }
Mikhail Naganov37977152018-07-11 15:54:44 -07004798}
4799
Eric Laurente0720872014-03-11 09:30:41 -07004800void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004801{
4802 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4803 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4804 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4805 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4806
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004807 // also take into account external policy-related changes: add all outputs which are
4808 // associated with policies in the "before" and "after" output vectors
4809 ALOGVV("checkOutputForStrategy(): policy related outputs");
4810 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004811 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004812 if (desc != 0 && desc->mPolicyMix != NULL) {
4813 srcOutputs.add(desc->mIoHandle);
4814 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4815 }
4816 }
4817 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004818 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004819 if (desc != 0 && desc->mPolicyMix != NULL) {
4820 dstOutputs.add(desc->mIoHandle);
4821 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4822 }
4823 }
4824
Mikhail Naganov9de8bd12018-07-23 16:41:31 -07004825 if (srcOutputs != dstOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004826 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4827 // audio from invalidated tracks will be rendered when unmuting
4828 uint32_t maxLatency = 0;
4829 for (audio_io_handle_t srcOut : srcOutputs) {
4830 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4831 if (desc != 0 && maxLatency < desc->latency()) {
4832 maxLatency = desc->latency();
4833 }
4834 }
Eric Laurente552edb2014-03-10 17:42:56 -07004835 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4836 strategy, srcOutputs[0], dstOutputs[0]);
4837 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004838 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004839 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4840 if (desc != 0 && isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004841 setStrategyMute(strategy, true, desc);
Eric Laurentac3a6902018-05-11 16:39:10 -07004842 setStrategyMute(strategy, false, desc, maxLatency * LATENCY_MUTE_FACTOR, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004843 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004844 sp<AudioSourceDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004845 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004846 if (source != 0){
4847 connectAudioSource(source);
4848 }
Eric Laurente552edb2014-03-10 17:42:56 -07004849 }
4850
4851 // Move effects associated to this strategy from previous output to new output
4852 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004853 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004854 }
4855 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004856 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004857 if (getStrategy((audio_stream_type_t)i) == strategy) {
4858 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004859 }
4860 }
4861 }
4862}
4863
Eric Laurente0720872014-03-11 09:30:41 -07004864void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004865{
François Gaffie2110e042015-03-24 08:41:51 +01004866 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004867 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004868 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004869 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004870 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004871 checkOutputForStrategy(STRATEGY_SONIFICATION);
4872 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004873 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004874 checkOutputForStrategy(STRATEGY_MEDIA);
4875 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004876 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004877}
4878
Eric Laurente0720872014-03-11 09:30:41 -07004879void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004880{
François Gaffie53615e22015-03-19 09:24:12 +01004881 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004882 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004883 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004884 return;
4885 }
4886
Eric Laurent3a4311c2014-03-17 12:00:47 -07004887 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004888 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4889 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4890 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004891
4892 // if suspended, restore A2DP output if:
4893 // ((SCO device is NOT connected) ||
4894 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4895 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004896 //
Eric Laurentf732e072016-08-03 19:30:28 -07004897 // if not suspended, suspend A2DP output if:
4898 // (SCO device is connected) &&
4899 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4900 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004901 //
4902 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004903 if (!isScoConnected ||
4904 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4905 AUDIO_POLICY_FORCE_BT_SCO) &&
4906 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4907 AUDIO_POLICY_FORCE_BT_SCO) &&
4908 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004909 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004910
4911 mpClientInterface->restoreOutput(a2dpOutput);
4912 mA2dpSuspended = false;
4913 }
4914 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004915 if (isScoConnected &&
4916 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4917 AUDIO_POLICY_FORCE_BT_SCO) ||
4918 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4919 AUDIO_POLICY_FORCE_BT_SCO) ||
4920 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004921 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004922
4923 mpClientInterface->suspendOutput(a2dpOutput);
4924 mA2dpSuspended = true;
4925 }
4926 }
4927}
4928
Eric Laurentc75307b2015-03-17 15:29:32 -07004929audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4930 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004931{
4932 audio_devices_t device = AUDIO_DEVICE_NONE;
4933
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004934 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004935 if (index >= 0) {
4936 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4937 if (patchDesc->mUid != mUidCached) {
4938 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004939 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004940 return outputDesc->device();
4941 }
4942 }
4943
Eric Laurentf3a5a602018-05-22 18:42:55 -07004944 // Check if an explicit routing request exists for an active stream on this output and
4945 // use it in priority before any other rule
4946 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
4947 if (outputDesc->isStreamActive((audio_stream_type_t)stream)) {
4948 audio_devices_t forcedDevice =
4949 mOutputRoutes.getActiveDeviceForStream(
4950 (audio_stream_type_t)stream, mAvailableOutputDevices);
4951
4952 if (forcedDevice != AUDIO_DEVICE_NONE) {
4953 return forcedDevice;
4954 }
4955 }
4956 }
4957
Eric Laurente552edb2014-03-10 17:42:56 -07004958 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004959 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004960 // use device for strategy enforced audible
4961 // 2: we are in call or the strategy phone is active on the output:
4962 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004963 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004964 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004965 // 4: the strategy for enforced audible is active but not enforced on the output:
4966 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004967 // 5: the strategy accessibility is active on the output:
4968 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004969 // 6: the strategy "respectful" sonification is active on the output:
4970 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004971 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004972 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004973 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004974 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004975 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004976 // use device for strategy t-t-s
Eric Laurent484e9272018-06-07 17:29:23 -07004977
4978 // FIXME: extend use of isStrategyActiveOnSameModule() to all strategies
4979 // with a refined rule considering mutually exclusive devices (using same backend)
4980 // as opposed to all streams on the same audio HAL module.
François Gaffiead3183e2015-03-18 16:55:35 +01004981 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004982 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004983 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4984 } else if (isInCall() ||
Eric Laurent484e9272018-06-07 17:29:23 -07004985 isStrategyActiveOnSameModule(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004986 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004987 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004988 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004989 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
4990 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004991 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4992 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004993 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004994 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004995 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004996 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004997 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004998 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004999 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005000 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01005001 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005002 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07005003 }
5004
Eric Laurent1c333e22014-05-20 10:48:17 -07005005 ALOGV("getNewOutputDevice() selected device %x", device);
5006 return device;
5007}
5008
Eric Laurentfb66dd92016-01-28 18:32:03 -08005009audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07005010{
Eric Laurentfb66dd92016-01-28 18:32:03 -08005011 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005012
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005013 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005014 if (index >= 0) {
5015 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5016 if (patchDesc->mUid != mUidCached) {
5017 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005018 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005019 return inputDesc->mDevice;
5020 }
5021 }
5022
Eric Laurentdc95a252018-04-12 12:46:56 -07005023 // If we are not in call and no client is active on this input, this methods returns
5024 // AUDIO_DEVICE_NONE, causing the patch on the input stream to be released.
Eric Laurentfb66dd92016-01-28 18:32:03 -08005025 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
Eric Laurentdc95a252018-04-12 12:46:56 -07005026 if (source == AUDIO_SOURCE_DEFAULT && isInCall()) {
5027 source = AUDIO_SOURCE_VOICE_COMMUNICATION;
5028 }
5029 if (source != AUDIO_SOURCE_DEFAULT) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08005030 device = getDeviceAndMixForInputSource(source);
5031 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005032
Eric Laurente552edb2014-03-10 17:42:56 -07005033 return device;
5034}
5035
Eric Laurent794fde22016-03-11 09:50:45 -08005036bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
5037 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08005038 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08005039}
5040
Eric Laurente0720872014-03-11 09:30:41 -07005041uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005042 return (uint32_t)getStrategy(stream);
5043}
5044
Eric Laurente0720872014-03-11 09:30:41 -07005045audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005046 // By checking the range of stream before calling getStrategy, we avoid
5047 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
5048 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08005049 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005050 return AUDIO_DEVICE_NONE;
5051 }
Eric Laurent28d09f02016-03-08 10:43:05 -08005052 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08005053 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
5054 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08005055 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07005056 }
Eric Laurent794fde22016-03-11 09:50:45 -08005057 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08005058 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07005059 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005060 for (audio_io_handle_t output : getOutputsForDevice(curDevices, mOutputs)) {
5061 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08005062 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08005063 curDevices |= outputDesc->device();
5064 }
5065 }
5066 devices |= curDevices;
Eric Laurente552edb2014-03-10 17:42:56 -07005067 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005068
5069 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
5070 and doesn't really need to.*/
5071 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
5072 devices |= AUDIO_DEVICE_OUT_SPEAKER;
5073 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
5074 }
Eric Laurente552edb2014-03-10 17:42:56 -07005075 return devices;
5076}
5077
François Gaffie2110e042015-03-24 08:41:51 +01005078routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
5079{
Eric Laurent223fd5c2014-11-11 13:43:36 -08005080 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01005081 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005082}
5083
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005084uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
5085 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005086 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5087 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
5088 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005089 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5090 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
5091 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005092 // usage to strategy mapping
François Gaffie2110e042015-03-24 08:41:51 +01005093 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005094}
5095
Eric Laurente0720872014-03-11 09:30:41 -07005096void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005097 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005098 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07005099 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
5100 updateDevicesAndOutputs();
5101 break;
5102 default:
5103 break;
5104 }
5105}
5106
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005107uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07005108
5109 // skip beacon mute management if a dedicated TTS output is available
5110 if (mTtsOutputAvailable) {
5111 return 0;
5112 }
5113
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005114 switch(event) {
5115 case STARTING_OUTPUT:
5116 mBeaconMuteRefCount++;
5117 break;
5118 case STOPPING_OUTPUT:
5119 if (mBeaconMuteRefCount > 0) {
5120 mBeaconMuteRefCount--;
5121 }
5122 break;
5123 case STARTING_BEACON:
5124 mBeaconPlayingRefCount++;
5125 break;
5126 case STOPPING_BEACON:
5127 if (mBeaconPlayingRefCount > 0) {
5128 mBeaconPlayingRefCount--;
5129 }
5130 break;
5131 }
5132
5133 if (mBeaconMuteRefCount > 0) {
5134 // any playback causes beacon to be muted
5135 return setBeaconMute(true);
5136 } else {
5137 // no other playback: unmute when beacon starts playing, mute when it stops
5138 return setBeaconMute(mBeaconPlayingRefCount == 0);
5139 }
5140}
5141
5142uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5143 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5144 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5145 // keep track of muted state to avoid repeating mute/unmute operations
5146 if (mBeaconMuted != mute) {
5147 // mute/unmute AUDIO_STREAM_TTS on all outputs
5148 ALOGV("\t muting %d", mute);
5149 uint32_t maxLatency = 0;
5150 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005151 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005152 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07005153 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005154 0 /*delay*/, AUDIO_DEVICE_NONE);
5155 const uint32_t latency = desc->latency() * 2;
5156 if (latency > maxLatency) {
5157 maxLatency = latency;
5158 }
5159 }
5160 mBeaconMuted = mute;
5161 return maxLatency;
5162 }
5163 return 0;
5164}
5165
Eric Laurente0720872014-03-11 09:30:41 -07005166audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01005167 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005168{
Eric Laurentf3a5a602018-05-22 18:42:55 -07005169 // Check if an explicit routing request exists for a stream type corresponding to the
5170 // specified strategy and use it in priority over default routing rules.
5171 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
5172 if (getStrategy((audio_stream_type_t)stream) == strategy) {
5173 audio_devices_t forcedDevice =
5174 mOutputRoutes.getActiveDeviceForStream(
5175 (audio_stream_type_t)stream, mAvailableOutputDevices);
5176 if (forcedDevice != AUDIO_DEVICE_NONE) {
5177 return forcedDevice;
5178 }
Paul McLeanaa981192015-03-21 09:55:15 -07005179 }
5180 }
5181
Eric Laurente552edb2014-03-10 17:42:56 -07005182 if (fromCache) {
5183 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
5184 strategy, mDeviceForStrategy[strategy]);
5185 return mDeviceForStrategy[strategy];
5186 }
François Gaffie2110e042015-03-24 08:41:51 +01005187 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07005188}
5189
Eric Laurente0720872014-03-11 09:30:41 -07005190void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005191{
5192 for (int i = 0; i < NUM_STRATEGIES; i++) {
5193 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
5194 }
5195 mPreviousOutputs = mOutputs;
5196}
5197
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005198uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005199 audio_devices_t prevDevice,
5200 uint32_t delayMs)
5201{
5202 // mute/unmute strategies using an incompatible device combination
5203 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5204 // if unmuting, unmute only after the specified delay
5205 if (outputDesc->isDuplicated()) {
5206 return 0;
5207 }
5208
5209 uint32_t muteWaitMs = 0;
5210 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07005211 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005212
5213 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
5214 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07005215 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07005216 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
5217 bool doMute = false;
5218
5219 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
5220 doMute = true;
5221 outputDesc->mStrategyMutedByDevice[i] = true;
5222 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
5223 doMute = true;
5224 outputDesc->mStrategyMutedByDevice[i] = false;
5225 }
Eric Laurent99401132014-05-07 19:48:15 -07005226 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005227 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005228 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005229 // skip output if it does not share any device with current output
5230 if ((desc->supportedDevices() & outputDesc->supportedDevices())
5231 == AUDIO_DEVICE_NONE) {
5232 continue;
5233 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005234 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07005235 mute ? "muting" : "unmuting", i, curDevice);
5236 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005237 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005238 if (mute) {
5239 // FIXME: should not need to double latency if volume could be applied
5240 // immediately by the audioflinger mixer. We must account for the delay
5241 // between now and the next time the audioflinger thread for this output
5242 // will process a buffer (which corresponds to one buffer size,
5243 // usually 1/2 or 1/4 of the latency).
5244 if (muteWaitMs < desc->latency() * 2) {
5245 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005246 }
5247 }
5248 }
5249 }
5250 }
5251 }
5252
Eric Laurent99401132014-05-07 19:48:15 -07005253 // temporary mute output if device selection changes to avoid volume bursts due to
5254 // different per device volumes
5255 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005256 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5257 // temporary mute duration is conservatively set to 4 times the reported latency
5258 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5259 if (muteWaitMs < tempMuteWaitMs) {
5260 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005261 }
Eric Laurentdc462862016-07-19 12:29:53 -07005262
Eric Laurent99401132014-05-07 19:48:15 -07005263 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005264 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005265 // make sure that we do not start the temporary mute period too early in case of
5266 // delayed device change
5267 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005268 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07005269 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07005270 }
5271 }
5272 }
5273
Eric Laurente552edb2014-03-10 17:42:56 -07005274 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5275 if (muteWaitMs > delayMs) {
5276 muteWaitMs -= delayMs;
5277 usleep(muteWaitMs * 1000);
5278 return muteWaitMs;
5279 }
5280 return 0;
5281}
5282
Eric Laurentc75307b2015-03-17 15:29:32 -07005283uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005284 audio_devices_t device,
5285 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07005286 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005287 audio_patch_handle_t *patchHandle,
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005288 const char *address,
5289 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005290{
Eric Laurentc75307b2015-03-17 15:29:32 -07005291 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005292 AudioParameter param;
5293 uint32_t muteWaitMs;
5294
5295 if (outputDesc->isDuplicated()) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005296 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs,
5297 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
5298 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs,
5299 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005300 return muteWaitMs;
5301 }
5302 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5303 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07005304 if ((device != AUDIO_DEVICE_NONE) &&
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005305 ((device & outputDesc->supportedDevices()) == AUDIO_DEVICE_NONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005306 return 0;
5307 }
5308
5309 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07005310 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07005311
5312 audio_devices_t prevDevice = outputDesc->mDevice;
5313
Paul McLeanaa981192015-03-21 09:55:15 -07005314 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005315
5316 if (device != AUDIO_DEVICE_NONE) {
5317 outputDesc->mDevice = device;
5318 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005319
5320 // if the outputs are not materially active, there is no need to mute.
5321 if (requiresMuteCheck) {
5322 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
5323 } else {
5324 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5325 muteWaitMs = 0;
5326 }
Eric Laurente552edb2014-03-10 17:42:56 -07005327
5328 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005329 // the requested device is AUDIO_DEVICE_NONE
5330 // OR the requested device is the same as current device
5331 // AND force is not specified
5332 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07005333 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07005334 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
5335 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005336 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005337 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005338 return muteWaitMs;
5339 }
5340
5341 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07005342
Eric Laurente552edb2014-03-10 17:42:56 -07005343 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07005344 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005345 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005346 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07005347 DeviceVector deviceList;
5348 if ((address == NULL) || (strlen(address) == 0)) {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005349 deviceList = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurentc40d9692016-04-13 19:14:13 -07005350 } else {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005351 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
5352 device, String8(address));
5353 if (deviceDesc) deviceList.add(deviceDesc);
Eric Laurentc40d9692016-04-13 19:14:13 -07005354 }
5355
Eric Laurent1c333e22014-05-20 10:48:17 -07005356 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005357 PatchBuilder patchBuilder;
5358 patchBuilder.addSource(outputDesc);
Eric Laurent1c333e22014-05-20 10:48:17 -07005359 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005360 patchBuilder.addSink(deviceList.itemAt(i));
Eric Laurent1c333e22014-05-20 10:48:17 -07005361 }
Mikhail Naganovdc769682018-05-04 15:34:08 -07005362 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005363 }
bryant_liuf5e7e792014-08-19 20:07:05 +08005364
5365 // inform all input as well
5366 for (size_t i = 0; i < mInputs.size(); i++) {
5367 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01005368 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08005369 AudioParameter inputCmd = AudioParameter();
5370 ALOGV("%s: inform input %d of device:%d", __func__,
5371 inputDescriptor->mIoHandle, device);
5372 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
5373 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
5374 inputCmd.toString(),
5375 delayMs);
5376 }
5377 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005378 }
Eric Laurente552edb2014-03-10 17:42:56 -07005379
5380 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07005381 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005382
5383 return muteWaitMs;
5384}
5385
Eric Laurentc75307b2015-03-17 15:29:32 -07005386status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005387 int delayMs,
5388 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005389{
Eric Laurent6a94d692014-05-20 11:18:06 -07005390 ssize_t index;
5391 if (patchHandle) {
5392 index = mAudioPatches.indexOfKey(*patchHandle);
5393 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005394 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005395 }
5396 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005397 return INVALID_OPERATION;
5398 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005399 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5400 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005401 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005402 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005403 removeAudioPatch(patchDesc->mHandle);
5404 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005405 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005406 return status;
5407}
5408
5409status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5410 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005411 bool force,
5412 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005413{
5414 status_t status = NO_ERROR;
5415
Eric Laurent1f2f2232014-06-02 12:01:23 -07005416 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005417 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5418 inputDesc->mDevice = device;
5419
Mikhail Naganov708e0382018-05-30 09:53:04 -07005420 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005421 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005422 PatchBuilder patchBuilder;
5423 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005424 // AUDIO_SOURCE_HOTWORD is for internal use only:
5425 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07005426 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5427 auto result = usecase;
5428 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5429 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5430 }
5431 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07005432 //only one input device for now
Mikhail Naganovdc769682018-05-04 15:34:08 -07005433 addSource(deviceList.itemAt(0));
5434 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005435 }
5436 }
5437 return status;
5438}
5439
Eric Laurent6a94d692014-05-20 11:18:06 -07005440status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5441 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005442{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005443 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005444 ssize_t index;
5445 if (patchHandle) {
5446 index = mAudioPatches.indexOfKey(*patchHandle);
5447 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005448 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005449 }
5450 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005451 return INVALID_OPERATION;
5452 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005453 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5454 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005455 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005456 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005457 removeAudioPatch(patchDesc->mHandle);
5458 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005459 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005460 return status;
5461}
5462
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005463sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005464 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005465 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005466 audio_format_t& format,
5467 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005468 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005469{
5470 // Choose an input profile based on the requested capture parameters: select the first available
5471 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005472 //
5473 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5474 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005475
Glenn Kasten730b9262018-03-29 15:01:26 -07005476 sp<IOProfile> firstInexact;
5477 uint32_t updatedSamplingRate = 0;
5478 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5479 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005480 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005481 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005482 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005483 //updatedFormat = format;
Eric Laurent275e8e92014-11-30 15:14:47 -08005484 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005485 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005486 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005487 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005488 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005489 &channelMask /*updatedChannelMask*/,
5490 // FIXME ugly cast
5491 (audio_output_flags_t) flags,
5492 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005493 return profile;
5494 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005495 if (firstInexact == nullptr && profile->isCompatibleProfile(device, address,
5496 samplingRate,
5497 &updatedSamplingRate,
5498 format,
5499 &updatedFormat,
5500 channelMask,
5501 &updatedChannelMask,
5502 // FIXME ugly cast
5503 (audio_output_flags_t) flags,
5504 false /*exactMatchRequiredForInputFlags*/)) {
5505 firstInexact = profile;
5506 }
5507
Eric Laurente552edb2014-03-10 17:42:56 -07005508 }
5509 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005510 if (firstInexact != nullptr) {
5511 samplingRate = updatedSamplingRate;
5512 format = updatedFormat;
5513 channelMask = updatedChannelMask;
5514 return firstInexact;
5515 }
Eric Laurente552edb2014-03-10 17:42:56 -07005516 return NULL;
5517}
5518
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005519
5520audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005521 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005522{
François Gaffie036e1e92015-03-19 10:16:24 +01005523 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5524 audio_devices_t selectedDeviceFromMix =
5525 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005526
François Gaffie036e1e92015-03-19 10:16:24 +01005527 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5528 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005529 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005530 return getDeviceForInputSource(inputSource);
5531}
5532
5533audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5534{
Eric Laurentad2e7b92017-09-14 20:06:42 -07005535 // Routing
5536 // Scan the whole RouteMap to see if we have an explicit route:
5537 // if the input source in the RouteMap is the same as the argument above,
5538 // and activity count is non-zero and the device in the route descriptor is available
5539 // then select this device.
Paul McLean466dc8e2015-04-17 13:15:36 -06005540 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
5541 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
Eric Laurent2157f5b2018-04-25 18:33:02 -07005542 if ((inputSource == route->mSource) && route->isActiveOrChanged() &&
Eric Laurentad2e7b92017-09-14 20:06:42 -07005543 (mAvailableInputDevices.indexOf(route->mDeviceDescriptor) >= 0)) {
Paul McLean466dc8e2015-04-17 13:15:36 -06005544 return route->mDeviceDescriptor->type();
5545 }
5546 }
5547
5548 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005549}
5550
Eric Laurente0720872014-03-11 09:30:41 -07005551float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005552 int index,
5553 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005554{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005555 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005556
5557 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5558 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5559 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5560 // the ringtone volume
5561 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5562 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5563 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5564 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5565 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5566 }
5567
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005568 // in-call: always cap volume by voice volume + some low headroom
5569 if ((stream != AUDIO_STREAM_VOICE_CALL) &&
Eric Laurent7731b5a2018-04-06 15:47:22 -07005570 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005571 switch (stream) {
5572 case AUDIO_STREAM_SYSTEM:
5573 case AUDIO_STREAM_RING:
5574 case AUDIO_STREAM_MUSIC:
5575 case AUDIO_STREAM_ALARM:
5576 case AUDIO_STREAM_NOTIFICATION:
5577 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5578 case AUDIO_STREAM_DTMF:
5579 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005580 int voiceVolumeIndex =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005581 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, device);
Eric Laurent7731b5a2018-04-06 15:47:22 -07005582 const float maxVoiceVolDb =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005583 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, device)
Eric Laurent7731b5a2018-04-06 15:47:22 -07005584 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005585 if (volumeDB > maxVoiceVolDb) {
5586 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5587 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5588 volumeDB = maxVoiceVolDb;
5589 }
5590 } break;
5591 default:
5592 break;
5593 }
5594 }
5595
Eric Laurente552edb2014-03-10 17:42:56 -07005596 // if a headset is connected, apply the following rules to ring tones and notifications
5597 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005598 // - always attenuate notifications volume by 6dB
5599 // - attenuate ring tones volume by 6dB unless music is not playing and
5600 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005601 // - if music is playing, always limit the volume to current music volume,
5602 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005603 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005604 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5605 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5606 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005607 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005608 AUDIO_DEVICE_OUT_USB_HEADSET |
5609 AUDIO_DEVICE_OUT_HEARING_AID)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005610 ((stream_strategy == STRATEGY_SONIFICATION)
5611 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005612 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005613 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005614 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005615 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005616 // when the phone is ringing we must consider that music could have been paused just before
5617 // by the music application and behave as if music was active if the last music track was
5618 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005619 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005620 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005621 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005622 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005623 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005624 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5625 musicDevice),
5626 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005627 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5628 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005629 if (volumeDB > minVolDB) {
5630 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005631 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005632 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005633 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5634 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5635 // on A2DP, also ensure notification volume is not too low compared to media when
5636 // intended to be played
5637 if ((volumeDB > -96.0f) &&
5638 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5639 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5640 stream, device,
5641 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5642 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5643 }
5644 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005645 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5646 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005647 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005648 }
5649 }
5650
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005651 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005652}
5653
Eric Laurent3839bc02018-07-10 18:33:34 -07005654int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
5655 audio_stream_type_t srcStream,
5656 audio_stream_type_t dstStream)
5657{
5658 if (srcStream == dstStream) {
5659 return srcIndex;
5660 }
5661 float minSrc = (float)mVolumeCurves->getVolumeIndexMin(srcStream);
5662 float maxSrc = (float)mVolumeCurves->getVolumeIndexMax(srcStream);
5663 float minDst = (float)mVolumeCurves->getVolumeIndexMin(dstStream);
5664 float maxDst = (float)mVolumeCurves->getVolumeIndexMax(dstStream);
5665
5666 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
5667}
5668
Eric Laurente0720872014-03-11 09:30:41 -07005669status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005670 int index,
5671 const sp<AudioOutputDescriptor>& outputDesc,
5672 audio_devices_t device,
5673 int delayMs,
5674 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005675{
Eric Laurente552edb2014-03-10 17:42:56 -07005676 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005677 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005678 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005679 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005680 return NO_ERROR;
5681 }
François Gaffie2110e042015-03-24 08:41:51 +01005682 audio_policy_forced_cfg_t forceUseForComm =
5683 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005684 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005685 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5686 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005687 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005688 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005689 return INVALID_OPERATION;
5690 }
5691
Eric Laurentc75307b2015-03-17 15:29:32 -07005692 if (device == AUDIO_DEVICE_NONE) {
5693 device = outputDesc->device();
5694 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005695
Eric Laurentffbc80f2015-03-18 18:30:19 -07005696 float volumeDb = computeVolume(stream, index, device);
HW Leeda7581e2018-05-22 18:31:34 +08005697 if (outputDesc->isFixedVolume(device) ||
5698 // Force VoIP volume to max for bluetooth SCO
5699 ((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
5700 (device & AUDIO_DEVICE_OUT_ALL_SCO) != 0)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005701 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005702 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005703
Eric Laurentffbc80f2015-03-18 18:30:19 -07005704 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005705
Eric Laurent3b73df72014-03-11 09:06:29 -07005706 if (stream == AUDIO_STREAM_VOICE_CALL ||
5707 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005708 float voiceVolume;
5709 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005710 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurent3839bc02018-07-10 18:33:34 -07005711 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005712 } else {
5713 voiceVolume = 1.0;
5714 }
5715
Eric Laurent18fba842016-03-31 14:41:26 -07005716 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005717 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5718 mLastVoiceVolume = voiceVolume;
5719 }
5720 }
5721
5722 return NO_ERROR;
5723}
5724
Eric Laurentc75307b2015-03-17 15:29:32 -07005725void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5726 audio_devices_t device,
5727 int delayMs,
5728 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005729{
Eric Laurentc75307b2015-03-17 15:29:32 -07005730 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005731
Eric Laurent794fde22016-03-11 09:50:45 -08005732 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005733 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005734 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005735 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005736 device,
5737 delayMs,
5738 force);
5739 }
5740}
5741
Eric Laurente0720872014-03-11 09:30:41 -07005742void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005743 bool on,
5744 const sp<AudioOutputDescriptor>& outputDesc,
5745 int delayMs,
5746 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005747{
Eric Laurent72249d52015-06-08 11:12:15 -07005748 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5749 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005750 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005751 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005752 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005753 }
5754 }
5755}
5756
Eric Laurente0720872014-03-11 09:30:41 -07005757void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005758 bool on,
5759 const sp<AudioOutputDescriptor>& outputDesc,
5760 int delayMs,
5761 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005762{
Eric Laurente552edb2014-03-10 17:42:56 -07005763 if (device == AUDIO_DEVICE_NONE) {
5764 device = outputDesc->device();
5765 }
5766
Eric Laurentc75307b2015-03-17 15:29:32 -07005767 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5768 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005769
5770 if (on) {
5771 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005772 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005773 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005774 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005775 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005776 }
5777 }
5778 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5779 outputDesc->mMuteCount[stream]++;
5780 } else {
5781 if (outputDesc->mMuteCount[stream] == 0) {
5782 ALOGV("setStreamMute() unmuting non muted stream!");
5783 return;
5784 }
5785 if (--outputDesc->mMuteCount[stream] == 0) {
5786 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005787 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005788 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005789 device,
5790 delayMs);
5791 }
5792 }
5793}
5794
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005795audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5796{
5797 // flags to stream type mapping
5798 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5799 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5800 }
5801 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5802 return AUDIO_STREAM_BLUETOOTH_SCO;
5803 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005804 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5805 return AUDIO_STREAM_TTS;
5806 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005807
5808 // usage to stream type mapping
5809 switch (attr->usage) {
5810 case AUDIO_USAGE_MEDIA:
5811 case AUDIO_USAGE_GAME:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005812 case AUDIO_USAGE_ASSISTANT:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005813 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5814 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005815 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5816 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005817 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5818 return AUDIO_STREAM_SYSTEM;
5819 case AUDIO_USAGE_VOICE_COMMUNICATION:
5820 return AUDIO_STREAM_VOICE_CALL;
5821
5822 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5823 return AUDIO_STREAM_DTMF;
5824
5825 case AUDIO_USAGE_ALARM:
5826 return AUDIO_STREAM_ALARM;
5827 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5828 return AUDIO_STREAM_RING;
5829
5830 case AUDIO_USAGE_NOTIFICATION:
5831 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5832 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5833 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5834 case AUDIO_USAGE_NOTIFICATION_EVENT:
5835 return AUDIO_STREAM_NOTIFICATION;
5836
5837 case AUDIO_USAGE_UNKNOWN:
5838 default:
5839 return AUDIO_STREAM_MUSIC;
5840 }
5841}
Eric Laurente83b55d2014-11-14 10:06:21 -08005842
François Gaffie53615e22015-03-19 09:24:12 +01005843bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5844{
Eric Laurente83b55d2014-11-14 10:06:21 -08005845 // has flags that map to a strategy?
5846 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5847 return true;
5848 }
5849
5850 // has known usage?
5851 switch (paa->usage) {
5852 case AUDIO_USAGE_UNKNOWN:
5853 case AUDIO_USAGE_MEDIA:
5854 case AUDIO_USAGE_VOICE_COMMUNICATION:
5855 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5856 case AUDIO_USAGE_ALARM:
5857 case AUDIO_USAGE_NOTIFICATION:
5858 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5859 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5860 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5861 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5862 case AUDIO_USAGE_NOTIFICATION_EVENT:
5863 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5864 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5865 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5866 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005867 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005868 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005869 break;
5870 default:
5871 return false;
5872 }
5873 return true;
5874}
5875
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005876bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005877 routing_strategy strategy, uint32_t inPastMs,
5878 nsecs_t sysTime) const
5879{
5880 if ((sysTime == 0) && (inPastMs != 0)) {
5881 sysTime = systemTime();
5882 }
Eric Laurent794fde22016-03-11 09:50:45 -08005883 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005884 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5885 (NUM_STRATEGIES == strategy)) &&
5886 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5887 return true;
5888 }
5889 }
5890 return false;
5891}
5892
Eric Laurent484e9272018-06-07 17:29:23 -07005893bool AudioPolicyManager::isStrategyActiveOnSameModule(const sp<AudioOutputDescriptor>& outputDesc,
5894 routing_strategy strategy, uint32_t inPastMs,
5895 nsecs_t sysTime) const
5896{
5897 for (size_t i = 0; i < mOutputs.size(); i++) {
5898 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5899 if (outputDesc->sharesHwModuleWith(desc)
5900 && isStrategyActive(desc, strategy, inPastMs, sysTime)) {
5901 return true;
5902 }
5903 }
5904 return false;
5905}
5906
François Gaffie2110e042015-03-24 08:41:51 +01005907audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5908{
5909 return mEngine->getForceUse(usage);
5910}
5911
5912bool AudioPolicyManager::isInCall()
5913{
5914 return isStateInCall(mEngine->getPhoneState());
5915}
5916
5917bool AudioPolicyManager::isStateInCall(int state)
5918{
5919 return is_state_in_call(state);
5920}
5921
Eric Laurentd60560a2015-04-10 11:31:20 -07005922void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5923{
5924 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5925 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
5926 if (sourceDesc->mDevice->equals(deviceDesc)) {
5927 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle());
5928 stopAudioSource(sourceDesc->getHandle());
5929 }
5930 }
5931
5932 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5933 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5934 bool release = false;
5935 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5936 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5937 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5938 source->ext.device.type == deviceDesc->type()) {
5939 release = true;
5940 }
5941 }
5942 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5943 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5944 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5945 sink->ext.device.type == deviceDesc->type()) {
5946 release = true;
5947 }
5948 }
5949 if (release) {
5950 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5951 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5952 }
5953 }
5954}
5955
Phil Burk09bc4612016-02-24 15:58:15 -08005956// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005957void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5958 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005959 // TODO Set this based on Config properties.
5960 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005961
5962 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5963 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005964 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005965
jiabin81772902018-04-02 17:52:27 -07005966 // If MANUAL, keep the supported surround sound formats as current enabled ones.
5967 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
5968 formats.clear();
5969 for (auto it = mSurroundFormats.begin(); it != mSurroundFormats.end(); it++) {
5970 formats.add(*it);
Phil Burk09bc4612016-02-24 15:58:15 -08005971 }
jiabin81772902018-04-02 17:52:27 -07005972 // Always enable IEC61937 when in MANUAL mode.
5973 formats.add(AUDIO_FORMAT_IEC61937);
5974 } else { // NEVER, AUTO or ALWAYS
5975 // Analyze original support for various formats.
5976 bool supportsAC3 = false;
5977 bool supportsOtherSurround = false;
5978 bool supportsIEC61937 = false;
5979 mSurroundFormats.clear();
5980 for (ssize_t formatIndex = 0; formatIndex < (ssize_t)formats.size(); formatIndex++) {
5981 audio_format_t format = formats[formatIndex];
5982 switch (format) {
5983 case AUDIO_FORMAT_AC3:
5984 supportsAC3 = true;
5985 break;
5986 case AUDIO_FORMAT_E_AC3:
5987 case AUDIO_FORMAT_DTS:
5988 case AUDIO_FORMAT_DTS_HD:
5989 // If ALWAYS, remove all other surround formats here
5990 // since we will add them later.
5991 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5992 formats.removeAt(formatIndex);
5993 formatIndex--;
5994 }
5995 supportsOtherSurround = true;
5996 break;
5997 case AUDIO_FORMAT_IEC61937:
5998 supportsIEC61937 = true;
5999 break;
6000 default:
6001 break;
6002 }
6003 }
Phil Burk09bc4612016-02-24 15:58:15 -08006004
jiabin81772902018-04-02 17:52:27 -07006005 // Modify formats based on surround preferences.
6006 // If NEVER, remove support for surround formats.
6007 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
6008 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
6009 // Remove surround sound related formats.
6010 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
6011 audio_format_t format = formats[formatIndex];
6012 switch(format) {
6013 case AUDIO_FORMAT_AC3:
6014 case AUDIO_FORMAT_E_AC3:
6015 case AUDIO_FORMAT_DTS:
6016 case AUDIO_FORMAT_DTS_HD:
6017 case AUDIO_FORMAT_IEC61937:
6018 formats.removeAt(formatIndex);
6019 break;
6020 default:
6021 formatIndex++; // keep it
6022 break;
6023 }
6024 }
6025 supportsAC3 = false;
6026 supportsOtherSurround = false;
6027 supportsIEC61937 = false;
6028 }
6029 } else { // AUTO or ALWAYS
6030 // Most TVs support AC3 even if they do not report it in the EDID.
6031 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
6032 && !supportsAC3) {
6033 formats.add(AUDIO_FORMAT_AC3);
6034 supportsAC3 = true;
6035 }
6036
6037 // If ALWAYS, add support for raw surround formats if all are missing.
6038 // This assumes that if any of these formats are reported by the HAL
6039 // then the report is valid and should not be modified.
6040 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
6041 formats.add(AUDIO_FORMAT_E_AC3);
6042 formats.add(AUDIO_FORMAT_DTS);
6043 formats.add(AUDIO_FORMAT_DTS_HD);
6044 supportsOtherSurround = true;
6045 }
6046
6047 // Add support for IEC61937 if any raw surround supported.
6048 // The HAL could do this but add it here, just in case.
6049 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
6050 formats.add(AUDIO_FORMAT_IEC61937);
6051 supportsIEC61937 = true;
6052 }
6053
6054 // Add reported surround sound formats to enabled surround formats.
6055 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
Phil Burk07ac1142016-03-25 13:39:29 -07006056 audio_format_t format = formats[formatIndex];
6057 switch(format) {
6058 case AUDIO_FORMAT_AC3:
6059 case AUDIO_FORMAT_E_AC3:
6060 case AUDIO_FORMAT_DTS:
6061 case AUDIO_FORMAT_DTS_HD:
jiabin81772902018-04-02 17:52:27 -07006062 case AUDIO_FORMAT_AAC_LC:
6063 case AUDIO_FORMAT_DOLBY_TRUEHD:
6064 case AUDIO_FORMAT_E_AC3_JOC:
6065 mSurroundFormats.insert(format);
Phil Burk07ac1142016-03-25 13:39:29 -07006066 default:
Phil Burk07ac1142016-03-25 13:39:29 -07006067 break;
6068 }
Phil Burk09bc4612016-02-24 15:58:15 -08006069 }
Phil Burk07ac1142016-03-25 13:39:29 -07006070 }
Phil Burk09bc4612016-02-24 15:58:15 -08006071 }
Phil Burk0709b0a2016-03-31 12:54:57 -07006072}
6073
6074// Modify the list of channel masks supported.
6075void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
6076 ChannelsVector &channelMasks = *channelMasksPtr;
6077 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6078 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
6079
6080 // If NEVER, then remove support for channelMasks > stereo.
6081 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
6082 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
6083 audio_channel_mask_t channelMask = channelMasks[maskIndex];
6084 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
6085 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
6086 channelMasks.removeAt(maskIndex);
6087 } else {
6088 maskIndex++;
6089 }
6090 }
jiabin81772902018-04-02 17:52:27 -07006091 // If ALWAYS or MANUAL, then make sure we at least support 5.1
6092 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
6093 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006094 bool supports5dot1 = false;
6095 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006096 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006097 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
6098 supports5dot1 = true;
6099 break;
6100 }
6101 }
6102 // If not then add 5.1 support.
6103 if (!supports5dot1) {
6104 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
6105 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
6106 }
Phil Burk09bc4612016-02-24 15:58:15 -08006107 }
6108}
6109
Phil Burk00eeb322016-03-31 12:41:00 -07006110void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
6111 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01006112 AudioProfileVector &profiles)
6113{
6114 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07006115
François Gaffie112b0af2015-11-19 16:13:25 +01006116 // Format MUST be checked first to update the list of AudioProfile
6117 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006118 reply = mpClientInterface->getParameters(
6119 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07006120 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006121 AudioParameter repliedParameters(reply);
6122 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006123 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01006124 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
6125 return;
6126 }
Phil Burk09bc4612016-02-24 15:58:15 -08006127 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07006128 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006129 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07006130 }
Phil Burk09bc4612016-02-24 15:58:15 -08006131 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01006132 }
François Gaffie112b0af2015-11-19 16:13:25 +01006133
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006134 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08006135 ChannelsVector channelMasks;
6136 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01006137 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07006138 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01006139
6140 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006141 reply = mpClientInterface->getParameters(
6142 ioHandle,
6143 requestedParameters.toString() + ";" +
6144 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01006145 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006146 AudioParameter repliedParameters(reply);
6147 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006148 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006149 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01006150 }
6151 }
6152 if (profiles.hasDynamicChannelsFor(format)) {
6153 reply = mpClientInterface->getParameters(ioHandle,
6154 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07006155 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01006156 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006157 AudioParameter repliedParameters(reply);
6158 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006159 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006160 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07006161 if (device == AUDIO_DEVICE_OUT_HDMI) {
6162 filterSurroundChannelMasks(&channelMasks);
6163 }
François Gaffie112b0af2015-11-19 16:13:25 +01006164 }
6165 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08006166 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006167 }
6168}
Eric Laurentd60560a2015-04-10 11:31:20 -07006169
Mikhail Naganovdc769682018-05-04 15:34:08 -07006170status_t AudioPolicyManager::installPatch(const char *caller,
6171 audio_patch_handle_t *patchHandle,
6172 AudioIODescriptorInterface *ioDescriptor,
6173 const struct audio_patch *patch,
6174 int delayMs)
6175{
6176 ssize_t index = mAudioPatches.indexOfKey(
6177 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6178 *patchHandle : ioDescriptor->getPatchHandle());
6179 sp<AudioPatch> patchDesc;
6180 status_t status = installPatch(
6181 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6182 if (status == NO_ERROR) {
6183 ioDescriptor->setPatchHandle(patchDesc->mHandle);
6184 }
6185 return status;
6186}
6187
6188status_t AudioPolicyManager::installPatch(const char *caller,
6189 ssize_t index,
6190 audio_patch_handle_t *patchHandle,
6191 const struct audio_patch *patch,
6192 int delayMs,
6193 uid_t uid,
6194 sp<AudioPatch> *patchDescPtr)
6195{
6196 sp<AudioPatch> patchDesc;
6197 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6198 if (index >= 0) {
6199 patchDesc = mAudioPatches.valueAt(index);
6200 afPatchHandle = patchDesc->mAfPatchHandle;
6201 }
6202
6203 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6204 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6205 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6206 if (status == NO_ERROR) {
6207 if (index < 0) {
6208 patchDesc = new AudioPatch(patch, uid);
6209 addAudioPatch(patchDesc->mHandle, patchDesc);
6210 } else {
6211 patchDesc->mPatch = *patch;
6212 }
6213 patchDesc->mAfPatchHandle = afPatchHandle;
6214 if (patchHandle) {
6215 *patchHandle = patchDesc->mHandle;
6216 }
6217 nextAudioPortGeneration();
6218 mpClientInterface->onAudioPatchListUpdate();
6219 }
6220 if (patchDescPtr) *patchDescPtr = patchDesc;
6221 return status;
6222}
6223
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006224} // namespace android