blob: cd40bc5b350a68fe746135b4206d634b669a74b6 [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;
Eric Laurent97ac8712018-07-27 18:59:02 -0700791 const audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100792 audio_devices_t msdDevice = getMsdAudioOutDeviceTypes();
Eric Laurent8fc147b2018-07-22 19:13:55 -0700793
Eric 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"
Eric Laurent97ac8712018-07-27 18:59:02 -0700811 " session %d selectedDeviceId %d",
812 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
813 session, requestedDeviceId);
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
Eric Laurent97ac8712018-07-27 18:59:02 -0700820 *stream = streamTypefromAttributesInt(&attributes);
821
822 strategy = getStrategyForAttr(&attributes);
823
Scott Randolph7b1fd232018-06-18 15:33:03 -0700824 // First check for explicit routing (eg. setPreferredDevice)
Eric Laurent97ac8712018-07-27 18:59:02 -0700825 if (requestedDeviceId != AUDIO_PORT_HANDLE_NONE) {
826 sp<DeviceDescriptor> deviceDesc =
827 mAvailableOutputDevices.getDeviceFromId(requestedDeviceId);
828 device = deviceDesc->type();
Scott Randolph7b1fd232018-06-18 15:33:03 -0700829 } else {
830 // If no explict route, is there a matching dynamic policy that applies?
831 sp<SwAudioOutputDescriptor> desc;
832 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
833 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
834 if (!audio_has_proportional_frames(config->format)) {
835 return BAD_VALUE;
836 }
837 *stream = streamTypefromAttributesInt(&attributes);
838 *output = desc->mIoHandle;
Eric Laurent97ac8712018-07-27 18:59:02 -0700839 AudioMix *mix = desc->mPolicyMix;
840 sp<DeviceDescriptor> deviceDesc =
841 mAvailableOutputDevices.getDevice(mix->mDeviceType, mix->mDeviceAddress);
842 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Scott Randolph7b1fd232018-06-18 15:33:03 -0700843 ALOGV("getOutputForAttr() returns output %d", *output);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700844 goto exit;
Scott Randolph7b1fd232018-06-18 15:33:03 -0700845 }
846
847 // Virtual sources must always be dynamicaly or explicitly routed
848 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
849 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
850 return BAD_VALUE;
851 }
Eric Laurent97ac8712018-07-27 18:59:02 -0700852 device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700853 }
Scott Randolph7b1fd232018-06-18 15:33:03 -0700854
Eric Laurente83b55d2014-11-14 10:06:21 -0800855 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200856 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -0700857 }
858
Nadav Barb2f18162018-07-18 13:01:53 +0300859 // Set incall music only if device was explicitly set, and fallback to the device which is
860 // chosen by the engine if not.
861 // FIXME: provide a more generic approach which is not device specific and move this back
862 // to getOutputForDevice.
863 if (device == AUDIO_DEVICE_OUT_TELEPHONY_TX &&
864 *stream == AUDIO_STREAM_MUSIC &&
865 audio_is_linear_pcm(config->format) &&
866 isInCall()) {
Eric Laurent97ac8712018-07-27 18:59:02 -0700867 if (requestedDeviceId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +0300868 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
869 } else {
Eric Laurent97ac8712018-07-27 18:59:02 -0700870 // Get the devce type directly from the engine to bypass preferred route logic
Nadav Barb2f18162018-07-18 13:01:53 +0300871 device = mEngine->getDeviceForStrategy(strategy);
872 }
873 }
874
Glenn Kasten49f36ba2017-12-06 13:02:02 -0800875 ALOGV("getOutputForAttr() device 0x%x, sampling rate %d, format %#x, channel mask %#x, "
876 "flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +0200877 device, config->sample_rate, config->format, config->channel_mask, *flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700878
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100879 *output = AUDIO_IO_HANDLE_NONE;
880 if (msdDevice != AUDIO_DEVICE_NONE) {
881 *output = getOutputForDevice(msdDevice, session, *stream, config, flags);
882 if (*output != AUDIO_IO_HANDLE_NONE && setMsdPatch(device) == NO_ERROR) {
883 ALOGV("%s() Using MSD device 0x%x instead of device 0x%x",
884 __func__, msdDevice, device);
885 device = msdDevice;
886 } else {
887 *output = AUDIO_IO_HANDLE_NONE;
888 }
889 }
890 if (*output == AUDIO_IO_HANDLE_NONE) {
891 *output = getOutputForDevice(device, session, *stream, config, flags);
892 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800893 if (*output == AUDIO_IO_HANDLE_NONE) {
894 return INVALID_OPERATION;
895 }
Paul McLeanaa981192015-03-21 09:55:15 -0700896
Eric Laurent8fc147b2018-07-22 19:13:55 -0700897 outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -0700898 *selectedDeviceId = outputDevices.size() > 0 ? outputDevices.itemAt(0)->getId()
899 : AUDIO_PORT_HANDLE_NONE;
900
Eric Laurent8fc147b2018-07-22 19:13:55 -0700901exit:
902 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
903 .format = config->format,
904 .channel_mask = config->channel_mask };
905 sp<TrackClientDescriptor> clientDesc =
Eric Laurent97ac8712018-07-27 18:59:02 -0700906 new TrackClientDescriptor(*portId, uid, session, attributes, clientConfig,
907 requestedDeviceId, *stream,
908 getStrategyForAttr(&attributes),
909 *flags);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700910 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent97ac8712018-07-27 18:59:02 -0700911 outputDesc->clientsMap().emplace(*portId, clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700912
913 ALOGV(" getOutputForAttr() returns output %d selectedDeviceId %d for port ID %d",
914 *output, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -0700915
Eric Laurente83b55d2014-11-14 10:06:21 -0800916 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700917}
918
919audio_io_handle_t AudioPolicyManager::getOutputForDevice(
920 audio_devices_t device,
Kevin Rocard169753c2017-03-06 14:18:23 -0800921 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700922 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -0800923 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200924 audio_output_flags_t *flags)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700925{
Andy Hungc88b0642018-04-27 15:42:35 -0700926 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700927 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700928
Eric Laurente552edb2014-03-10 17:42:56 -0700929 // open a direct output if required by specified parameters
930 //force direct flag if offload flag is set: offloading implies a direct output stream
931 // and all common behaviors are driven by checking only the direct flag
932 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +0200933 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
934 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700935 }
Nadav Bar766fb022018-01-07 12:18:03 +0200936 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
937 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -0700938 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800939 // only allow deep buffering for music stream type
940 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +0200941 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700942 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +0200943 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700944 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
945 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +0200946 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800947 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700948 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +0200949 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700950 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Eric Laurentfe231122017-11-17 17:48:06 -0800951 audio_is_linear_pcm(config->format)) {
Nadav Bar766fb022018-01-07 12:18:03 +0200952 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700953 AUDIO_OUTPUT_FLAG_DIRECT);
954 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700955 }
Eric Laurente552edb2014-03-10 17:42:56 -0700956
Nadav Bar766fb022018-01-07 12:18:03 +0200957
Eric Laurentb732cf52014-09-24 19:08:21 -0700958 sp<IOProfile> profile;
959
960 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700961 // and not explicitly requested
Nadav Bar766fb022018-01-07 12:18:03 +0200962 if (((*flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Eric Laurentfe231122017-11-17 17:48:06 -0800963 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
964 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
Eric Laurentb732cf52014-09-24 19:08:21 -0700965 goto non_direct_output;
966 }
967
Andy Hung2ddee192015-12-18 17:34:44 -0800968 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
969 // This prevents creating an offloaded track and tearing it down immediately after start
970 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700971 // FIXME: We should check the audio session here but we do not have it in this context.
972 // This may prevent offloading in rare situations where effects are left active by apps
973 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700974
Nadav Bar766fb022018-01-07 12:18:03 +0200975 if (((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800976 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700977 profile = getProfileForDirectOutput(device,
Eric Laurentfe231122017-11-17 17:48:06 -0800978 config->sample_rate,
979 config->format,
980 config->channel_mask,
Nadav Bar766fb022018-01-07 12:18:03 +0200981 (audio_output_flags_t)*flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700982 }
983
Eric Laurent1c333e22014-05-20 10:48:17 -0700984 if (profile != 0) {
Andy Hungc88b0642018-04-27 15:42:35 -0700985 // exclusive outputs for MMAP and Offload are enforced by different session ids.
986 for (size_t i = 0; i < mOutputs.size(); i++) {
987 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
988 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
989 // reuse direct output if currently open by the same client
990 // and configured with same parameters
991 if ((config->sample_rate == desc->mSamplingRate) &&
Andy Hung5659ed52018-04-30 10:31:26 -0700992 (config->format == desc->mFormat) &&
Andy Hungc88b0642018-04-27 15:42:35 -0700993 (config->channel_mask == desc->mChannelMask) &&
994 (session == desc->mDirectClientSession)) {
995 desc->mDirectOpenCount++;
996 ALOGI("getOutputForDevice() reusing direct output %d for session %d",
997 mOutputs.keyAt(i), session);
998 return mOutputs.keyAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700999 }
1000 }
1001 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08001002
1003 if (!profile->canOpenNewIo()) {
1004 goto non_direct_output;
Eric Laurente552edb2014-03-10 17:42:56 -07001005 }
Eric Laurent861a6282015-05-18 15:40:16 -07001006
Eric Laurent3974e3b2017-12-07 17:58:43 -08001007 sp<SwAudioOutputDescriptor> outputDesc =
1008 new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurent53b810e2017-12-10 17:25:10 -08001009
Mikhail Naganov708e0382018-05-30 09:53:04 -07001010 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -08001011 String8 address = outputDevices.size() > 0 ? outputDevices.itemAt(0)->mAddress
1012 : String8("");
1013
Nadav Bar766fb022018-01-07 12:18:03 +02001014 status = outputDesc->open(config, device, address, stream, *flags, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07001015
1016 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001017 if (status != NO_ERROR ||
Eric Laurentfe231122017-11-17 17:48:06 -08001018 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
Andy Hung5659ed52018-04-30 10:31:26 -07001019 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->mFormat) ||
Eric Laurentfe231122017-11-17 17:48:06 -08001020 (config->channel_mask != 0 && config->channel_mask != outputDesc->mChannelMask)) {
1021 ALOGV("getOutputForDevice() failed opening direct output: output %d sample rate %d %d,"
1022 "format %d %d, channel mask %04x %04x", output, config->sample_rate,
1023 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
1024 config->channel_mask, outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001025 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001026 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07001027 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001028 // fall back to mixer output if possible when the direct output could not be open
Eric Laurentfe231122017-11-17 17:48:06 -08001029 if (audio_is_linear_pcm(config->format) &&
1030 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -08001031 goto non_direct_output;
1032 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001033 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001034 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001035 outputDesc->mRefCount[stream] = 0;
1036 outputDesc->mStopTime[stream] = 0;
1037 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -08001038 outputDesc->mDirectClientSession = session;
1039
Eric Laurente552edb2014-03-10 17:42:56 -07001040 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001041 mPreviousOutputs = mOutputs;
Eric Laurentf4e63452017-11-06 19:31:46 +00001042 ALOGV("getOutputForDevice() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001043 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001044 return output;
1045 }
1046
Eric Laurentb732cf52014-09-24 19:08:21 -07001047non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001048
1049 // A request for HW A/V sync cannot fallback to a mixed output because time
1050 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001051 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001052 return AUDIO_IO_HANDLE_NONE;
1053 }
1054
Eric Laurente552edb2014-03-10 17:42:56 -07001055 // ignoring channel mask due to downmix capability in mixer
1056
1057 // open a non direct output
1058
1059 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001060 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001061 // get which output is suitable for the specified stream. The actual
1062 // routing change will happen when startOutput() will be called
1063 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1064
Eric Laurent8838a382014-09-08 16:44:28 -07001065 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001066 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1067 output = selectOutput(outputs, *flags, config->format);
Eric Laurente552edb2014-03-10 17:42:56 -07001068 }
Eric Laurentf4e63452017-11-06 19:31:46 +00001069 ALOGW_IF((output == 0), "getOutputForDevice() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001070 "sampling rate %d, format %#x, channels %#x, flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +02001071 stream, config->sample_rate, config->format, config->channel_mask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001072
Eric Laurente552edb2014-03-10 17:42:56 -07001073 return output;
1074}
1075
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001076sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
1077 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1078 if (msdModule != 0) {
1079 DeviceVector msdInputDevices = mAvailableInputDevices.getDevicesFromHwModule(
1080 msdModule->getHandle());
1081 if (!msdInputDevices.isEmpty()) return msdInputDevices.itemAt(0);
1082 }
1083 return 0;
1084}
1085
1086audio_devices_t AudioPolicyManager::getMsdAudioOutDeviceTypes() const {
1087 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1088 if (msdModule != 0) {
1089 return mAvailableOutputDevices.getDeviceTypesFromHwModule(msdModule->getHandle());
1090 }
1091 return AUDIO_DEVICE_NONE;
1092}
1093
1094const AudioPatchCollection AudioPolicyManager::getMsdPatches() const {
1095 AudioPatchCollection msdPatches;
1096 audio_module_handle_t msdModuleHandle = mHwModules.getModuleFromName(
1097 AUDIO_HARDWARE_MODULE_ID_MSD)->getHandle();
1098 if (msdModuleHandle == AUDIO_MODULE_HANDLE_NONE) return msdPatches;
1099 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1100 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1101 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1102 const struct audio_port_config *source = &patch->mPatch.sources[j];
1103 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1104 source->ext.device.hw_module == msdModuleHandle) {
1105 msdPatches.addAudioPatch(patch->mHandle, patch);
1106 }
1107 }
1108 }
1109 return msdPatches;
1110}
1111
1112status_t AudioPolicyManager::getBestMsdAudioProfileFor(audio_devices_t outputDevice,
1113 bool hwAvSync, audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1114{
1115 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1116 if (msdModule == nullptr) {
1117 ALOGE("%s() unable to get MSD module", __func__);
1118 return NO_INIT;
1119 }
1120 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(outputDevice);
1121 if (deviceModule == nullptr) {
1122 ALOGE("%s() unable to get module for %#x", __func__, outputDevice);
1123 return NO_INIT;
1124 }
1125 const InputProfileCollection &inputProfiles = msdModule->getInputProfiles();
1126 if (inputProfiles.isEmpty()) {
1127 ALOGE("%s() no input profiles for MSD module", __func__);
1128 return NO_INIT;
1129 }
1130 const OutputProfileCollection &outputProfiles = deviceModule->getOutputProfiles();
1131 if (outputProfiles.isEmpty()) {
1132 ALOGE("%s() no output profiles for device %#x", __func__, outputDevice);
1133 return NO_INIT;
1134 }
1135 AudioProfileVector msdProfiles;
1136 // Each IOProfile represents a MixPort from audio_policy_configuration.xml
1137 for (const auto &inProfile : inputProfiles) {
1138 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0)) {
1139 msdProfiles.appendVector(inProfile->getAudioProfiles());
1140 }
1141 }
1142 AudioProfileVector deviceProfiles;
1143 for (const auto &outProfile : outputProfiles) {
1144 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0)) {
1145 deviceProfiles.appendVector(outProfile->getAudioProfiles());
1146 }
1147 }
1148 struct audio_config_base bestSinkConfig;
1149 status_t result = msdProfiles.findBestMatchingOutputConfig(deviceProfiles,
1150 compressedFormatsOrder, surroundChannelMasksOrder, true /*preferHigherSamplingRates*/,
1151 &bestSinkConfig);
1152 if (result != NO_ERROR) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001153 ALOGD("%s() no matching profiles found for device: %#x, hwAvSync: %d",
1154 __func__, outputDevice, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001155 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001156 }
1157 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1158 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1159 sinkConfig->format = bestSinkConfig.format;
1160 // For encoded streams force direct flag to prevent downstream mixing.
1161 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1162 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
1163 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1164 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1165 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1166 sourceConfig->format = bestSinkConfig.format;
1167 // Copy input stream directly without any processing (e.g. resampling).
1168 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1169 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1170 if (hwAvSync) {
1171 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1172 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1173 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1174 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1175 }
1176 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1177 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1178 sinkConfig->config_mask |= config_mask;
1179 sourceConfig->config_mask |= config_mask;
1180 return NO_ERROR;
1181}
1182
1183PatchBuilder AudioPolicyManager::buildMsdPatch(audio_devices_t outputDevice) const
1184{
1185 PatchBuilder patchBuilder;
1186 patchBuilder.addSource(getMsdAudioInDevice()).
1187 addSink(findDevice(mAvailableOutputDevices, outputDevice));
1188 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1189 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
1190 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1191 // For now, we just forcefully try with HwAvSync first.
1192 status_t res = getBestMsdAudioProfileFor(outputDevice, true /*hwAvSync*/,
1193 &sourceConfig, &sinkConfig) == NO_ERROR ? NO_ERROR :
1194 getBestMsdAudioProfileFor(
1195 outputDevice, false /*hwAvSync*/, &sourceConfig, &sinkConfig);
1196 if (res == NO_ERROR) {
1197 // Found a matching profile for encoded audio. Re-create PatchBuilder with this config.
1198 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1199 }
1200 ALOGV("%s() no matching profile found. Fall through to default PCM patch"
1201 " supporting PCM format conversion.", __func__);
1202 return patchBuilder;
1203}
1204
1205status_t AudioPolicyManager::setMsdPatch(audio_devices_t outputDevice) {
1206 ALOGV("%s() for outputDevice %#x", __func__, outputDevice);
1207 if (outputDevice == AUDIO_DEVICE_NONE) {
1208 // Use media strategy for unspecified output device. This should only
1209 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1210 // therefore invalidate explicit routing requests.
1211 outputDevice = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
1212 }
1213 PatchBuilder patchBuilder = buildMsdPatch(outputDevice);
1214 const struct audio_patch* patch = patchBuilder.patch();
1215 const AudioPatchCollection msdPatches = getMsdPatches();
1216 if (!msdPatches.isEmpty()) {
1217 LOG_ALWAYS_FATAL_IF(msdPatches.size() > 1,
1218 "The current MSD prototype only supports one output patch");
1219 sp<AudioPatch> currentPatch = msdPatches.valueAt(0);
1220 if (audio_patches_are_equal(&currentPatch->mPatch, patch)) {
1221 return NO_ERROR;
1222 }
1223 releaseAudioPatch(currentPatch->mHandle, mUidCached);
1224 }
1225 status_t status = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1226 patch, 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1227 ALOGE_IF(status != NO_ERROR, "%s() error %d creating MSD audio patch", __func__, status);
1228 ALOGI_IF(status == NO_ERROR, "%s() Patch created from MSD_IN to "
1229 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__, outputDevice,
1230 patch->sources[0].format, patch->sources[0].channel_mask, patch->sources[0].sample_rate);
1231 return status;
1232}
1233
Eric Laurente0720872014-03-11 09:30:41 -07001234audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001235 audio_output_flags_t flags,
1236 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001237{
1238 // select one output among several that provide a path to a particular device or set of
1239 // devices (the list was previously build by getOutputsForDevice()).
1240 // The priority is as follows:
1241 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001242 // 2: the output with the bit depth the closest to the requested one
1243 // 3: the primary output
1244 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001245
1246 if (outputs.size() == 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001247 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001248 }
1249 if (outputs.size() == 1) {
1250 return outputs[0];
1251 }
1252
1253 int maxCommonFlags = 0;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001254 audio_io_handle_t outputForFlags = AUDIO_IO_HANDLE_NONE;
1255 audio_io_handle_t outputForPrimary = AUDIO_IO_HANDLE_NONE;
1256 audio_io_handle_t outputForFormat = AUDIO_IO_HANDLE_NONE;
Eric Laurente6930022016-02-11 10:20:40 -08001257 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1258 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001259
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001260 for (audio_io_handle_t output : outputs) {
1261 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001262 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001263 // if a valid format is specified, skip output if not compatible
1264 if (format != AUDIO_FORMAT_INVALID) {
1265 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Andy Hung5659ed52018-04-30 10:31:26 -07001266 if (format != outputDesc->mFormat) {
Eric Laurent8838a382014-09-08 16:44:28 -07001267 continue;
1268 }
1269 } else if (!audio_is_linear_pcm(format)) {
1270 continue;
1271 }
Eric Laurente6930022016-02-11 10:20:40 -08001272 if (AudioPort::isBetterFormatMatch(
1273 outputDesc->mFormat, bestFormat, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001274 outputForFormat = output;
Eric Laurente6930022016-02-11 10:20:40 -08001275 bestFormat = outputDesc->mFormat;
1276 }
Eric Laurent8838a382014-09-08 16:44:28 -07001277 }
1278
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001279 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001280 if (commonFlags >= maxCommonFlags) {
1281 if (commonFlags == maxCommonFlags) {
Andy Hungc9901522017-11-10 20:07:54 -08001282 if (format != AUDIO_FORMAT_INVALID
1283 && AudioPort::isBetterFormatMatch(
1284 outputDesc->mFormat, bestFormatForFlags, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001285 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001286 bestFormatForFlags = outputDesc->mFormat;
1287 }
1288 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001289 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001290 maxCommonFlags = commonFlags;
1291 bestFormatForFlags = outputDesc->mFormat;
1292 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001293 ALOGV("selectOutput() commonFlags for output %d, %04x", output, commonFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001294 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001295 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001296 outputForPrimary = output;
Eric Laurente552edb2014-03-10 17:42:56 -07001297 }
1298 }
1299 }
1300
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001301 if (outputForFlags != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001302 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001303 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001304 if (outputForFormat != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001305 return outputForFormat;
1306 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001307 if (outputForPrimary != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001308 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001309 }
1310
1311 return outputs[0];
1312}
1313
Eric Laurent8fc147b2018-07-22 19:13:55 -07001314status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001315{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001316 ALOGV("%s portId %d", __FUNCTION__, portId);
1317
1318 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1319 if (outputDesc == 0) {
1320 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001321 return BAD_VALUE;
1322 }
Eric Laurent97ac8712018-07-27 18:59:02 -07001323 sp<TrackClientDescriptor> client = outputDesc->clientsMap()[portId];
Eric Laurente552edb2014-03-10 17:42:56 -07001324
Eric Laurent8fc147b2018-07-22 19:13:55 -07001325 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001326 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001327
Eric Laurent733ce942017-12-07 12:18:25 -08001328 status_t status = outputDesc->start();
1329 if (status != NO_ERROR) {
1330 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001331 }
1332
Eric Laurent97ac8712018-07-27 18:59:02 -07001333 uint32_t delayMs;
1334 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001335
1336 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001337 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001338 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001339 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001340 if (delayMs != 0) {
1341 usleep(delayMs * 1000);
1342 }
1343
1344 return status;
1345}
1346
Eric Laurent97ac8712018-07-27 18:59:02 -07001347status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1348 const sp<TrackClientDescriptor>& client,
1349 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001350{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001351 // cannot start playback of STREAM_TTS if any other output is being used
1352 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001353
1354 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001355 audio_stream_type_t stream = client->stream();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001356 if (stream == AUDIO_STREAM_TTS) {
1357 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001358 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001359 return INVALID_OPERATION;
1360 } else {
1361 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1362 }
1363 } else {
1364 // some playback other than beacon starts
1365 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1366 }
1367
Eric Laurent77305a62016-07-25 16:39:22 -07001368 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001369 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001370 bool force = !outputDesc->isActive() &&
1371 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001372
Eric Laurent97ac8712018-07-27 18:59:02 -07001373 audio_devices_t device = AUDIO_DEVICE_NONE;
1374 AudioMix *policyMix = NULL;
1375 const char *address = NULL;
1376 if (outputDesc->mPolicyMix != NULL) {
1377 policyMix = outputDesc->mPolicyMix;
1378 address = policyMix->mDeviceAddress.string();
1379 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1380 device = policyMix->mDeviceType;
1381 } else {
1382 device = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1383 }
1384 }
1385
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001386 // requiresMuteCheck is false when we can bypass mute strategy.
1387 // It covers a common case when there is no materially active audio
1388 // and muting would result in unnecessary delay and dropped audio.
1389 const uint32_t outputLatencyMs = outputDesc->latency();
1390 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1391
Eric Laurente552edb2014-03-10 17:42:56 -07001392 // increment usage count for this stream on the requested output:
1393 // NOTE that the usage count is the same for duplicated output and hardware output which is
1394 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1395 outputDesc->changeRefCount(stream, 1);
Eric Laurent97ac8712018-07-27 18:59:02 -07001396 client->setActive(true);
1397
1398 if (client->hasPreferredDevice(true)) {
1399 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
1400 if (device != outputDesc->device()) {
1401 checkStrategyRoute(getStrategy(stream), outputDesc->mIoHandle);
1402 }
1403 }
Eric Laurente552edb2014-03-10 17:42:56 -07001404
Eric Laurent36829f92017-04-07 19:04:42 -07001405 if (stream == AUDIO_STREAM_MUSIC) {
1406 selectOutputForMusicEffects();
1407 }
1408
Eric Laurent493404d2015-04-21 15:07:36 -07001409 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001410 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001411 if (device == AUDIO_DEVICE_NONE) {
1412 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001413 }
Eric Laurent36829f92017-04-07 19:04:42 -07001414
Eric Laurente552edb2014-03-10 17:42:56 -07001415 routing_strategy strategy = getStrategy(stream);
1416 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001417 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1418 (beaconMuteLatency > 0);
1419 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001420 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001421 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001422 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001423 // An output has a shared device if
1424 // - managed by the same hw module
1425 // - supports the currently selected device
1426 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
1427 && (desc->supportedDevices() & device) != AUDIO_DEVICE_NONE;
1428
Eric Laurent77305a62016-07-25 16:39:22 -07001429 // force a device change if any other output is:
1430 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001431 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001432 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001433 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001434 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001435 // change the device currently selected by the other output.
1436 if (sharedDevice &&
Eric Laurent77305a62016-07-25 16:39:22 -07001437 desc->device() != device &&
Eric Laurent77305a62016-07-25 16:39:22 -07001438 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001439 force = true;
1440 }
1441 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001442 // a notification so that audio focus effect can propagate, or that a mute/unmute
1443 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001444 const uint32_t latencyMs = desc->latency();
1445 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1446
1447 if (shouldWait && isActive && (waitMs < latencyMs)) {
1448 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001449 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001450
1451 // Require mute check if another output is on a shared device
1452 // and currently active to have proper drain and avoid pops.
1453 // Note restoring AudioTracks onto this output needs to invoke
1454 // a volume ramp if there is no mute.
1455 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001456 }
1457 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001458
1459 const uint32_t muteWaitMs =
1460 setOutputDevice(outputDesc, device, force, 0, NULL, address, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001461
Eric Laurente552edb2014-03-10 17:42:56 -07001462 // apply volume rules for current stream and device if necessary
1463 checkAndSetVolume(stream,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001464 mVolumeCurves->getVolumeIndex(stream, outputDesc->device()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001465 outputDesc,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001466 outputDesc->device());
Eric Laurente552edb2014-03-10 17:42:56 -07001467
1468 // update the outputs if starting an output with a stream that can affect notification
1469 // routing
1470 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001471
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001472 // force reevaluating accessibility routing when ringtone or alarm starts
1473 if (strategy == STRATEGY_SONIFICATION) {
1474 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1475 }
Eric Laurentdc462862016-07-19 12:29:53 -07001476
1477 if (waitMs > muteWaitMs) {
1478 *delayMs = waitMs - muteWaitMs;
1479 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001480
1481 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1482 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1483 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1484 // change occurs after the MixerThread starts and causes a stream volume
1485 // glitch.
1486 //
1487 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001488 }
Eric Laurentdc462862016-07-19 12:29:53 -07001489
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001490 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1491 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1492 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1493 }
1494
Eric Laurent97ac8712018-07-27 18:59:02 -07001495 // Automatically enable the remote submix input when output is started on a re routing mix
1496 // of type MIX_TYPE_RECORDERS
1497 if (audio_is_remote_submix_device(device) && policyMix != NULL &&
1498 policyMix->mMixType == MIX_TYPE_RECORDERS) {
1499 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1500 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1501 address,
1502 "remote-submix");
1503 }
1504
Eric Laurente552edb2014-03-10 17:42:56 -07001505 return NO_ERROR;
1506}
1507
Eric Laurent8fc147b2018-07-22 19:13:55 -07001508status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001509{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001510 ALOGV("%s portId %d", __FUNCTION__, portId);
1511
1512 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1513 if (outputDesc == 0) {
1514 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001515 return BAD_VALUE;
1516 }
Eric Laurent97ac8712018-07-27 18:59:02 -07001517 sp<TrackClientDescriptor> client = outputDesc->clientsMap()[portId];
Eric Laurente552edb2014-03-10 17:42:56 -07001518
Eric Laurent97ac8712018-07-27 18:59:02 -07001519 ALOGV("stopOutput() output %d, stream %d, session %d",
1520 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07001521
Eric Laurent97ac8712018-07-27 18:59:02 -07001522 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08001523
Eric Laurent733ce942017-12-07 12:18:25 -08001524 if (status == NO_ERROR ) {
1525 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001526 }
1527 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001528}
1529
Eric Laurent97ac8712018-07-27 18:59:02 -07001530status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1531 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07001532{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001533 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07001534 audio_stream_type_t stream = client->stream();
1535
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001536 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1537
Eric Laurente552edb2014-03-10 17:42:56 -07001538 if (outputDesc->mRefCount[stream] > 0) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001539 if (outputDesc->mRefCount[stream] == 1) {
1540 // Automatically disable the remote submix input when output is stopped on a
1541 // re routing mix of type MIX_TYPE_RECORDERS
1542 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1543 outputDesc->mPolicyMix != NULL &&
1544 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1545 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1546 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1547 outputDesc->mPolicyMix->mDeviceAddress,
1548 "remote-submix");
1549 }
1550 }
1551 bool forceDeviceUpdate = false;
1552 if (client->hasPreferredDevice(true)) {
1553 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1554 forceDeviceUpdate = true;
1555 }
1556
Eric Laurente552edb2014-03-10 17:42:56 -07001557 // decrement usage count of this stream on the output
1558 outputDesc->changeRefCount(stream, -1);
Eric Laurent97ac8712018-07-27 18:59:02 -07001559 client->setActive(false);
Paul McLeanaa981192015-03-21 09:55:15 -07001560
Eric Laurente552edb2014-03-10 17:42:56 -07001561 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001562 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001563 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001564 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001565 // delay the device switch by twice the latency because stopOutput() is executed when
1566 // the track stop() command is received and at that time the audio track buffer can
1567 // still contain data that needs to be drained. The latency only covers the audio HAL
1568 // and kernel buffers. Also the latency does not always include additional delay in the
1569 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001570 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001571
1572 // force restoring the device selection on other active outputs if it differs from the
1573 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001574 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001575 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001576 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001577 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001578 desc->isActive() &&
1579 outputDesc->sharesHwModuleWith(desc) &&
1580 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001581 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1582 bool force = desc->device() != newDevice2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001583
Eric Laurentc75307b2015-03-17 15:29:32 -07001584 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001585 newDevice2,
1586 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001587 delayMs);
1588 // re-apply device specific volume if not done by setOutputDevice()
1589 if (!force) {
1590 applyStreamVolumes(desc, newDevice2, delayMs);
1591 }
Eric Laurente552edb2014-03-10 17:42:56 -07001592 }
1593 }
1594 // update the outputs if stopping one with a stream that can affect notification routing
1595 handleNotificationRoutingForStream(stream);
1596 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001597
1598 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1599 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1600 setStrategyMute(STRATEGY_SONIFICATION, false, outputDesc);
1601 }
1602
Eric Laurent36829f92017-04-07 19:04:42 -07001603 if (stream == AUDIO_STREAM_MUSIC) {
1604 selectOutputForMusicEffects();
1605 }
Eric Laurente552edb2014-03-10 17:42:56 -07001606 return NO_ERROR;
1607 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001608 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001609 return INVALID_OPERATION;
1610 }
1611}
1612
Eric Laurent8fc147b2018-07-22 19:13:55 -07001613void AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001614{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001615 ALOGV("%s portId %d", __FUNCTION__, portId);
1616
1617 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1618 if (outputDesc == 0) {
1619 ALOGW("releaseOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001620 return;
1621 }
Eric Laurent97ac8712018-07-27 18:59:02 -07001622 sp<TrackClientDescriptor> client = outputDesc->clientsMap()[portId];
Eric Laurent8fc147b2018-07-22 19:13:55 -07001623
1624 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001625
Eric Laurent8fc147b2018-07-22 19:13:55 -07001626 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1627 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001628 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07001629 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001630 return;
1631 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001632 if (--outputDesc->mDirectOpenCount == 0) {
1633 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07001634 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001635 }
1636 }
Eric Laurent97ac8712018-07-27 18:59:02 -07001637 outputDesc->clientsMap().erase(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001638}
1639
1640
Eric Laurentcaf7f482014-11-25 17:50:47 -08001641status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1642 audio_io_handle_t *input,
1643 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001644 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001645 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001646 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001647 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001648 input_type_t *inputType,
1649 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001650{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001651 ALOGV("getInputForAttr() source %d, sampling rate %d, format %#x, channel mask %#x,"
Eric Laurentcaf7f482014-11-25 17:50:47 -08001652 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001653 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001654
Eric Laurentad2e7b92017-09-14 20:06:42 -07001655 status_t status = NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -08001656 // handle legacy remote submix case where the address was not always specified
1657 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001658 audio_source_t halInputSource;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001659 audio_source_t inputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001660 AudioMix *policyMix = NULL;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001661 DeviceVector inputDevices;
Eric Laurent8fc147b2018-07-22 19:13:55 -07001662 sp<AudioInputDescriptor> inputDesc;
1663 sp<RecordClientDescriptor> clientDesc;
1664 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Eric Laurent20b9ef02016-12-05 11:03:16 -08001665
Eric Laurentfe231122017-11-17 17:48:06 -08001666 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1667 inputSource = AUDIO_SOURCE_MIC;
1668 }
1669
Paul McLean466dc8e2015-04-17 13:15:36 -06001670 // Explicit routing?
1671 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -07001672 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
jiabinc0c831a2018-01-29 17:55:15 -08001673 deviceDesc = mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001674 }
Paul McLean466dc8e2015-04-17 13:15:36 -06001675
Eric Laurentad2e7b92017-09-14 20:06:42 -07001676 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1677 // possible
1678 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1679 *input != AUDIO_IO_HANDLE_NONE) {
1680 ssize_t index = mInputs.indexOfKey(*input);
1681 if (index < 0) {
1682 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1683 status = BAD_VALUE;
1684 goto error;
1685 }
1686 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1687 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1688 if (audioSession == 0) {
1689 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1690 status = BAD_VALUE;
1691 goto error;
1692 }
1693 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1694 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001695 // corresponds to a new client and is only permitted from the same UID.
1696 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurentad2e7b92017-09-14 20:06:42 -07001697 if (audioSession->openCount() == 1) {
1698 audioSession->setUid(uid);
1699 } else if (audioSession->uid() != uid) {
Eric Laurent331679c2018-04-16 17:03:16 -07001700 if (!audioSession->isSilenced()) {
1701 ALOGW("getInputForAttr() bad uid %d for session %d uid %d",
1702 uid, session, audioSession->uid());
1703 status = INVALID_OPERATION;
1704 goto error;
1705 }
1706 audioSession->setUid(uid);
1707 audioSession->setSilenced(false);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001708 }
1709 audioSession->changeOpenCount(1);
1710 *inputType = API_INPUT_LEGACY;
1711 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1712 *portId = AudioPort::getNextUniqueId();
1713 }
Mikhail Naganov708e0382018-05-30 09:53:04 -07001714 inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(inputDesc->mDevice);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001715 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1716 : AUDIO_PORT_HANDLE_NONE;
1717 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
1718
Eric Laurent8fc147b2018-07-22 19:13:55 -07001719 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001720 }
1721
1722 *input = AUDIO_IO_HANDLE_NONE;
1723 *inputType = API_INPUT_INVALID;
1724
Eric Laurentad2e7b92017-09-14 20:06:42 -07001725 halInputSource = inputSource;
1726
1727 // TODO: check for existing client for this port ID
1728 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1729 *portId = AudioPort::getNextUniqueId();
1730 }
1731
1732 audio_devices_t device;
1733
Eric Laurentc447ded2015-01-06 08:47:05 -08001734 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001735 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001736 status = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
1737 if (status != NO_ERROR) {
1738 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001739 }
1740 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001741 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1742 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001743 } else {
Eric Laurent97ac8712018-07-27 18:59:02 -07001744 if (deviceDesc != 0) {
1745 device = deviceDesc->type();
1746 } else {
1747 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
1748 }
Eric Laurent275e8e92014-11-30 15:14:47 -08001749 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001750 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001751 status = BAD_VALUE;
1752 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001753 }
Eric Laurentc722f302014-12-10 11:21:49 -08001754 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001755 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001756 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1757 // there is an external policy, but this input is attached to a mix of recorders,
1758 // meaning it receives audio injected into the framework, so the recorder doesn't
1759 // know about it and is therefore considered "legacy"
1760 *inputType = API_INPUT_LEGACY;
1761 } else {
1762 // recording a mix of players defined by an external policy, we're rerouting for
1763 // an external policy
1764 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1765 }
Eric Laurentc722f302014-12-10 11:21:49 -08001766 } else if (audio_is_remote_submix_device(device)) {
1767 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001768 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001769 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1770 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001771 } else {
1772 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001773 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001774
Eric Laurent599c7582015-12-07 18:05:55 -08001775 }
1776
1777 *input = getInputForDevice(device, address, session, uid, inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001778 config, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001779 policyMix);
1780 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001781 status = INVALID_OPERATION;
1782 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001783 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001784
Mikhail Naganov708e0382018-05-30 09:53:04 -07001785 inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -07001786 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1787 : AUDIO_PORT_HANDLE_NONE;
1788
Eric Laurent8fc147b2018-07-22 19:13:55 -07001789exit:
1790 clientDesc = new RecordClientDescriptor(*portId, uid, session,
1791 *attr, *config, requestedDeviceId, inputSource, flags);
1792 inputDesc = mInputs.valueFor(*input);
Eric Laurent97ac8712018-07-27 18:59:02 -07001793 inputDesc->clientsMap().emplace(*portId, clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001794
1795 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
1796 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001797
Eric Laurent599c7582015-12-07 18:05:55 -08001798 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001799
1800error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07001801 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001802}
1803
1804
1805audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1806 String8 address,
1807 audio_session_t session,
1808 uid_t uid,
1809 audio_source_t inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001810 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08001811 audio_input_flags_t flags,
1812 AudioMix *policyMix)
1813{
1814 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1815 audio_source_t halInputSource = inputSource;
1816 bool isSoundTrigger = false;
1817
1818 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1819 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1820 if (index >= 0) {
1821 input = mSoundTriggerSessions.valueFor(session);
1822 isSoundTrigger = true;
1823 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1824 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1825 } else {
1826 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001827 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001828 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08001829 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001830 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001831 }
1832
Andy Hungf129b032015-04-07 13:45:50 -07001833 // find a compatible input profile (not necessarily identical in parameters)
1834 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08001835 // sampling rate and flags may be updated by getInputProfile
1836 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
1837 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07001838 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08001839 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07001840 audio_input_flags_t profileFlags = flags;
1841 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07001842 profileFormat = config->format; // reset each time through loop, in case it is updated
Eric Laurent275e8e92014-11-30 15:14:47 -08001843 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001844 profileSamplingRate, profileFormat, profileChannelMask,
1845 profileFlags);
1846 if (profile != 0) {
1847 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001848 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1849 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001850 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1851 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1852 } else { // fail
Glenn Kastenfaa10a62017-05-25 15:52:05 -07001853 ALOGW("getInputForDevice() could not find profile for device 0x%X, "
Eric Laurentfe231122017-11-17 17:48:06 -08001854 "sampling rate %u, format %#x, channel mask 0x%X, flags %#x",
1855 device, config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001856 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001857 }
Eric Laurente552edb2014-03-10 17:42:56 -07001858 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001859 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08001860 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08001861 if (samplingRate == 0) {
1862 samplingRate = profileSamplingRate;
1863 }
Eric Laurente552edb2014-03-10 17:42:56 -07001864
Eric Laurent322b4d22015-04-03 15:57:54 -07001865 if (profile->getModuleHandle() == 0) {
1866 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001867 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001868 }
1869
Eric Laurent599c7582015-12-07 18:05:55 -08001870 sp<AudioSession> audioSession = new AudioSession(session,
Eric Laurentfe231122017-11-17 17:48:06 -08001871 inputSource,
1872 config->format,
1873 samplingRate,
1874 config->channel_mask,
1875 flags,
1876 uid,
Eric Laurenta18dced2018-07-20 15:14:54 -07001877 isSoundTrigger);
Eric Laurent599c7582015-12-07 18:05:55 -08001878
Eric Laurent3974e3b2017-12-07 17:58:43 -08001879 if (!profile->canOpenNewIo()) {
1880 return AUDIO_IO_HANDLE_NONE;
1881 }
1882
Eric Laurentfe231122017-11-17 17:48:06 -08001883 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001884
Eric Laurentfe231122017-11-17 17:48:06 -08001885 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
1886 lConfig.sample_rate = profileSamplingRate;
1887 lConfig.channel_mask = profileChannelMask;
1888 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07001889
Eric Laurent53b810e2017-12-10 17:25:10 -08001890 if (address == "") {
Mikhail Naganov708e0382018-05-30 09:53:04 -07001891 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -08001892 // the inputs vector must be of size >= 1, but we don't want to crash here
1893 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress : String8("");
1894 }
1895
Eric Laurentfe231122017-11-17 17:48:06 -08001896 status_t status = inputDesc->open(&lConfig, device, address,
1897 halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001898
1899 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001900 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08001901 (profileSamplingRate != lConfig.sample_rate) ||
1902 !audio_formats_match(profileFormat, lConfig.format) ||
1903 (profileChannelMask != lConfig.channel_mask)) {
1904 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001905 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08001906 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001907 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001908 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07001909 }
Eric Laurent599c7582015-12-07 18:05:55 -08001910 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001911 }
1912
Eric Laurentc722f302014-12-10 11:21:49 -08001913 inputDesc->mPolicyMix = policyMix;
Eric Laurent599c7582015-12-07 18:05:55 -08001914 inputDesc->addAudioSession(session, audioSession);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001915
Eric Laurent599c7582015-12-07 18:05:55 -08001916 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001917 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001918
Eric Laurent599c7582015-12-07 18:05:55 -08001919 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001920}
1921
Eric Laurentbb948092017-01-23 18:33:30 -08001922//static
1923bool AudioPolicyManager::isConcurrentSource(audio_source_t source)
1924{
1925 return (source == AUDIO_SOURCE_HOTWORD) ||
1926 (source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
1927 (source == AUDIO_SOURCE_FM_TUNER);
1928}
1929
Eric Laurentfb66dd92016-01-28 18:32:03 -08001930bool AudioPolicyManager::isConcurentCaptureAllowed(const sp<AudioInputDescriptor>& inputDesc,
1931 const sp<AudioSession>& audioSession)
1932{
1933 // Do not allow capture if an active voice call is using a software patch and
1934 // the call TX source device is on the same HW module.
1935 // FIXME: would be better to refine to only inputs whose profile connects to the
1936 // call TX device but this information is not in the audio patch
1937 if (mCallTxPatch != 0 &&
1938 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1939 return false;
1940 }
1941
1942 // starting concurrent capture is enabled if:
1943 // 1) capturing for re-routing
1944 // 2) capturing for HOTWORD source
1945 // 3) capturing for FM TUNER source
1946 // 3) All other active captures are either for re-routing or HOTWORD
1947
1948 if (is_virtual_input_device(inputDesc->mDevice) ||
Eric Laurentbb948092017-01-23 18:33:30 -08001949 isConcurrentSource(audioSession->inputSource())) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001950 return true;
1951 }
1952
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001953 for (const auto& activeInput : mInputs.getActiveInputs()) {
Eric Laurentbb948092017-01-23 18:33:30 -08001954 if (!isConcurrentSource(activeInput->inputSource(true)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001955 !is_virtual_input_device(activeInput->mDevice)) {
1956 return false;
1957 }
1958 }
1959
1960 return true;
1961}
1962
Chris Thornton2b864642017-06-27 21:26:07 -07001963// FIXME: remove when concurrent capture is ready. This is a hack to work around bug b/63083537.
1964bool AudioPolicyManager::soundTriggerSupportsConcurrentCapture() {
1965 if (!mHasComputedSoundTriggerSupportsConcurrentCapture) {
1966 bool soundTriggerSupportsConcurrentCapture = false;
1967 unsigned int numModules = 0;
1968 struct sound_trigger_module_descriptor* nModules = NULL;
1969
1970 status_t status = SoundTrigger::listModules(nModules, &numModules);
1971 if (status == NO_ERROR && numModules != 0) {
1972 nModules = (struct sound_trigger_module_descriptor*) calloc(
1973 numModules, sizeof(struct sound_trigger_module_descriptor));
1974 if (nModules == NULL) {
1975 // We failed to malloc the buffer, so just say no for now, and hope that we have more
1976 // ram the next time this function is called.
1977 ALOGE("Failed to allocate buffer for module descriptors");
1978 return false;
1979 }
1980
1981 status = SoundTrigger::listModules(nModules, &numModules);
1982 if (status == NO_ERROR) {
1983 soundTriggerSupportsConcurrentCapture = true;
1984 for (size_t i = 0; i < numModules; ++i) {
1985 soundTriggerSupportsConcurrentCapture &=
1986 nModules[i].properties.concurrent_capture;
1987 }
1988 }
1989 free(nModules);
1990 }
1991 mSoundTriggerSupportsConcurrentCapture = soundTriggerSupportsConcurrentCapture;
1992 mHasComputedSoundTriggerSupportsConcurrentCapture = true;
1993 }
1994 return mSoundTriggerSupportsConcurrentCapture;
1995}
1996
Eric Laurentfb66dd92016-01-28 18:32:03 -08001997
Eric Laurent8fc147b2018-07-22 19:13:55 -07001998status_t AudioPolicyManager::startInput(audio_port_handle_t portId,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001999 bool silenced,
Eric Laurentfb66dd92016-01-28 18:32:03 -08002000 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07002001{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002002 *concurrency = API_INPUT_CONCURRENCY_NONE;
2003
2004 ALOGV("%s portId %d", __FUNCTION__, portId);
2005
2006 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2007 if (inputDesc == 0) {
2008 ALOGW("startInput() no input for client %d", portId);
2009 return BAD_VALUE;
2010 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002011 sp<RecordClientDescriptor> client = inputDesc->clientsMap()[portId];
Eric Laurent8fc147b2018-07-22 19:13:55 -07002012 audio_session_t session = client->session();
2013 audio_io_handle_t input = inputDesc->mIoHandle;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002014
2015 ALOGV("AudioPolicyManager::startInput(input:%d, session:%d, silenced:%d, concurrency:%d)",
2016 input, session, silenced, *concurrency);
2017
Eric Laurent599c7582015-12-07 18:05:55 -08002018 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
2019 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07002020 ALOGW("startInput() unknown session %d on input %d", session, input);
2021 return BAD_VALUE;
2022 }
2023
Eric Laurent74708e72017-04-07 17:13:42 -07002024 if (!is_virtual_input_device(inputDesc->mDevice)) {
2025 if (mCallTxPatch != 0 &&
2026 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
2027 ALOGW("startInput(%d) failed: call in progress", input);
Ray Essick84e84a52018-05-03 18:45:07 -07002028 *concurrency |= API_INPUT_CONCURRENCY_CALL;
Eric Laurent74708e72017-04-07 17:13:42 -07002029 return INVALID_OPERATION;
2030 }
2031
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002032 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002033
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002034 // If a UID is idle and records silence and another not silenced recording starts
2035 // from another UID (idle or active) we stop the current idle UID recording in
2036 // favor of the new one - "There can be only one" TM
2037 if (!silenced) {
2038 for (const auto& activeDesc : activeInputs) {
2039 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
2040 activeDesc->getId() == inputDesc->getId()) {
2041 continue;
2042 }
2043
2044 AudioSessionCollection activeSessions = activeDesc->getAudioSessions(
2045 true /*activeOnly*/);
2046 sp<AudioSession> activeSession = activeSessions.valueAt(0);
2047 if (activeSession->isSilenced()) {
Eric Laurent8fc147b2018-07-22 19:13:55 -07002048 closeSession(activeDesc, activeSession);
2049 ALOGV("startInput() session %d stopping silenced session %d", session, activeSession->session());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002050 activeInputs = mInputs.getActiveInputs();
2051 }
2052 }
2053 }
2054
2055 for (const auto& activeDesc : activeInputs) {
Eric Laurentcb4dae22017-07-01 19:39:32 -07002056 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
2057 activeDesc->getId() == inputDesc->getId()) {
2058 continue;
2059 }
2060
Eric Laurent74708e72017-04-07 17:13:42 -07002061 audio_source_t activeSource = activeDesc->inputSource(true);
2062 if (audioSession->inputSource() == AUDIO_SOURCE_HOTWORD) {
2063 if (activeSource == AUDIO_SOURCE_HOTWORD) {
2064 if (activeDesc->hasPreemptedSession(session)) {
2065 ALOGW("startInput(%d) failed for HOTWORD: "
2066 "other input %d already started for HOTWORD",
2067 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07002068 *concurrency |= API_INPUT_CONCURRENCY_HOTWORD;
Eric Laurent74708e72017-04-07 17:13:42 -07002069 return INVALID_OPERATION;
2070 }
2071 } else {
2072 ALOGV("startInput(%d) failed for HOTWORD: other input %d already started",
2073 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07002074 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07002075 return INVALID_OPERATION;
2076 }
2077 } else {
2078 if (activeSource != AUDIO_SOURCE_HOTWORD) {
2079 ALOGW("startInput(%d) failed: other input %d already started",
2080 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07002081 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07002082 return INVALID_OPERATION;
2083 }
2084 }
2085 }
2086
Chris Thornton2b864642017-06-27 21:26:07 -07002087 // We only need to check if the sound trigger session supports concurrent capture if the
2088 // input is also a sound trigger input. Otherwise, we should preempt any hotword stream
2089 // that's running.
2090 const bool allowConcurrentWithSoundTrigger =
2091 inputDesc->isSoundTrigger() ? soundTriggerSupportsConcurrentCapture() : false;
2092
Eric Laurent74708e72017-04-07 17:13:42 -07002093 // if capture is allowed, preempt currently active HOTWORD captures
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002094 for (const auto& activeDesc : activeInputs) {
Chris Thornton2b864642017-06-27 21:26:07 -07002095 if (allowConcurrentWithSoundTrigger && activeDesc->isSoundTrigger()) {
2096 continue;
2097 }
2098
Eric Laurent74708e72017-04-07 17:13:42 -07002099 audio_source_t activeSource = activeDesc->inputSource(true);
2100 if (activeSource == AUDIO_SOURCE_HOTWORD) {
2101 AudioSessionCollection activeSessions =
2102 activeDesc->getAudioSessions(true /*activeOnly*/);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002103 sp<AudioSession> activeSession = activeSessions[0];
Eric Laurent74708e72017-04-07 17:13:42 -07002104 SortedVector<audio_session_t> sessions = activeDesc->getPreemptedSessions();
Ray Essick84e84a52018-05-03 18:45:07 -07002105 *concurrency |= API_INPUT_CONCURRENCY_PREEMPT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002106 sessions.add(activeSession->session());
Eric Laurent74708e72017-04-07 17:13:42 -07002107 inputDesc->setPreemptedSessions(sessions);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002108 closeSession(inputDesc, activeSession);
Eric Laurent74708e72017-04-07 17:13:42 -07002109 ALOGV("startInput(%d) for HOTWORD preempting HOTWORD input %d",
2110 input, activeDesc->mIoHandle);
2111 }
2112 }
2113 }
Eric Laurente552edb2014-03-10 17:42:56 -07002114
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002115 // Make sure we start with the correct silence state
2116 audioSession->setSilenced(silenced);
2117
Eric Laurent313d1e72016-01-29 09:56:57 -08002118 // increment activity count before calling getNewInputDevice() below as only active sessions
2119 // are considered for device selection
Eric Laurenta18dced2018-07-20 15:14:54 -07002120 inputDesc->changeRefCount(session, 1);
Eric Laurent97ac8712018-07-27 18:59:02 -07002121 client->setActive(true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002122
Eric Laurent97ac8712018-07-27 18:59:02 -07002123 if (audioSession->activeCount() == 1 || client->hasPreferredDevice(true)) {
Eric Laurent271a93e2016-09-29 14:47:06 -07002124 // indicate active capture to sound trigger service if starting capture from a mic on
2125 // primary HW module
Eric Laurentf7c50102016-09-30 15:19:43 -07002126 audio_devices_t device = getNewInputDevice(inputDesc);
Eric Laurent271a93e2016-09-29 14:47:06 -07002127 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002128
Eric Laurent733ce942017-12-07 12:18:25 -08002129 status_t status = inputDesc->start();
2130 if (status != NO_ERROR) {
Eric Laurenta18dced2018-07-20 15:14:54 -07002131 inputDesc->changeRefCount(session, -1);
Eric Laurent97ac8712018-07-27 18:59:02 -07002132 client->setActive(false);
Eric Laurent733ce942017-12-07 12:18:25 -08002133 return status;
2134 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002135
Eric Laurent733ce942017-12-07 12:18:25 -08002136 if (inputDesc->getAudioSessionCount(true/*activeOnly*/) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002137 // if input maps to a dynamic policy with an activity listener, notify of state change
2138 if ((inputDesc->mPolicyMix != NULL)
2139 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2140 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2141 MIX_STATE_MIXING);
Eric Laurentc722f302014-12-10 11:21:49 -08002142 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002143
Eric Laurentf7c50102016-09-30 15:19:43 -07002144 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2145 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Eric Laurent05b345e2016-11-18 12:36:27 -08002146 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002147 SoundTrigger::setCaptureState(true);
2148 }
2149
2150 // automatically enable the remote submix output when input is started if not
2151 // used by a policy mix of type MIX_TYPE_RECORDERS
2152 // For remote submix (a virtual device), we open only one input per capture request.
2153 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2154 String8 address = String8("");
2155 if (inputDesc->mPolicyMix == NULL) {
2156 address = String8("0");
2157 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2158 address = inputDesc->mPolicyMix->mDeviceAddress;
2159 }
2160 if (address != "") {
2161 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2162 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2163 address, "remote-submix");
2164 }
Eric Laurentc722f302014-12-10 11:21:49 -08002165 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002166 }
Eric Laurente552edb2014-03-10 17:42:56 -07002167 }
2168
Eric Laurent599c7582015-12-07 18:05:55 -08002169 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
Eric Laurente552edb2014-03-10 17:42:56 -07002170
Eric Laurente552edb2014-03-10 17:42:56 -07002171 return NO_ERROR;
2172}
2173
Eric Laurent8fc147b2018-07-22 19:13:55 -07002174status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002175{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002176 ALOGV("%s portId %d", __FUNCTION__, portId);
2177
2178 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2179 if (inputDesc == 0) {
2180 ALOGW("stopInput() no input for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002181 return BAD_VALUE;
2182 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002183 sp<RecordClientDescriptor> client = inputDesc->clientsMap()[portId];
Eric Laurent8fc147b2018-07-22 19:13:55 -07002184 audio_session_t session = client->session();
2185 audio_io_handle_t input = inputDesc->mIoHandle;
2186
2187 ALOGV("stopInput() input %d", input);
Eric Laurente552edb2014-03-10 17:42:56 -07002188
Eric Laurent599c7582015-12-07 18:05:55 -08002189 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07002190
Eric Laurent599c7582015-12-07 18:05:55 -08002191 if (audioSession->activeCount() == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002192 ALOGW("stopInput() input %d already stopped", input);
2193 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002194 }
2195
Eric Laurenta18dced2018-07-20 15:14:54 -07002196 inputDesc->changeRefCount(session, -1);
Eric Laurent97ac8712018-07-27 18:59:02 -07002197 client->setActive(false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002198
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002199 if (audioSession->activeCount() == 0) {
Eric Laurent733ce942017-12-07 12:18:25 -08002200 inputDesc->stop();
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002201 if (inputDesc->isActive()) {
2202 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2203 } else {
2204 // if input maps to a dynamic policy with an activity listener, notify of state change
2205 if ((inputDesc->mPolicyMix != NULL)
2206 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2207 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2208 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002209 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002210
2211 // automatically disable the remote submix output when input is stopped if not
2212 // used by a policy mix of type MIX_TYPE_RECORDERS
2213 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2214 String8 address = String8("");
2215 if (inputDesc->mPolicyMix == NULL) {
2216 address = String8("0");
2217 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2218 address = inputDesc->mPolicyMix->mDeviceAddress;
2219 }
2220 if (address != "") {
2221 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2222 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2223 address, "remote-submix");
2224 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002225 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002226
Eric Laurentf7c50102016-09-30 15:19:43 -07002227 audio_devices_t device = inputDesc->mDevice;
Eric Laurentfb66dd92016-01-28 18:32:03 -08002228 resetInputDevice(input);
Eric Laurent84332aa2016-01-28 22:19:18 +00002229
Eric Laurentf7c50102016-09-30 15:19:43 -07002230 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2231 // primary HW module
2232 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2233 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2234 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08002235 SoundTrigger::setCaptureState(false);
2236 }
2237 inputDesc->clearPreemptedSessions();
Eric Laurent84332aa2016-01-28 22:19:18 +00002238 }
Eric Laurente552edb2014-03-10 17:42:56 -07002239 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002240 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002241}
2242
Eric Laurent8fc147b2018-07-22 19:13:55 -07002243void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002244{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002245 ALOGV("%s portId %d", __FUNCTION__, portId);
2246
2247 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2248 if (inputDesc == 0) {
2249 ALOGW("releaseInput() no input for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002250 return;
2251 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002252 sp<RecordClientDescriptor> client = inputDesc->clientsMap()[portId];
Eric Laurent8fc147b2018-07-22 19:13:55 -07002253 audio_session_t session = client->session();
2254 audio_io_handle_t input = inputDesc->mIoHandle;
2255
2256 ALOGV("releaseInput() %d", input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002257
Eric Laurent599c7582015-12-07 18:05:55 -08002258 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
vivek mehta587b8df2017-01-31 14:58:44 -08002259 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07002260 ALOGW("releaseInput() unknown session %d on input %d", session, input);
2261 return;
2262 }
Eric Laurent599c7582015-12-07 18:05:55 -08002263
2264 if (audioSession->openCount() == 0) {
2265 ALOGW("releaseInput() invalid open count %d on session %d",
2266 audioSession->openCount(), session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002267 return;
2268 }
Eric Laurent599c7582015-12-07 18:05:55 -08002269
2270 if (audioSession->changeOpenCount(-1) == 0) {
2271 inputDesc->removeAudioSession(session);
2272 }
2273
Jean-Michel Trivi65bfe912015-12-04 15:56:47 -08002274 if (inputDesc->getOpenRefCount() > 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002275 ALOGV("releaseInput() exit > 0");
2276 return;
2277 }
2278
Eric Laurent05b90f82014-08-27 15:32:29 -07002279 closeInput(input);
Eric Laurent97ac8712018-07-27 18:59:02 -07002280 inputDesc->clientsMap().erase(portId);
Eric Laurentb52c1522014-05-20 11:27:36 -07002281 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002282 ALOGV("releaseInput() exit");
2283}
2284
Eric Laurent8fc147b2018-07-22 19:13:55 -07002285void AudioPolicyManager::closeSessions(const sp<AudioInputDescriptor>& input, bool activeOnly)
2286{
2287 AudioSessionCollection sessions = input->getAudioSessions(activeOnly /*activeOnly*/);
2288 for (size_t i = 0; i < sessions.size(); i++) {
2289 closeSession(input, sessions[i]);
2290 }
2291}
2292
2293void AudioPolicyManager::closeSession(const sp<AudioInputDescriptor>& input,
2294 const sp<AudioSession>& session)
2295{
2296 RecordClientVector clients = input->getClientsForSession(session->session());
2297
2298 for (const auto& client : clients) {
2299 stopInput(client->portId());
2300 releaseInput(client->portId());
2301 }
2302}
2303
2304
Eric Laurentd4692962014-05-05 18:13:44 -07002305void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002306 bool patchRemoved = false;
2307
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002308 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002309 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002310 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002311 if (patch_index >= 0) {
2312 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002313 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002314 mAudioPatches.removeItemsAt(patch_index);
2315 patchRemoved = true;
2316 }
Eric Laurentfe231122017-11-17 17:48:06 -08002317 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002318 }
2319 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002320 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002321 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002322
2323 if (patchRemoved) {
2324 mpClientInterface->onAudioPatchListUpdate();
2325 }
Eric Laurentd4692962014-05-05 18:13:44 -07002326}
2327
Eric Laurente0720872014-03-11 09:30:41 -07002328void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002329 int indexMin,
2330 int indexMax)
2331{
2332 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002333 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002334
2335 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002336 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2337 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002338 continue;
2339 }
2340 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002341 }
Eric Laurente552edb2014-03-10 17:42:56 -07002342}
2343
Eric Laurente0720872014-03-11 09:30:41 -07002344status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002345 int index,
2346 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002347{
2348
Nadav Bar7c605f62017-12-25 00:01:52 +02002349 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2350 // app that has MODIFY_PHONE_STATE permission.
2351 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
2352 !(stream == AUDIO_STREAM_VOICE_CALL && index == 0)) ||
François Gaffied1ab2bd2015-12-02 18:20:06 +01002353 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002354 return BAD_VALUE;
2355 }
2356 if (!audio_is_output_device(device)) {
2357 return BAD_VALUE;
2358 }
2359
2360 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002361 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002362
Eric Laurent1fd372e2016-04-06 14:23:53 -07002363 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002364 stream, device, index);
2365
Eric Laurent28d09f02016-03-08 10:43:05 -08002366 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002367 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2368 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002369 continue;
2370 }
2371 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2372 }
Eric Laurente552edb2014-03-10 17:42:56 -07002373
Eric Laurent1fd372e2016-04-06 14:23:53 -07002374 // update volume on all outputs and streams matching the following:
2375 // - The requested stream (or a stream matching for volume control) is active on the output
2376 // - The device (or devices) selected by the strategy corresponding to this stream includes
2377 // the requested device
2378 // - For non default requested device, currently selected device on the output is either the
2379 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002380 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2381 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002382 status_t status = NO_ERROR;
2383 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002384 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2385 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08002386 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
Eric Laurent3839bc02018-07-10 18:33:34 -07002387 if (!(streamsMatchForvolume(stream, (audio_stream_type_t)curStream))) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002388 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002389 }
Eric Laurentdcd4ab12018-06-29 17:45:13 -07002390 if (!(desc->isStreamActive((audio_stream_type_t)curStream) || isInCall())) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002391 continue;
2392 }
Eric Laurent794fde22016-03-11 09:50:45 -08002393 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002394 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2395 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002396 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2397 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002398 continue;
2399 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002400 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002401 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002402 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07002403 applyVolume = (curDevice & curStreamDevice) != 0;
2404 } else {
2405 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002406 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002407 }
Eric Laurent3839bc02018-07-10 18:33:34 -07002408 // rescale index before applying to curStream as ranges may be different for
2409 // stream and curStream
2410 int idx = rescaleVolumeIndex(index, stream, (audio_stream_type_t)curStream);
Eric Laurente76f29c2016-09-14 17:17:53 -07002411 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002412 //FIXME: workaround for truncated touch sounds
2413 // delayed volume change for system stream to be removed when the problem is
2414 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002415 status_t volStatus =
Eric Laurent3839bc02018-07-10 18:33:34 -07002416 checkAndSetVolume((audio_stream_type_t)curStream, idx, desc, curDevice,
Eric Laurentdc462862016-07-19 12:29:53 -07002417 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002418 if (volStatus != NO_ERROR) {
2419 status = volStatus;
2420 }
2421 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002422 }
Eric Laurente552edb2014-03-10 17:42:56 -07002423 }
2424 return status;
2425}
2426
Eric Laurente0720872014-03-11 09:30:41 -07002427status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002428 int *index,
2429 audio_devices_t device)
2430{
2431 if (index == NULL) {
2432 return BAD_VALUE;
2433 }
2434 if (!audio_is_output_device(device)) {
2435 return BAD_VALUE;
2436 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002437 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002438 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002439 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002440 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2441 }
François Gaffiedfd74092015-03-19 12:10:59 +01002442 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002443
François Gaffied1ab2bd2015-12-02 18:20:06 +01002444 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002445 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2446 return NO_ERROR;
2447}
2448
Eric Laurent36829f92017-04-07 19:04:42 -07002449audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002450{
2451 // select one output among several suitable for global effects.
2452 // The priority is as follows:
2453 // 1: An offloaded output. If the effect ends up not being offloadable,
2454 // AudioFlinger will invalidate the track and the offloaded output
2455 // will be closed causing the effect to be moved to a PCM output.
2456 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002457 // 3: The primary output
2458 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002459
Eric Laurent3b73df72014-03-11 09:06:29 -07002460 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002461 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent36829f92017-04-07 19:04:42 -07002462 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002463
Eric Laurent36829f92017-04-07 19:04:42 -07002464 if (outputs.size() == 0) {
2465 return AUDIO_IO_HANDLE_NONE;
2466 }
Eric Laurente552edb2014-03-10 17:42:56 -07002467
Eric Laurent36829f92017-04-07 19:04:42 -07002468 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2469 bool activeOnly = true;
2470
2471 while (output == AUDIO_IO_HANDLE_NONE) {
2472 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2473 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2474 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2475
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002476 for (audio_io_handle_t output : outputs) {
2477 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002478 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2479 continue;
2480 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002481 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2482 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002483 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002484 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002485 }
2486 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002487 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002488 }
2489 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002490 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002491 }
2492 }
2493 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2494 output = outputOffloaded;
2495 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2496 output = outputDeepBuffer;
2497 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2498 output = outputPrimary;
2499 } else {
2500 output = outputs[0];
2501 }
2502 activeOnly = false;
2503 }
2504
2505 if (output != mMusicEffectOutput) {
2506 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2507 mMusicEffectOutput = output;
2508 }
2509
2510 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002511 return output;
2512}
2513
Eric Laurent36829f92017-04-07 19:04:42 -07002514audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2515{
2516 return selectOutputForMusicEffects();
2517}
2518
Eric Laurente0720872014-03-11 09:30:41 -07002519status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002520 audio_io_handle_t io,
2521 uint32_t strategy,
2522 int session,
2523 int id)
2524{
2525 ssize_t index = mOutputs.indexOfKey(io);
2526 if (index < 0) {
2527 index = mInputs.indexOfKey(io);
2528 if (index < 0) {
2529 ALOGW("registerEffect() unknown io %d", io);
2530 return INVALID_OPERATION;
2531 }
2532 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002533 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002534}
2535
Eric Laurentc75307b2015-03-17 15:29:32 -07002536bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2537{
Eric Laurent28d09f02016-03-08 10:43:05 -08002538 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002539 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2540 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002541 continue;
2542 }
2543 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2544 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002545 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002546}
2547
2548bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2549{
2550 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2551}
2552
Eric Laurente0720872014-03-11 09:30:41 -07002553bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002554{
2555 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002556 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002557 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002558 return true;
2559 }
2560 }
2561 return false;
2562}
2563
Eric Laurent275e8e92014-11-30 15:14:47 -08002564// Register a list of custom mixes with their attributes and format.
2565// When a mix is registered, corresponding input and output profiles are
2566// added to the remote submix hw module. The profile contains only the
2567// parameters (sampling rate, format...) specified by the mix.
2568// The corresponding input remote submix device is also connected.
2569//
2570// When a remote submix device is connected, the address is checked to select the
2571// appropriate profile and the corresponding input or output stream is opened.
2572//
2573// When capture starts, getInputForAttr() will:
2574// - 1 look for a mix matching the address passed in attribtutes tags if any
2575// - 2 if none found, getDeviceForInputSource() will:
2576// - 2.1 look for a mix matching the attributes source
2577// - 2.2 if none found, default to device selection by policy rules
2578// At this time, the corresponding output remote submix device is also connected
2579// and active playback use cases can be transferred to this mix if needed when reconnecting
2580// after AudioTracks are invalidated
2581//
2582// When playback starts, getOutputForAttr() will:
2583// - 1 look for a mix matching the address passed in attribtutes tags if any
2584// - 2 if none found, look for a mix matching the attributes usage
2585// - 3 if none found, default to device and output selection by policy rules.
2586
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002587status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002588{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002589 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2590 status_t res = NO_ERROR;
2591
2592 sp<HwModule> rSubmixModule;
2593 // examine each mix's route type
2594 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002595 AudioMix mix = mixes[i];
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002596 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
Eric Laurent97ac8712018-07-27 18:59:02 -07002597 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002598 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002599 break;
2600 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002601 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002602 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002603 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002604 rSubmixModule = mHwModules.getModuleFromName(
2605 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2606 if (rSubmixModule == 0) {
2607 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2608 i);
2609 res = INVALID_OPERATION;
2610 break;
2611 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002612 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002613
Eric Laurent97ac8712018-07-27 18:59:02 -07002614 String8 address = mix.mDeviceAddress;
2615 if (mix.mMixType == MIX_TYPE_PLAYERS) {
2616 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2617 } else {
2618 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
2619 }
François Gaffie036e1e92015-03-19 10:16:24 +01002620
Eric Laurent97ac8712018-07-27 18:59:02 -07002621 if (mPolicyMixes.registerMix(address, mix, 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002622 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002623 res = INVALID_OPERATION;
2624 break;
2625 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002626 audio_config_t outputConfig = mix.mFormat;
2627 audio_config_t inputConfig = mix.mFormat;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002628 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2629 // stereo and let audio flinger do the channel conversion if needed.
2630 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2631 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2632 rSubmixModule->addOutputProfile(address, &outputConfig,
2633 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2634 rSubmixModule->addInputProfile(address, &inputConfig,
2635 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002636
Eric Laurent97ac8712018-07-27 18:59:02 -07002637 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002638 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2639 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2640 address.string(), "remote-submix");
2641 } else {
2642 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2643 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2644 address.string(), "remote-submix");
2645 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002646 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2647 String8 address = mix.mDeviceAddress;
2648 audio_devices_t device = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002649 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2650 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002651
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002652 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002653 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2654 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2655 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2656 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2657 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2658 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002659 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2660 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002661 if (mPolicyMixes.registerMix(address, mix, desc) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002662 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002663 } else {
2664 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002665 }
2666 break;
2667 }
2668 }
2669
2670 if (res != NO_ERROR) {
2671 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002672 i, device, address.string());
2673 res = INVALID_OPERATION;
2674 break;
2675 } else if (!foundOutput) {
2676 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2677 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002678 res = INVALID_OPERATION;
2679 break;
2680 }
Eric Laurentc722f302014-12-10 11:21:49 -08002681 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002682 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002683 if (res != NO_ERROR) {
2684 unregisterPolicyMixes(mixes);
2685 }
2686 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002687}
2688
2689status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2690{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002691 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002692 status_t res = NO_ERROR;
2693 sp<HwModule> rSubmixModule;
2694 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002695 for (const auto& mix : mixes) {
2696 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002697
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002698 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002699 rSubmixModule = mHwModules.getModuleFromName(
2700 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2701 if (rSubmixModule == 0) {
2702 res = INVALID_OPERATION;
2703 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002704 }
2705 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002706
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002707 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002708
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002709 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2710 res = INVALID_OPERATION;
2711 continue;
2712 }
2713
2714 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2715 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2716 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2717 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2718 address.string(), "remote-submix");
2719 }
2720 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2721 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2722 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2723 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2724 address.string(), "remote-submix");
2725 }
2726 rSubmixModule->removeOutputProfile(address);
2727 rSubmixModule->removeInputProfile(address);
2728
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002729 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2730 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002731 res = INVALID_OPERATION;
2732 continue;
2733 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002734 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002735 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002736 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002737}
2738
Eric Laurente552edb2014-03-10 17:42:56 -07002739
Eric Laurente0720872014-03-11 09:30:41 -07002740status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002741{
Eric Laurente552edb2014-03-10 17:42:56 -07002742 String8 result;
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002743 result.appendFormat("\nAudioPolicyManager Dump: %p\n", this);
2744 result.appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07002745 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002746 std::string stateLiteral;
2747 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002748 result.appendFormat(" Phone state: %s\n", stateLiteral.c_str());
2749 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
2750 "communications", "media", "record", "dock", "system",
2751 "HDMI system audio", "encoded surround output", "vibrate ringing" };
2752 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
2753 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
2754 result.appendFormat(" Force use for %s: %d\n",
2755 forceUses[i], mEngine->getForceUse(i));
2756 }
2757 result.appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
2758 result.appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
2759 result.appendFormat(" Config source: %s\n", getConfig().getSource().c_str());
François Gaffie2110e042015-03-24 08:41:51 +01002760 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002761
François Gaffie112b0af2015-11-19 16:13:25 +01002762 mAvailableOutputDevices.dump(fd, String8("Available output"));
2763 mAvailableInputDevices.dump(fd, String8("Available input"));
Mikhail Naganovd4120142017-12-06 15:49:22 -08002764 mHwModulesAll.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002765 mOutputs.dump(fd);
2766 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002767 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002768 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002769 mAudioPatches.dump(fd);
Mikhail Naganov44344b02016-12-13 11:21:02 -08002770 mPolicyMixes.dump(fd);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07002771 mAudioSources.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002772
2773 return NO_ERROR;
2774}
2775
2776// This function checks for the parameters which can be offloaded.
2777// This can be enhanced depending on the capability of the DSP and policy
2778// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002779bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002780{
2781 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002782 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002783 offloadInfo.sample_rate, offloadInfo.channel_mask,
2784 offloadInfo.format,
2785 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2786 offloadInfo.has_video);
2787
Andy Hung2ddee192015-12-18 17:34:44 -08002788 if (mMasterMono) {
2789 return false; // no offloading if mono is set.
2790 }
2791
Eric Laurente552edb2014-03-10 17:42:56 -07002792 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07002793 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
2794 ALOGV("offload disabled by audio.offload.disable");
2795 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002796 }
2797
2798 // Check if stream type is music, then only allow offload as of now.
2799 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2800 {
2801 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2802 return false;
2803 }
2804
2805 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002806 const bool allowOffloadWithVideo =
2807 property_get_bool("audio.offload.video", false /* default_value */);
2808 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002809 ALOGV("isOffloadSupported: has_video == true, returning false");
2810 return false;
2811 }
2812
2813 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07002814 const int min_duration_secs = property_get_int32(
2815 "audio.offload.min.duration.secs", -1 /* default_value */);
2816 if (min_duration_secs >= 0) {
2817 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
2818 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%d)",
2819 min_duration_secs);
Eric Laurente552edb2014-03-10 17:42:56 -07002820 return false;
2821 }
2822 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2823 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2824 return false;
2825 }
2826
2827 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2828 // creating an offloaded track and tearing it down immediately after start when audioflinger
2829 // detects there is an active non offloadable effect.
2830 // FIXME: We should check the audio session here but we do not have it in this context.
2831 // This may prevent offloading in rare situations where effects are left active by apps
2832 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002833 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002834 return false;
2835 }
2836
2837 // See if there is a profile to support this.
2838 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002839 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002840 offloadInfo.sample_rate,
2841 offloadInfo.format,
2842 offloadInfo.channel_mask,
2843 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002844 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2845 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002846}
2847
Eric Laurent6a94d692014-05-20 11:18:06 -07002848status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2849 audio_port_type_t type,
2850 unsigned int *num_ports,
2851 struct audio_port *ports,
2852 unsigned int *generation)
2853{
2854 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2855 generation == NULL) {
2856 return BAD_VALUE;
2857 }
2858 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2859 if (ports == NULL) {
2860 *num_ports = 0;
2861 }
2862
2863 size_t portsWritten = 0;
2864 size_t portsMax = *num_ports;
2865 *num_ports = 0;
2866 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002867 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2868 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002869 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002870 for (const auto& dev : mAvailableOutputDevices) {
2871 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002872 continue;
2873 }
2874 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002875 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002876 }
2877 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002878 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002879 }
2880 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002881 for (const auto& dev : mAvailableInputDevices) {
2882 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002883 continue;
2884 }
2885 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002886 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002887 }
2888 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002889 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002890 }
2891 }
2892 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2893 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2894 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2895 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2896 }
2897 *num_ports += mInputs.size();
2898 }
2899 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002900 size_t numOutputs = 0;
2901 for (size_t i = 0; i < mOutputs.size(); i++) {
2902 if (!mOutputs[i]->isDuplicated()) {
2903 numOutputs++;
2904 if (portsWritten < portsMax) {
2905 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2906 }
2907 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002908 }
Eric Laurent84c70242014-06-23 08:46:27 -07002909 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002910 }
2911 }
2912 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002913 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002914 return NO_ERROR;
2915}
2916
Eric Laurent99fcae42018-05-17 16:59:18 -07002917status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07002918{
Eric Laurent99fcae42018-05-17 16:59:18 -07002919 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
2920 return BAD_VALUE;
2921 }
2922 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
2923 if (dev != 0) {
2924 dev->toAudioPort(port);
2925 return NO_ERROR;
2926 }
2927 dev = mAvailableInputDevices.getDeviceFromId(port->id);
2928 if (dev != 0) {
2929 dev->toAudioPort(port);
2930 return NO_ERROR;
2931 }
2932 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
2933 if (out != 0) {
2934 out->toAudioPort(port);
2935 return NO_ERROR;
2936 }
2937 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
2938 if (in != 0) {
2939 in->toAudioPort(port);
2940 return NO_ERROR;
2941 }
2942 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002943}
2944
Eric Laurent6a94d692014-05-20 11:18:06 -07002945status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2946 audio_patch_handle_t *handle,
2947 uid_t uid)
2948{
2949 ALOGV("createAudioPatch()");
2950
2951 if (handle == NULL || patch == NULL) {
2952 return BAD_VALUE;
2953 }
2954 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2955
Mikhail Naganovac9858b2018-06-15 13:12:37 -07002956 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07002957 return BAD_VALUE;
2958 }
2959 // only one source per audio patch supported for now
2960 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002961 return INVALID_OPERATION;
2962 }
Eric Laurent874c42872014-08-08 15:13:39 -07002963
2964 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002965 return INVALID_OPERATION;
2966 }
Eric Laurent874c42872014-08-08 15:13:39 -07002967 for (size_t i = 0; i < patch->num_sinks; i++) {
2968 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2969 return INVALID_OPERATION;
2970 }
2971 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002972
2973 sp<AudioPatch> patchDesc;
2974 ssize_t index = mAudioPatches.indexOfKey(*handle);
2975
Eric Laurent6a94d692014-05-20 11:18:06 -07002976 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2977 patch->sources[0].role,
2978 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002979#if LOG_NDEBUG == 0
2980 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002981 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002982 patch->sinks[i].role,
2983 patch->sinks[i].type);
2984 }
2985#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002986
2987 if (index >= 0) {
2988 patchDesc = mAudioPatches.valueAt(index);
2989 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2990 mUidCached, patchDesc->mUid, uid);
2991 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2992 return INVALID_OPERATION;
2993 }
2994 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002995 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002996 }
2997
2998 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002999 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003000 if (outputDesc == NULL) {
3001 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
3002 return BAD_VALUE;
3003 }
Eric Laurent84c70242014-06-23 08:46:27 -07003004 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
3005 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003006 if (patchDesc != 0) {
3007 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
3008 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
3009 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
3010 return BAD_VALUE;
3011 }
3012 }
Eric Laurent874c42872014-08-08 15:13:39 -07003013 DeviceVector devices;
3014 for (size_t i = 0; i < patch->num_sinks; i++) {
3015 // Only support mix to devices connection
3016 // TODO add support for mix to mix connection
3017 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3018 ALOGV("createAudioPatch() source mix but sink is not a device");
3019 return INVALID_OPERATION;
3020 }
3021 sp<DeviceDescriptor> devDesc =
3022 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3023 if (devDesc == 0) {
3024 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
3025 return BAD_VALUE;
3026 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003027
François Gaffie53615e22015-03-19 09:24:12 +01003028 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08003029 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07003030 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01003031 NULL, // updatedSamplingRate
3032 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003033 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01003034 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003035 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01003036 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07003037 ALOGV("createAudioPatch() profile not supported for device %08x",
3038 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07003039 return INVALID_OPERATION;
3040 }
3041 devices.add(devDesc);
3042 }
3043 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003044 return INVALID_OPERATION;
3045 }
Eric Laurent874c42872014-08-08 15:13:39 -07003046
Eric Laurent6a94d692014-05-20 11:18:06 -07003047 // TODO: reconfigure output format and channels here
3048 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07003049 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07003050 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003051 index = mAudioPatches.indexOfKey(*handle);
3052 if (index >= 0) {
3053 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3054 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
3055 }
3056 patchDesc = mAudioPatches.valueAt(index);
3057 patchDesc->mUid = uid;
3058 ALOGV("createAudioPatch() success");
3059 } else {
3060 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
3061 return INVALID_OPERATION;
3062 }
3063 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3064 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3065 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003066 // only one sink supported when connecting an input device to a mix
3067 if (patch->num_sinks > 1) {
3068 return INVALID_OPERATION;
3069 }
François Gaffie53615e22015-03-19 09:24:12 +01003070 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003071 if (inputDesc == NULL) {
3072 return BAD_VALUE;
3073 }
3074 if (patchDesc != 0) {
3075 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3076 return BAD_VALUE;
3077 }
3078 }
3079 sp<DeviceDescriptor> devDesc =
3080 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
3081 if (devDesc == 0) {
3082 return BAD_VALUE;
3083 }
3084
François Gaffie53615e22015-03-19 09:24:12 +01003085 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08003086 devDesc->mAddress,
3087 patch->sinks[0].sample_rate,
3088 NULL, /*updatedSampleRate*/
3089 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003090 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003091 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003092 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003093 // FIXME for the parameter type,
3094 // and the NONE
3095 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003096 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003097 return INVALID_OPERATION;
3098 }
3099 // TODO: reconfigure output format and channels here
3100 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01003101 devDesc->type(), inputDesc->mIoHandle);
3102 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003103 index = mAudioPatches.indexOfKey(*handle);
3104 if (index >= 0) {
3105 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3106 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
3107 }
3108 patchDesc = mAudioPatches.valueAt(index);
3109 patchDesc->mUid = uid;
3110 ALOGV("createAudioPatch() success");
3111 } else {
3112 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
3113 return INVALID_OPERATION;
3114 }
3115 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3116 // device to device connection
3117 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003118 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003119 return BAD_VALUE;
3120 }
3121 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003122 sp<DeviceDescriptor> srcDeviceDesc =
3123 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07003124 if (srcDeviceDesc == 0) {
3125 return BAD_VALUE;
3126 }
Eric Laurent874c42872014-08-08 15:13:39 -07003127
Eric Laurent6a94d692014-05-20 11:18:06 -07003128 //update source and sink with our own data as the data passed in the patch may
3129 // be incomplete.
3130 struct audio_patch newPatch = *patch;
3131 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003132
Eric Laurent874c42872014-08-08 15:13:39 -07003133 for (size_t i = 0; i < patch->num_sinks; i++) {
3134 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3135 ALOGV("createAudioPatch() source device but one sink is not a device");
3136 return INVALID_OPERATION;
3137 }
3138
3139 sp<DeviceDescriptor> sinkDeviceDesc =
3140 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3141 if (sinkDeviceDesc == 0) {
3142 return BAD_VALUE;
3143 }
3144 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
3145
Eric Laurent3bcf8592015-04-03 12:13:24 -07003146 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003147 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003148 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08003149 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003150 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003151 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003152 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003153 return INVALID_OPERATION;
3154 }
Eric Laurent874c42872014-08-08 15:13:39 -07003155 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01003156 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003157 // if the sink device is reachable via an opened output stream, request to go via
3158 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07003159 audio_io_handle_t output = selectOutput(outputs,
3160 AUDIO_OUTPUT_FLAG_NONE,
3161 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07003162 if (output != AUDIO_IO_HANDLE_NONE) {
3163 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3164 if (outputDesc->isDuplicated()) {
3165 return INVALID_OPERATION;
3166 }
3167 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003168 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003169 newPatch.num_sources = 2;
3170 }
Eric Laurent83b88082014-06-20 18:31:16 -07003171 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003172 }
3173 // TODO: check from routing capabilities in config file and other conflicting patches
3174
Mikhail Naganovdc769682018-05-04 15:34:08 -07003175 status_t status = installPatch(__func__, index, handle, &newPatch, 0, uid, &patchDesc);
3176 if (status != NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003177 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3178 status);
3179 return INVALID_OPERATION;
3180 }
3181 } else {
3182 return BAD_VALUE;
3183 }
3184 } else {
3185 return BAD_VALUE;
3186 }
3187 return NO_ERROR;
3188}
3189
3190status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3191 uid_t uid)
3192{
3193 ALOGV("releaseAudioPatch() patch %d", handle);
3194
3195 ssize_t index = mAudioPatches.indexOfKey(handle);
3196
3197 if (index < 0) {
3198 return BAD_VALUE;
3199 }
3200 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3201 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3202 mUidCached, patchDesc->mUid, uid);
3203 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3204 return INVALID_OPERATION;
3205 }
3206
3207 struct audio_patch *patch = &patchDesc->mPatch;
3208 patchDesc->mUid = mUidCached;
3209 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003210 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003211 if (outputDesc == NULL) {
3212 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3213 return BAD_VALUE;
3214 }
3215
Eric Laurentc75307b2015-03-17 15:29:32 -07003216 setOutputDevice(outputDesc,
3217 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07003218 true,
3219 0,
3220 NULL);
3221 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3222 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003223 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003224 if (inputDesc == NULL) {
3225 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3226 return BAD_VALUE;
3227 }
3228 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003229 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003230 true,
3231 NULL);
3232 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003233 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3234 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3235 status, patchDesc->mAfPatchHandle);
3236 removeAudioPatch(patchDesc->mHandle);
3237 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003238 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003239 } else {
3240 return BAD_VALUE;
3241 }
3242 } else {
3243 return BAD_VALUE;
3244 }
3245 return NO_ERROR;
3246}
3247
3248status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3249 struct audio_patch *patches,
3250 unsigned int *generation)
3251{
François Gaffie53615e22015-03-19 09:24:12 +01003252 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003253 return BAD_VALUE;
3254 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003255 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003256 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003257}
3258
Eric Laurente1715a42014-05-20 11:30:42 -07003259status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003260{
Eric Laurente1715a42014-05-20 11:30:42 -07003261 ALOGV("setAudioPortConfig()");
3262
3263 if (config == NULL) {
3264 return BAD_VALUE;
3265 }
3266 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3267 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003268 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3269 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003270 }
3271
Eric Laurenta121f902014-06-03 13:32:54 -07003272 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003273 if (config->type == AUDIO_PORT_TYPE_MIX) {
3274 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003275 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003276 if (outputDesc == NULL) {
3277 return BAD_VALUE;
3278 }
Eric Laurent84c70242014-06-23 08:46:27 -07003279 ALOG_ASSERT(!outputDesc->isDuplicated(),
3280 "setAudioPortConfig() called on duplicated output %d",
3281 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003282 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003283 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003284 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003285 if (inputDesc == NULL) {
3286 return BAD_VALUE;
3287 }
Eric Laurenta121f902014-06-03 13:32:54 -07003288 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003289 } else {
3290 return BAD_VALUE;
3291 }
3292 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3293 sp<DeviceDescriptor> deviceDesc;
3294 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3295 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3296 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3297 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3298 } else {
3299 return BAD_VALUE;
3300 }
3301 if (deviceDesc == NULL) {
3302 return BAD_VALUE;
3303 }
Eric Laurenta121f902014-06-03 13:32:54 -07003304 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003305 } else {
3306 return BAD_VALUE;
3307 }
3308
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003309 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003310 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3311 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003312 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003313 audioPortConfig->toAudioPortConfig(&newConfig, config);
3314 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003315 }
Eric Laurenta121f902014-06-03 13:32:54 -07003316 if (status != NO_ERROR) {
3317 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003318 }
Eric Laurente1715a42014-05-20 11:30:42 -07003319
3320 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003321}
3322
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003323void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3324{
Eric Laurentd60560a2015-04-10 11:31:20 -07003325 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003326 clearAudioPatches(uid);
3327 clearSessionRoutes(uid);
3328}
3329
Eric Laurent6a94d692014-05-20 11:18:06 -07003330void AudioPolicyManager::clearAudioPatches(uid_t uid)
3331{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003332 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003333 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3334 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003335 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003336 }
3337 }
3338}
3339
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003340void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3341 audio_io_handle_t ouptutToSkip)
3342{
3343 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3344 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3345 for (size_t j = 0; j < mOutputs.size(); j++) {
3346 if (mOutputs.keyAt(j) == ouptutToSkip) {
3347 continue;
3348 }
3349 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3350 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3351 continue;
3352 }
3353 // If the default device for this strategy is on another output mix,
3354 // invalidate all tracks in this strategy to force re connection.
3355 // Otherwise select new device on the output mix.
3356 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003357 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003358 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3359 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3360 }
3361 }
3362 } else {
3363 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3364 setOutputDevice(outputDesc, newDevice, false);
3365 }
3366 }
3367}
3368
3369void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3370{
3371 // remove output routes associated with this uid
3372 SortedVector<routing_strategy> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07003373 for (size_t i = 0; i < mOutputs.size(); i++) {
3374 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3375 TrackClientMap clients = outputDesc->clientsMap();
3376 for (const auto& client : clients) {
3377 if (client.second->hasPreferredDevice() && client.second->uid() == uid) {
3378 client.second->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3379 affectedStrategies.add(getStrategy(client.second->stream()));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003380 }
3381 }
3382 }
3383 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003384 for (const auto& strategy : affectedStrategies) {
3385 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003386 }
3387
3388 // remove input routes associated with this uid
3389 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07003390 for (size_t i = 0; i < mInputs.size(); i++) {
3391 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
3392 RecordClientMap clients = inputDesc->clientsMap();
3393 for (const auto& client : clients) {
3394 if (client.second->hasPreferredDevice() && client.second->uid() == uid) {
3395 client.second->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3396 affectedSources.add(client.second->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003397 }
3398 }
3399 }
3400 // reroute inputs if necessary
3401 SortedVector<audio_io_handle_t> inputsToClose;
3402 for (size_t i = 0; i < mInputs.size(); i++) {
3403 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003404 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003405 inputsToClose.add(inputDesc->mIoHandle);
3406 }
3407 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003408 for (const auto& input : inputsToClose) {
3409 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003410 }
3411}
3412
Eric Laurentd60560a2015-04-10 11:31:20 -07003413void AudioPolicyManager::clearAudioSources(uid_t uid)
3414{
3415 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003416 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3417 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07003418 stopAudioSource(mAudioSources.keyAt(i));
3419 }
3420 }
3421}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003422
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003423status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3424 audio_io_handle_t *ioHandle,
3425 audio_devices_t *device)
3426{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003427 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3428 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003429 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003430
François Gaffiedf372692015-03-19 10:43:27 +01003431 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003432}
3433
Eric Laurentd60560a2015-04-10 11:31:20 -07003434status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003435 const audio_attributes_t *attributes,
3436 audio_port_handle_t *portId,
3437 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003438{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003439 ALOGV("%s", __FUNCTION__);
3440 *portId = AUDIO_PORT_HANDLE_NONE;
3441
3442 if (source == NULL || attributes == NULL || portId == NULL) {
3443 ALOGW("%s invalid argument: source %p attributes %p handle %p",
3444 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003445 return BAD_VALUE;
3446 }
3447
Eric Laurentd60560a2015-04-10 11:31:20 -07003448 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3449 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003450 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
3451 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003452 return INVALID_OPERATION;
3453 }
3454
3455 sp<DeviceDescriptor> srcDeviceDesc =
3456 mAvailableInputDevices.getDevice(source->ext.device.type,
3457 String8(source->ext.device.address));
3458 if (srcDeviceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003459 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003460 return BAD_VALUE;
3461 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003462
3463 *portId = AudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07003464
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003465 struct audio_patch dummyPatch = {};
Eric Laurentd60560a2015-04-10 11:31:20 -07003466 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003467
3468 sp<SourceClientDescriptor> sourceDesc =
3469 new SourceClientDescriptor(*portId, uid, *attributes, patchDesc, srcDeviceDesc,
Eric Laurent97ac8712018-07-27 18:59:02 -07003470 streamTypefromAttributesInt(attributes),
3471 getStrategyForAttr(attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07003472
3473 status_t status = connectAudioSource(sourceDesc);
3474 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003475 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003476 }
3477 return status;
3478}
3479
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003480status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003481{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003482 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003483
3484 // make sure we only have one patch per source.
3485 disconnectAudioSource(sourceDesc);
3486
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003487 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003488 routing_strategy strategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003489 audio_stream_type_t stream = sourceDesc->stream();
3490 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->srcDevice();
Eric Laurentd60560a2015-04-10 11:31:20 -07003491
3492 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3493 sp<DeviceDescriptor> sinkDeviceDesc =
3494 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3495
3496 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003497
3498 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3499 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003500 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003501 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3502 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3503 // create patch between src device and output device
3504 // create Hwoutput and add to mHwOutputs
3505 } else {
3506 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3507 audio_io_handle_t output =
3508 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3509 if (output == AUDIO_IO_HANDLE_NONE) {
3510 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3511 return INVALID_OPERATION;
3512 }
3513 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3514 if (outputDesc->isDuplicated()) {
3515 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3516 return INVALID_OPERATION;
3517 }
Eric Laurent733ce942017-12-07 12:18:25 -08003518 status_t status = outputDesc->start();
3519 if (status != NO_ERROR) {
3520 return status;
3521 }
3522
Eric Laurentd60560a2015-04-10 11:31:20 -07003523 // create a special patch with no sink and two sources:
3524 // - the second source indicates to PatchPanel through which output mix this patch should
3525 // be connected as well as the stream type for volume control
3526 // - the sink is defined by whatever output device is currently selected for the output
3527 // though which this patch is routed.
Mikhail Naganovdc769682018-05-04 15:34:08 -07003528 PatchBuilder patchBuilder;
3529 patchBuilder.addSource(srcDeviceDesc).addSource(outputDesc, { .stream = stream });
3530 status = mpClientInterface->createAudioPatch(patchBuilder.patch(),
Eric Laurentd60560a2015-04-10 11:31:20 -07003531 &afPatchHandle,
3532 0);
3533 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3534 status, afPatchHandle);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003535 sourceDesc->patchDesc()->mPatch = *patchBuilder.patch();
Eric Laurentd60560a2015-04-10 11:31:20 -07003536 if (status != NO_ERROR) {
3537 ALOGW("%s patch panel could not connect device patch, error %d",
3538 __FUNCTION__, status);
3539 return INVALID_OPERATION;
3540 }
3541 uint32_t delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07003542 status = startSource(outputDesc, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003543
3544 if (status != NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003545 mpClientInterface->releaseAudioPatch(sourceDesc->patchDesc()->mAfPatchHandle, 0);
Eric Laurentd60560a2015-04-10 11:31:20 -07003546 return status;
3547 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003548 sourceDesc->setSwOutput(outputDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003549 if (delayMs != 0) {
3550 usleep(delayMs * 1000);
3551 }
3552 }
3553
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003554 sourceDesc->patchDesc()->mAfPatchHandle = afPatchHandle;
3555 addAudioPatch(sourceDesc->patchDesc()->mHandle, sourceDesc->patchDesc());
Eric Laurentd60560a2015-04-10 11:31:20 -07003556
3557 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003558}
3559
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003560status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07003561{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003562 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
3563 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003564 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003565 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003566 return BAD_VALUE;
3567 }
3568 status_t status = disconnectAudioSource(sourceDesc);
3569
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003570 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003571 return status;
3572}
3573
Andy Hung2ddee192015-12-18 17:34:44 -08003574status_t AudioPolicyManager::setMasterMono(bool mono)
3575{
3576 if (mMasterMono == mono) {
3577 return NO_ERROR;
3578 }
3579 mMasterMono = mono;
3580 // if enabling mono we close all offloaded devices, which will invalidate the
3581 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3582 // for recreating the new AudioTrack as non-offloaded PCM.
3583 //
3584 // If disabling mono, we leave all tracks as is: we don't know which clients
3585 // and tracks are able to be recreated as offloaded. The next "song" should
3586 // play back offloaded.
3587 if (mMasterMono) {
3588 Vector<audio_io_handle_t> offloaded;
3589 for (size_t i = 0; i < mOutputs.size(); ++i) {
3590 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3591 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3592 offloaded.push(desc->mIoHandle);
3593 }
3594 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003595 for (const auto& handle : offloaded) {
3596 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003597 }
3598 }
3599 // update master mono for all remaining outputs
3600 for (size_t i = 0; i < mOutputs.size(); ++i) {
3601 updateMono(mOutputs.keyAt(i));
3602 }
3603 return NO_ERROR;
3604}
3605
3606status_t AudioPolicyManager::getMasterMono(bool *mono)
3607{
3608 *mono = mMasterMono;
3609 return NO_ERROR;
3610}
3611
Eric Laurentac9cef52017-06-09 15:46:26 -07003612float AudioPolicyManager::getStreamVolumeDB(
3613 audio_stream_type_t stream, int index, audio_devices_t device)
3614{
3615 return computeVolume(stream, index, device);
3616}
3617
jiabin81772902018-04-02 17:52:27 -07003618status_t AudioPolicyManager::getSupportedFormats(audio_io_handle_t ioHandle,
3619 FormatVector& formats) {
3620 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
3621 return BAD_VALUE;
3622 }
3623 String8 reply;
3624 reply = mpClientInterface->getParameters(
3625 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
3626 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
3627 AudioParameter repliedParameters(reply);
3628 if (repliedParameters.get(
3629 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
3630 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
3631 return BAD_VALUE;
3632 }
3633 for (auto format : formatsFromString(reply.string())) {
3634 // Only AUDIO_FORMAT_AAC_LC will be used in Settings UI for all AAC formats.
3635 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3636 if (format == AAC_FORMATS[i]) {
3637 format = AUDIO_FORMAT_AAC_LC;
3638 break;
3639 }
3640 }
3641 bool exist = false;
3642 for (size_t i = 0; i < formats.size(); i++) {
3643 if (format == formats[i]) {
3644 exist = true;
3645 break;
3646 }
3647 }
3648 bool isSurroundFormat = false;
3649 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3650 if (SURROUND_FORMATS[i] == format) {
3651 isSurroundFormat = true;
3652 break;
3653 }
3654 }
3655 if (!exist && isSurroundFormat) {
3656 formats.add(format);
3657 }
3658 }
3659 return NO_ERROR;
3660}
3661
3662status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3663 audio_format_t *surroundFormats,
3664 bool *surroundFormatsEnabled,
3665 bool reported)
3666{
3667 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3668 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3669 return BAD_VALUE;
3670 }
3671 ALOGV("getSurroundFormats() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
3672 *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
3673
3674 // Only return value if there is HDMI output.
3675 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3676 return INVALID_OPERATION;
3677 }
3678
3679 size_t formatsWritten = 0;
3680 size_t formatsMax = *numSurroundFormats;
3681 *numSurroundFormats = 0;
3682 FormatVector formats;
3683 if (reported) {
3684 // Only get surround formats which are reported by device.
3685 // First list already open outputs that can be routed to this device
3686 audio_devices_t device = AUDIO_DEVICE_OUT_HDMI;
3687 SortedVector<audio_io_handle_t> outputs;
3688 bool reportedFormatFound = false;
3689 status_t status;
3690 sp<SwAudioOutputDescriptor> desc;
3691 for (size_t i = 0; i < mOutputs.size(); i++) {
3692 desc = mOutputs.valueAt(i);
3693 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
3694 outputs.add(mOutputs.keyAt(i));
3695 }
3696 }
3697 // Open an output to query dynamic parameters.
Mikhail Naganov708e0382018-05-30 09:53:04 -07003698 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003699 AUDIO_DEVICE_OUT_HDMI);
3700 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3701 String8 address = hdmiOutputDevices[i]->mAddress;
3702 for (const auto& hwModule : mHwModules) {
3703 for (size_t i = 0; i < hwModule->getOutputProfiles().size(); i++) {
3704 sp<IOProfile> profile = hwModule->getOutputProfiles()[i];
3705 if (profile->supportDevice(AUDIO_DEVICE_OUT_HDMI) &&
3706 profile->supportDeviceAddress(address)) {
3707 size_t j;
3708 for (j = 0; j < outputs.size(); j++) {
3709 desc = mOutputs.valueFor(outputs.itemAt(j));
3710 if (!desc->isDuplicated() && desc->mProfile == profile) {
3711 break;
3712 }
3713 }
3714 if (j != outputs.size()) {
3715 status = getSupportedFormats(outputs.itemAt(j), formats);
3716 reportedFormatFound |= (status == NO_ERROR);
3717 continue;
3718 }
3719
3720 if (!profile->canOpenNewIo()) {
3721 ALOGW("Max Output number %u already opened for this profile %s",
3722 profile->maxOpenCount, profile->getTagName().c_str());
3723 continue;
3724 }
3725
3726 ALOGV("opening output for device %08x with params %s profile %p name %s",
3727 device, address.string(), profile.get(), profile->getName().string());
3728 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
3729 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3730 status_t status = desc->open(nullptr, device, address,
3731 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE,
3732 &output);
3733
3734 if (status == NO_ERROR) {
3735 status = getSupportedFormats(output, formats);
3736 reportedFormatFound |= (status == NO_ERROR);
3737 desc->close();
3738 output = AUDIO_IO_HANDLE_NONE;
3739 }
3740 }
3741 }
3742 }
3743 }
3744
3745 if (!reportedFormatFound) {
3746 return UNKNOWN_ERROR;
3747 }
3748 } else {
3749 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3750 formats.add(SURROUND_FORMATS[i]);
3751 }
3752 }
3753 for (size_t i = 0; i < formats.size(); i++) {
3754 if (formatsWritten < formatsMax) {
3755 surroundFormats[formatsWritten] = formats[i];
3756 bool formatEnabled = false;
3757 if (formats[i] == AUDIO_FORMAT_AAC_LC) {
3758 for (size_t j = 0; j < ARRAY_SIZE(AAC_FORMATS); j++) {
3759 formatEnabled =
3760 mSurroundFormats.find(AAC_FORMATS[i]) != mSurroundFormats.end();
3761 break;
3762 }
3763 } else {
3764 formatEnabled = mSurroundFormats.find(formats[i]) != mSurroundFormats.end();
3765 }
3766 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3767 }
3768 (*numSurroundFormats)++;
3769 }
3770 return NO_ERROR;
3771}
3772
3773status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3774{
3775 // Check if audio format is a surround formats.
3776 bool isSurroundFormat = false;
3777 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3778 if (audioFormat == SURROUND_FORMATS[i]) {
3779 isSurroundFormat = true;
3780 break;
3781 }
3782 }
3783 if (!isSurroundFormat) {
3784 return BAD_VALUE;
3785 }
3786
3787 // Should only be called when MANUAL.
3788 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3789 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
3790 if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3791 return INVALID_OPERATION;
3792 }
3793
3794 if ((mSurroundFormats.find(audioFormat) != mSurroundFormats.end() && enabled)
3795 || (mSurroundFormats.find(audioFormat) == mSurroundFormats.end() && !enabled)) {
3796 return NO_ERROR;
3797 }
3798
3799 // The operation is valid only when there is HDMI output available.
3800 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3801 return INVALID_OPERATION;
3802 }
3803
3804 if (enabled) {
3805 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3806 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3807 mSurroundFormats.insert(AAC_FORMATS[i]);
3808 }
3809 } else {
3810 mSurroundFormats.insert(audioFormat);
3811 }
3812 } else {
3813 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3814 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3815 mSurroundFormats.erase(AAC_FORMATS[i]);
3816 }
3817 } else {
3818 mSurroundFormats.erase(audioFormat);
3819 }
3820 }
3821
3822 sp<SwAudioOutputDescriptor> outputDesc;
3823 bool profileUpdated = false;
Mikhail Naganov708e0382018-05-30 09:53:04 -07003824 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003825 AUDIO_DEVICE_OUT_HDMI);
3826 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3827 // Simulate reconnection to update enabled surround sound formats.
3828 String8 address = hdmiOutputDevices[i]->mAddress;
3829 String8 name = hdmiOutputDevices[i]->getName();
3830 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3831 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3832 address.c_str(),
3833 name.c_str());
3834 if (status != NO_ERROR) {
3835 continue;
3836 }
3837 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3838 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3839 address.c_str(),
3840 name.c_str());
3841 profileUpdated |= (status == NO_ERROR);
3842 }
Mikhail Naganov708e0382018-05-30 09:53:04 -07003843 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003844 AUDIO_DEVICE_IN_HDMI);
3845 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3846 // Simulate reconnection to update enabled surround sound formats.
3847 String8 address = hdmiInputDevices[i]->mAddress;
3848 String8 name = hdmiInputDevices[i]->getName();
3849 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3850 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3851 address.c_str(),
3852 name.c_str());
3853 if (status != NO_ERROR) {
3854 continue;
3855 }
3856 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3857 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3858 address.c_str(),
3859 name.c_str());
3860 profileUpdated |= (status == NO_ERROR);
3861 }
3862
3863 // Undo the surround formats change due to no audio profiles updated.
3864 if (!profileUpdated) {
3865 if (enabled) {
3866 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3867 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3868 mSurroundFormats.erase(AAC_FORMATS[i]);
3869 }
3870 } else {
3871 mSurroundFormats.erase(audioFormat);
3872 }
3873 } else {
3874 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3875 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3876 mSurroundFormats.insert(AAC_FORMATS[i]);
3877 }
3878 } else {
3879 mSurroundFormats.insert(audioFormat);
3880 }
3881 }
3882 }
3883
3884 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3885}
3886
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003887void AudioPolicyManager::setRecordSilenced(uid_t uid, bool silenced)
3888{
3889 ALOGV("AudioPolicyManager:setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
3890
3891 Vector<sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
3892 for (size_t i = 0; i < activeInputs.size(); i++) {
3893 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
3894 AudioSessionCollection activeSessions = activeDesc->getAudioSessions(true);
3895 for (size_t j = 0; j < activeSessions.size(); j++) {
3896 sp<AudioSession> activeSession = activeSessions.valueAt(j);
3897 if (activeSession->uid() == uid) {
3898 activeSession->setSilenced(silenced);
3899 }
3900 }
3901 }
3902}
3903
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003904status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003905{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003906 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003907
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003908 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003909 if (patchDesc == 0) {
3910 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003911 sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003912 return BAD_VALUE;
3913 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003914 removeAudioPatch(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003915
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003916 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003917 if (swOutputDesc != 0) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003918 status_t status = stopSource(swOutputDesc, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08003919 if (status == NO_ERROR) {
3920 swOutputDesc->stop();
3921 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003922 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3923 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003924 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003925 if (hwOutputDesc != 0) {
3926 // release patch between src device and output device
3927 // close Hwoutput and remove from mHwOutputs
3928 } else {
3929 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3930 }
3931 }
3932 return NO_ERROR;
3933}
3934
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003935sp<SourceClientDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
Eric Laurentd60560a2015-04-10 11:31:20 -07003936 audio_io_handle_t output, routing_strategy strategy)
3937{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003938 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07003939 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003940 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3941 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003942 routing_strategy sourceStrategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003943 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003944 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3945 source = sourceDesc;
3946 break;
3947 }
3948 }
3949 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003950}
3951
Eric Laurente552edb2014-03-10 17:42:56 -07003952// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003953// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003954// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003955uint32_t AudioPolicyManager::nextAudioPortGeneration()
3956{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003957 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003958}
3959
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003960#ifdef USE_XML_AUDIO_POLICY_CONF
3961// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3962static const char *kConfigLocationList[] =
3963 {"/odm/etc", "/vendor/etc", "/system/etc"};
3964static const int kConfigLocationListSize =
3965 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3966
3967static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3968 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07003969 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003970 status_t ret;
3971
Petri Gyntherf497f292018-04-17 18:46:10 -07003972 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
3973 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
3974 // A2DP offload supported but disabled: try to use special XML file
3975 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
3976 }
3977 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3978
3979 for (const char* fileName : fileNames) {
3980 for (int i = 0; i < kConfigLocationListSize; i++) {
3981 PolicySerializer serializer;
3982 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
3983 "%s/%s", kConfigLocationList[i], fileName);
3984 ret = serializer.deserialize(audioPolicyXmlConfigFile, config);
3985 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003986 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07003987 return ret;
3988 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003989 }
3990 }
3991 return ret;
3992}
3993#endif
3994
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003995AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
3996 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07003997 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07003998 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003999 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07004000 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07004001 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004002#ifdef USE_XML_AUDIO_POLICY_CONF
4003 mVolumeCurves(new VolumeCurvesCollection()),
4004 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08004005 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004006#else
4007 mVolumeCurves(new StreamDescriptorCollection()),
4008 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
4009 mDefaultOutputDevice),
4010#endif
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004011 mAudioPortGeneration(1),
4012 mBeaconMuteRefCount(0),
4013 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07004014 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08004015 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07004016 mMasterMono(false),
Chris Thornton2b864642017-06-27 21:26:07 -07004017 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE),
4018 mHasComputedSoundTriggerSupportsConcurrentCapture(false)
Eric Laurente552edb2014-03-10 17:42:56 -07004019{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004020}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004021
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004022AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
4023 : AudioPolicyManager(clientInterface, false /*forTesting*/)
4024{
4025 loadConfig();
4026 initialize();
4027}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004028
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004029void AudioPolicyManager::loadConfig() {
François Gaffied1ab2bd2015-12-02 18:20:06 +01004030#ifdef USE_XML_AUDIO_POLICY_CONF
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004031 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01004032#else
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004033 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, getConfig()) != NO_ERROR)
4034 && (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, getConfig()) != NO_ERROR)) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01004035#endif
4036 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004037 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01004038 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004039}
4040
4041status_t AudioPolicyManager::initialize() {
4042 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01004043
4044 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01004045 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
4046 if (!engineInstance) {
4047 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004048 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01004049 }
4050 // Retrieve the Policy Manager Interface
4051 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
4052 if (mEngine == NULL) {
4053 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004054 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01004055 }
4056 mEngine->setObserver(this);
4057 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004058 if (status != NO_ERROR) {
4059 LOG_FATAL("Policy engine not initialized(err=%d)", status);
4060 return status;
4061 }
François Gaffie2110e042015-03-24 08:41:51 +01004062
Eric Laurent3a4311c2014-03-17 12:00:47 -07004063 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07004064 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07004065 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
4066 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Mikhail Naganovd4120142017-12-06 15:49:22 -08004067 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004068 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08004069 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
4070 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07004071 continue;
4072 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08004073 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07004074 // open all output streams needed to access attached devices
4075 // except for direct output streams that are only opened when they are actually
4076 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07004077 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004078 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004079 if (!outProfile->canOpenNewIo()) {
4080 ALOGE("Invalid Output profile max open count %u for profile %s",
4081 outProfile->maxOpenCount, outProfile->getTagName().c_str());
4082 continue;
4083 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004084 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004085 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004086 continue;
4087 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004088 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004089 mTtsOutputAvailable = true;
4090 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004091
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004092 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07004093 continue;
4094 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004095 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01004096 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
4097 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07004098 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004099 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07004100 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004101 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07004102 }
Eric Laurentd78f1532014-09-16 16:38:20 -07004103 if ((profileType & outputDeviceTypes) == 0) {
4104 continue;
4105 }
Eric Laurentc75307b2015-03-17 15:29:32 -07004106 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
4107 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07004108 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov708e0382018-05-30 09:53:04 -07004109 const DeviceVector &devicesForType = supportedDevices.getDevicesFromTypeMask(
4110 profileType);
Eric Laurentc40d9692016-04-13 19:14:13 -07004111 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
4112 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07004113 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004114 status_t status = outputDesc->open(nullptr, profileType, address,
4115 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07004116
4117 if (status != NO_ERROR) {
4118 ALOGW("Cannot open output stream for device %08x on hw module %s",
4119 outputDesc->mDevice,
Mikhail Naganovd4120142017-12-06 15:49:22 -08004120 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07004121 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004122 for (const auto& dev : supportedDevices) {
4123 ssize_t index = mAvailableOutputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07004124 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08004125 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004126 mAvailableOutputDevices[index]->attach(hwModule);
Eric Laurentd78f1532014-09-16 16:38:20 -07004127 }
4128 }
4129 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004130 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004131 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07004132 }
4133 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07004134 setOutputDevice(outputDesc,
Eric Laurentfe231122017-11-17 17:48:06 -08004135 profileType,
Eric Laurentc40d9692016-04-13 19:14:13 -07004136 true,
4137 0,
4138 NULL,
Eric Laurentfe231122017-11-17 17:48:06 -08004139 address);
Eric Laurentd78f1532014-09-16 16:38:20 -07004140 }
Eric Laurente552edb2014-03-10 17:42:56 -07004141 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004142 // open input streams needed to access attached devices to validate
4143 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004144 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004145 if (!inProfile->canOpenNewIo()) {
4146 ALOGE("Invalid Input profile max open count %u for profile %s",
4147 inProfile->maxOpenCount, inProfile->getTagName().c_str());
4148 continue;
4149 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004150 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004151 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004152 continue;
4153 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004154 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07004155 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004156 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
4157
Eric Laurentd78f1532014-09-16 16:38:20 -07004158 if ((profileType & inputDeviceTypes) == 0) {
4159 continue;
4160 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08004161 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08004162 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004163
Mikhail Naganov708e0382018-05-30 09:53:04 -07004164 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(profileType);
Eric Laurent53b810e2017-12-10 17:25:10 -08004165 // the inputs vector must be of size >= 1, but we don't want to crash here
4166 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
4167 : String8("");
4168 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
4169 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
4170
Eric Laurentd78f1532014-09-16 16:38:20 -07004171 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004172 status_t status = inputDesc->open(nullptr,
4173 profileType,
Eric Laurent53b810e2017-12-10 17:25:10 -08004174 address,
Eric Laurentfe231122017-11-17 17:48:06 -08004175 AUDIO_SOURCE_MIC,
4176 AUDIO_INPUT_FLAG_NONE,
4177 &input);
Eric Laurentd78f1532014-09-16 16:38:20 -07004178
4179 if (status == NO_ERROR) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004180 for (const auto& dev : inProfile->getSupportedDevices()) {
4181 ssize_t index = mAvailableInputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07004182 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07004183 if (index >= 0) {
4184 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
4185 if (!devDesc->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004186 devDesc->attach(hwModule);
Eric Laurent83efe1c2017-07-09 16:51:08 -07004187 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07004188 }
Eric Laurentd78f1532014-09-16 16:38:20 -07004189 }
4190 }
Eric Laurentfe231122017-11-17 17:48:06 -08004191 inputDesc->close();
Eric Laurentd78f1532014-09-16 16:38:20 -07004192 } else {
4193 ALOGW("Cannot open input stream for device %08x on hw module %s",
Eric Laurentfe231122017-11-17 17:48:06 -08004194 profileType,
Mikhail Naganovd4120142017-12-06 15:49:22 -08004195 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07004196 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004197 }
4198 }
4199 // make sure all attached devices have been allocated a unique ID
4200 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004201 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004202 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004203 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
4204 continue;
4205 }
François Gaffie2110e042015-03-24 08:41:51 +01004206 // The device is now validated and can be appended to the available devices of the engine
4207 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
4208 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004209 i++;
4210 }
4211 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004212 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01004213 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004214 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
4215 continue;
4216 }
François Gaffie2110e042015-03-24 08:41:51 +01004217 // The device is now validated and can be appended to the available devices of the engine
4218 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
4219 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004220 i++;
4221 }
4222 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004223 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01004224 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004225 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004226 }
jiabin9ff780e2018-03-19 18:19:52 -07004227 // If microphones address is empty, set it according to device type
4228 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
4229 if (mAvailableInputDevices[i]->mAddress.isEmpty()) {
4230 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
4231 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
4232 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
4233 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BACK_MICROPHONE_ADDRESS);
4234 }
4235 }
4236 }
Eric Laurente552edb2014-03-10 17:42:56 -07004237
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004238 if (mPrimaryOutput == 0) {
4239 ALOGE("Failed to open primary output");
4240 status = NO_INIT;
4241 }
Eric Laurente552edb2014-03-10 17:42:56 -07004242
4243 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004244 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004245}
4246
Eric Laurente0720872014-03-11 09:30:41 -07004247AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004248{
Eric Laurente552edb2014-03-10 17:42:56 -07004249 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004250 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004251 }
4252 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004253 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004254 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004255 mAvailableOutputDevices.clear();
4256 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004257 mOutputs.clear();
4258 mInputs.clear();
4259 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004260 mHwModulesAll.clear();
jiabin81772902018-04-02 17:52:27 -07004261 mSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004262}
4263
Eric Laurente0720872014-03-11 09:30:41 -07004264status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004265{
Eric Laurent87ffa392015-05-22 10:32:38 -07004266 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004267}
4268
Eric Laurente552edb2014-03-10 17:42:56 -07004269// ---
4270
Eric Laurent98e38192018-02-15 18:31:53 -08004271void AudioPolicyManager::addOutput(audio_io_handle_t output,
4272 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004273{
Eric Laurent1c333e22014-05-20 10:48:17 -07004274 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08004275 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004276 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004277 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004278 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004279}
4280
François Gaffie53615e22015-03-19 09:24:12 +01004281void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4282{
4283 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004284 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004285}
4286
Eric Laurent98e38192018-02-15 18:31:53 -08004287void AudioPolicyManager::addInput(audio_io_handle_t input,
4288 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004289{
Eric Laurent1c333e22014-05-20 10:48:17 -07004290 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004291 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004292}
Eric Laurente552edb2014-03-10 17:42:56 -07004293
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004294void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08004295 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004296 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004297 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08004298 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004299 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08004300 if (devDesc != 0) {
4301 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
4302 desc->mIoHandle, address.string());
4303 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004304 }
4305}
4306
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004307status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004308 audio_policy_dev_state_t state,
4309 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004310 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07004311{
François Gaffie53615e22015-03-19 09:24:12 +01004312 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07004313 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004314
4315 if (audio_device_is_digital(device)) {
4316 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004317 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004318 }
Eric Laurente552edb2014-03-10 17:42:56 -07004319
Eric Laurent3b73df72014-03-11 09:06:29 -07004320 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004321 // first list already open outputs that can be routed to this device
4322 for (size_t i = 0; i < mOutputs.size(); i++) {
4323 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07004324 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004325 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004326 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
4327 outputs.add(mOutputs.keyAt(i));
4328 } else {
4329 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08004330 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004331 }
Eric Laurente552edb2014-03-10 17:42:56 -07004332 }
4333 }
4334 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004335 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004336 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004337 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4338 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004339 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004340 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004341 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004342 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004343 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4344 j, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004345 }
Eric Laurente552edb2014-03-10 17:42:56 -07004346 }
4347 }
4348 }
4349
Eric Laurent7b279bb2015-12-14 10:18:23 -08004350 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004351
Eric Laurente552edb2014-03-10 17:42:56 -07004352 if (profiles.isEmpty() && outputs.isEmpty()) {
4353 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4354 return BAD_VALUE;
4355 }
4356
4357 // open outputs for matching profiles if needed. Direct outputs are also opened to
4358 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4359 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004360 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004361
4362 // nothing to do if one output is already opened for this profile
4363 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004364 for (j = 0; j < outputs.size(); j++) {
4365 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004366 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004367 // matching profile: save the sample rates, format and channel masks supported
4368 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07004369 if (audio_device_is_digital(device)) {
4370 devDesc->importAudioPort(profile);
4371 }
Eric Laurente552edb2014-03-10 17:42:56 -07004372 break;
4373 }
4374 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004375 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004376 continue;
4377 }
4378
Eric Laurent3974e3b2017-12-07 17:58:43 -08004379 if (!profile->canOpenNewIo()) {
4380 ALOGW("Max Output number %u already opened for this profile %s",
4381 profile->maxOpenCount, profile->getTagName().c_str());
4382 continue;
4383 }
4384
Eric Laurent83efe1c2017-07-09 16:51:08 -07004385 ALOGV("opening output for device %08x with params %s profile %p name %s",
4386 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004387 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004388 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004389 status_t status = desc->open(nullptr, device, address,
4390 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004391
Eric Laurentfe231122017-11-17 17:48:06 -08004392 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004393 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004394 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004395 char *param = audio_device_address_to_parameter(device, address);
4396 mpClientInterface->setParameters(output, String8(param));
4397 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004398 }
Phil Burk00eeb322016-03-31 12:41:00 -07004399 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004400 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004401 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004402 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004403 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004404 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004405 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004406 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004407 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4408 profile->pickAudioProfile(
4409 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004410 config.offload_info.sample_rate = config.sample_rate;
4411 config.offload_info.channel_mask = config.channel_mask;
4412 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004413
4414 status_t status = desc->open(&config, device, address, AUDIO_STREAM_DEFAULT,
4415 AUDIO_OUTPUT_FLAG_NONE, &output);
4416 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004417 output = AUDIO_IO_HANDLE_NONE;
4418 }
Eric Laurentd4692962014-05-05 18:13:44 -07004419 }
4420
Eric Laurentcf2c0212014-07-25 16:20:43 -07004421 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004422 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01004423 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004424 sp<AudioPolicyMix> policyMix;
4425 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004426 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
4427 address.string());
4428 }
François Gaffie036e1e92015-03-19 10:16:24 +01004429 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07004430 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01004431
Eric Laurent87ffa392015-05-22 10:32:38 -07004432 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4433 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004434 // no duplicated output for direct outputs and
4435 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004436 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004437
Eric Laurentd4692962014-05-05 18:13:44 -07004438 //TODO: configure audio effect output stage here
4439
4440 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004441 sp<SwAudioOutputDescriptor> dupOutputDesc =
4442 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4443 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4444 &duplicatedOutput);
4445 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004446 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004447 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004448 } else {
4449 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004450 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004451 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004452 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004453 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004454 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004455 }
Eric Laurente552edb2014-03-10 17:42:56 -07004456 }
4457 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004458 } else {
4459 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004460 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004461 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004462 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004463 profiles.removeAt(profile_index);
4464 profile_index--;
4465 } else {
4466 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004467 // Load digital format info only for digital devices
4468 if (audio_device_is_digital(device)) {
4469 devDesc->importAudioPort(profile);
4470 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004471
François Gaffie53615e22015-03-19 09:24:12 +01004472 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004473 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4474 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004475 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004476 NULL/*patch handle*/, address.string());
4477 }
Eric Laurente552edb2014-03-10 17:42:56 -07004478 ALOGV("checkOutputsForDevice(): adding output %d", output);
4479 }
4480 }
4481
4482 if (profiles.isEmpty()) {
4483 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4484 return BAD_VALUE;
4485 }
Eric Laurentd4692962014-05-05 18:13:44 -07004486 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004487 // check if one opened output is not needed any more after disconnecting one device
4488 for (size_t i = 0; i < mOutputs.size(); i++) {
4489 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004490 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004491 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004492 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004493 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004494 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004495 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004496 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4497 mOutputs.keyAt(i));
4498 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004499 }
Eric Laurente552edb2014-03-10 17:42:56 -07004500 }
4501 }
Eric Laurentd4692962014-05-05 18:13:44 -07004502 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004503 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004504 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4505 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004506 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004507 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004508 "clearing direct output profile %zu on module %s",
4509 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004510 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004511 }
4512 }
4513 }
4514 }
4515 return NO_ERROR;
4516}
4517
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004518status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004519 audio_policy_dev_state_t state,
4520 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004521 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004522{
Paul McLean9080a4c2015-06-18 08:24:02 -07004523 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004524 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004525
4526 if (audio_device_is_digital(device)) {
4527 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004528 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004529 }
4530
Eric Laurentd4692962014-05-05 18:13:44 -07004531 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4532 // first list already open inputs that can be routed to this device
4533 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4534 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004535 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004536 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4537 inputs.add(mInputs.keyAt(input_index));
4538 }
4539 }
4540
4541 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004542 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004543 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004544 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004545 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004546 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004547 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004548
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004549 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004550 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004551 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004552 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004553 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4554 profile_index, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004555 }
Eric Laurentd4692962014-05-05 18:13:44 -07004556 }
4557 }
4558 }
4559
4560 if (profiles.isEmpty() && inputs.isEmpty()) {
4561 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4562 return BAD_VALUE;
4563 }
4564
4565 // open inputs for matching profiles if needed. Direct inputs are also opened to
4566 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4567 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4568
Eric Laurent1c333e22014-05-20 10:48:17 -07004569 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004570
Eric Laurentd4692962014-05-05 18:13:44 -07004571 // nothing to do if one input is already opened for this profile
4572 size_t input_index;
4573 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4574 desc = mInputs.valueAt(input_index);
4575 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004576 if (audio_device_is_digital(device)) {
4577 devDesc->importAudioPort(profile);
4578 }
Eric Laurentd4692962014-05-05 18:13:44 -07004579 break;
4580 }
4581 }
4582 if (input_index != mInputs.size()) {
4583 continue;
4584 }
4585
Eric Laurent3974e3b2017-12-07 17:58:43 -08004586 if (!profile->canOpenNewIo()) {
4587 ALOGW("Max Input number %u already opened for this profile %s",
4588 profile->maxOpenCount, profile->getTagName().c_str());
4589 continue;
4590 }
4591
Eric Laurentfe231122017-11-17 17:48:06 -08004592 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004593 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004594 status_t status = desc->open(nullptr,
4595 device,
4596 address,
4597 AUDIO_SOURCE_MIC,
4598 AUDIO_INPUT_FLAG_NONE,
4599 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004600
Eric Laurentcf2c0212014-07-25 16:20:43 -07004601 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004602 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004603 char *param = audio_device_address_to_parameter(device, address);
4604 mpClientInterface->setParameters(input, String8(param));
4605 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004606 }
Phil Burk00eeb322016-03-31 12:41:00 -07004607 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004608 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004609 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004610 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004611 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004612 }
4613
4614 if (input != 0) {
4615 addInput(input, desc);
4616 }
4617 } // endif input != 0
4618
Eric Laurentcf2c0212014-07-25 16:20:43 -07004619 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004620 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004621 profiles.removeAt(profile_index);
4622 profile_index--;
4623 } else {
4624 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004625 if (audio_device_is_digital(device)) {
4626 devDesc->importAudioPort(profile);
4627 }
Eric Laurentd4692962014-05-05 18:13:44 -07004628 ALOGV("checkInputsForDevice(): adding input %d", input);
4629 }
4630 } // end scan profiles
4631
4632 if (profiles.isEmpty()) {
4633 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4634 return BAD_VALUE;
4635 }
4636 } else {
4637 // Disconnect
4638 // check if one opened input is not needed any more after disconnecting one device
4639 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4640 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004641 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004642 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4643 mInputs.keyAt(input_index));
4644 inputs.add(mInputs.keyAt(input_index));
4645 }
4646 }
4647 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004648 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004649 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004650 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004651 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004652 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004653 if (profile->supportDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004654 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4655 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004656 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004657 }
4658 }
4659 }
4660 } // end disconnect
4661
4662 return NO_ERROR;
4663}
4664
4665
Eric Laurente0720872014-03-11 09:30:41 -07004666void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004667{
4668 ALOGV("closeOutput(%d)", output);
4669
Eric Laurentc75307b2015-03-17 15:29:32 -07004670 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004671 if (outputDesc == NULL) {
4672 ALOGW("closeOutput() unknown output %d", output);
4673 return;
4674 }
François Gaffie036e1e92015-03-19 10:16:24 +01004675 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004676
Eric Laurente552edb2014-03-10 17:42:56 -07004677 // look for duplicated outputs connected to the output being removed.
4678 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004679 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004680 if (dupOutputDesc->isDuplicated() &&
4681 (dupOutputDesc->mOutput1 == outputDesc ||
4682 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004683 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004684 if (dupOutputDesc->mOutput1 == outputDesc) {
4685 outputDesc2 = dupOutputDesc->mOutput2;
4686 } else {
4687 outputDesc2 = dupOutputDesc->mOutput1;
4688 }
4689 // As all active tracks on duplicated output will be deleted,
4690 // and as they were also referenced on the other output, the reference
4691 // count for their stream type must be adjusted accordingly on
4692 // the other output.
Eric Laurent733ce942017-12-07 12:18:25 -08004693 bool wasActive = outputDesc2->isActive();
Eric Laurent3b73df72014-03-11 09:06:29 -07004694 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004695 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07004696 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004697 }
Eric Laurent733ce942017-12-07 12:18:25 -08004698 // stop() will be a no op if the output is still active but is needed in case all
4699 // active streams refcounts where cleared above
4700 if (wasActive) {
4701 outputDesc2->stop();
4702 }
Eric Laurente552edb2014-03-10 17:42:56 -07004703 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4704 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4705
4706 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004707 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004708 }
4709 }
4710
Eric Laurent05b90f82014-08-27 15:32:29 -07004711 nextAudioPortGeneration();
4712
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004713 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004714 if (index >= 0) {
4715 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004716 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004717 mAudioPatches.removeItemsAt(index);
4718 mpClientInterface->onAudioPatchListUpdate();
4719 }
4720
Eric Laurentfe231122017-11-17 17:48:06 -08004721 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004722
François Gaffie53615e22015-03-19 09:24:12 +01004723 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004724 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004725}
4726
4727void AudioPolicyManager::closeInput(audio_io_handle_t input)
4728{
4729 ALOGV("closeInput(%d)", input);
4730
4731 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4732 if (inputDesc == NULL) {
4733 ALOGW("closeInput() unknown input %d", input);
4734 return;
4735 }
4736
Eric Laurent6a94d692014-05-20 11:18:06 -07004737 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004738
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004739 audio_devices_t device = inputDesc->mDevice;
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004740 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004741 if (index >= 0) {
4742 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004743 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004744 mAudioPatches.removeItemsAt(index);
4745 mpClientInterface->onAudioPatchListUpdate();
4746 }
4747
Eric Laurentfe231122017-11-17 17:48:06 -08004748 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004749 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004750
4751 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
4752 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
4753 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
4754 SoundTrigger::setCaptureState(false);
4755 }
Eric Laurente552edb2014-03-10 17:42:56 -07004756}
4757
Eric Laurentc75307b2015-03-17 15:29:32 -07004758SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4759 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004760 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004761{
4762 SortedVector<audio_io_handle_t> outputs;
4763
4764 ALOGVV("getOutputsForDevice() device %04x", device);
4765 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004766 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004767 i, openOutputs.valueAt(i)->isDuplicated(),
4768 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004769 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4770 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4771 outputs.add(openOutputs.keyAt(i));
4772 }
4773 }
4774 return outputs;
4775}
4776
Mikhail Naganov37977152018-07-11 15:54:44 -07004777void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
4778{
4779 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
4780 // output is suspended before any tracks are moved to it
4781 checkA2dpSuspend();
4782 checkOutputForAllStrategies();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004783 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07004784 updateDevicesAndOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004785 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
4786 setMsdPatch();
4787 }
Mikhail Naganov37977152018-07-11 15:54:44 -07004788}
4789
Eric Laurente0720872014-03-11 09:30:41 -07004790void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004791{
4792 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4793 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4794 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4795 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4796
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004797 // also take into account external policy-related changes: add all outputs which are
4798 // associated with policies in the "before" and "after" output vectors
4799 ALOGVV("checkOutputForStrategy(): policy related outputs");
4800 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004801 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004802 if (desc != 0 && desc->mPolicyMix != NULL) {
4803 srcOutputs.add(desc->mIoHandle);
4804 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4805 }
4806 }
4807 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004808 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004809 if (desc != 0 && desc->mPolicyMix != NULL) {
4810 dstOutputs.add(desc->mIoHandle);
4811 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4812 }
4813 }
4814
Mikhail Naganov9de8bd12018-07-23 16:41:31 -07004815 if (srcOutputs != dstOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004816 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4817 // audio from invalidated tracks will be rendered when unmuting
4818 uint32_t maxLatency = 0;
4819 for (audio_io_handle_t srcOut : srcOutputs) {
4820 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4821 if (desc != 0 && maxLatency < desc->latency()) {
4822 maxLatency = desc->latency();
4823 }
4824 }
Eric Laurente552edb2014-03-10 17:42:56 -07004825 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4826 strategy, srcOutputs[0], dstOutputs[0]);
4827 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004828 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004829 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4830 if (desc != 0 && isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004831 setStrategyMute(strategy, true, desc);
Eric Laurentac3a6902018-05-11 16:39:10 -07004832 setStrategyMute(strategy, false, desc, maxLatency * LATENCY_MUTE_FACTOR, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004833 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004834 sp<SourceClientDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004835 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004836 if (source != 0){
4837 connectAudioSource(source);
4838 }
Eric Laurente552edb2014-03-10 17:42:56 -07004839 }
4840
4841 // Move effects associated to this strategy from previous output to new output
4842 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004843 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004844 }
4845 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004846 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004847 if (getStrategy((audio_stream_type_t)i) == strategy) {
4848 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004849 }
4850 }
4851 }
4852}
4853
Eric Laurente0720872014-03-11 09:30:41 -07004854void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004855{
François Gaffie2110e042015-03-24 08:41:51 +01004856 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004857 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004858 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004859 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004860 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004861 checkOutputForStrategy(STRATEGY_SONIFICATION);
4862 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004863 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004864 checkOutputForStrategy(STRATEGY_MEDIA);
4865 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004866 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004867}
4868
Eric Laurente0720872014-03-11 09:30:41 -07004869void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004870{
François Gaffie53615e22015-03-19 09:24:12 +01004871 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004872 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004873 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004874 return;
4875 }
4876
Eric Laurent3a4311c2014-03-17 12:00:47 -07004877 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004878 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4879 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4880 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004881
4882 // if suspended, restore A2DP output if:
4883 // ((SCO device is NOT connected) ||
4884 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4885 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004886 //
Eric Laurentf732e072016-08-03 19:30:28 -07004887 // if not suspended, suspend A2DP output if:
4888 // (SCO device is connected) &&
4889 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4890 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004891 //
4892 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004893 if (!isScoConnected ||
4894 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4895 AUDIO_POLICY_FORCE_BT_SCO) &&
4896 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4897 AUDIO_POLICY_FORCE_BT_SCO) &&
4898 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004899 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004900
4901 mpClientInterface->restoreOutput(a2dpOutput);
4902 mA2dpSuspended = false;
4903 }
4904 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004905 if (isScoConnected &&
4906 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4907 AUDIO_POLICY_FORCE_BT_SCO) ||
4908 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4909 AUDIO_POLICY_FORCE_BT_SCO) ||
4910 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004911 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004912
4913 mpClientInterface->suspendOutput(a2dpOutput);
4914 mA2dpSuspended = true;
4915 }
4916 }
4917}
4918
Eric Laurent97ac8712018-07-27 18:59:02 -07004919template <class IoDescriptor, class Filter>
4920sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4921 IoDescriptor& desc, Filter filter, bool& active, const DeviceVector& devices)
4922{
4923 auto activeClients = desc->clientsList(true /*activeOnly*/);
4924 auto activeClientsWithRoute =
4925 desc->clientsList(true /*activeOnly*/, filter, true /*preferredDevice*/);
4926 active = activeClients.size() > 0;
4927 if (active && activeClients.size() == activeClientsWithRoute.size()) {
4928 return devices.getDeviceFromId(activeClientsWithRoute[0]->preferredDeviceId());
4929 }
4930 return nullptr;
4931}
4932
4933template <class IoCollection, class Filter>
4934sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4935 IoCollection& ioCollection, Filter filter, const DeviceVector& devices)
4936{
4937 sp<DeviceDescriptor> device;
4938 for (size_t i = 0; i < ioCollection.size(); i++) {
4939 auto desc = ioCollection.valueAt(i);
4940 bool active;
4941 sp<DeviceDescriptor> curDevice = findPreferredDevice(desc, filter, active, devices);
4942 if (active && curDevice == nullptr) {
4943 return nullptr;
4944 } else if (curDevice != nullptr) {
4945 device = curDevice;
4946 }
4947 }
4948 return device;
4949}
4950
Eric Laurentc75307b2015-03-17 15:29:32 -07004951audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4952 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004953{
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004954 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004955 if (index >= 0) {
4956 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4957 if (patchDesc->mUid != mUidCached) {
4958 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004959 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004960 return outputDesc->device();
4961 }
4962 }
4963
Eric Laurent97ac8712018-07-27 18:59:02 -07004964 // Honor explicit routing requests only if no client using default routing is active on this
4965 // input: a specific app can not force routing for other apps by setting a preferred device.
4966 bool active; // unused
4967 sp<DeviceDescriptor> deviceDesc =
4968 findPreferredDevice(outputDesc, STRATEGY_NONE, active, mAvailableOutputDevices);
4969 if (deviceDesc != nullptr) {
4970 return deviceDesc->type();
Eric Laurentf3a5a602018-05-22 18:42:55 -07004971 }
4972
Eric Laurente552edb2014-03-10 17:42:56 -07004973 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004974 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004975 // use device for strategy enforced audible
4976 // 2: we are in call or the strategy phone is active on the output:
4977 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004978 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004979 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004980 // 4: the strategy for enforced audible is active but not enforced on the output:
4981 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004982 // 5: the strategy accessibility is active on the output:
4983 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004984 // 6: the strategy "respectful" sonification is active on the output:
4985 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004986 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004987 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004988 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004989 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004990 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004991 // use device for strategy t-t-s
Eric Laurent484e9272018-06-07 17:29:23 -07004992
4993 // FIXME: extend use of isStrategyActiveOnSameModule() to all strategies
4994 // with a refined rule considering mutually exclusive devices (using same backend)
4995 // as opposed to all streams on the same audio HAL module.
Eric Laurent97ac8712018-07-27 18:59:02 -07004996 audio_devices_t device = AUDIO_DEVICE_NONE;
François Gaffiead3183e2015-03-18 16:55:35 +01004997 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004998 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004999 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
5000 } else if (isInCall() ||
Eric Laurent484e9272018-06-07 17:29:23 -07005001 isStrategyActiveOnSameModule(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005002 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
Yung Ti Su3e7eb5e2018-06-13 11:48:42 +08005003 } else if (isStrategyActiveOnSameModule(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005004 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07005005 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
5006 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08005007 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
5008 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01005009 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005010 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01005011 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005012 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01005013 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005014 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01005015 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005016 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01005017 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005018 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07005019 }
5020
Eric Laurent1c333e22014-05-20 10:48:17 -07005021 ALOGV("getNewOutputDevice() selected device %x", device);
5022 return device;
5023}
5024
Eric Laurentfb66dd92016-01-28 18:32:03 -08005025audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07005026{
Eric Laurentfb66dd92016-01-28 18:32:03 -08005027 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005028
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005029 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005030 if (index >= 0) {
5031 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5032 if (patchDesc->mUid != mUidCached) {
5033 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005034 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005035 return inputDesc->mDevice;
5036 }
5037 }
5038
Eric Laurent97ac8712018-07-27 18:59:02 -07005039 // Honor explicit routing requests only if no client using default routing is active on this
5040 // input: a specific app can not force routing for other apps by setting a preferred device.
5041 bool active;
5042 sp<DeviceDescriptor> deviceDesc =
5043 findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
5044 if (deviceDesc != nullptr) {
5045 return deviceDesc->type();
5046 }
5047
Eric Laurentdc95a252018-04-12 12:46:56 -07005048 // If we are not in call and no client is active on this input, this methods returns
5049 // AUDIO_DEVICE_NONE, causing the patch on the input stream to be released.
Eric Laurentfb66dd92016-01-28 18:32:03 -08005050 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
Eric Laurentdc95a252018-04-12 12:46:56 -07005051 if (source == AUDIO_SOURCE_DEFAULT && isInCall()) {
5052 source = AUDIO_SOURCE_VOICE_COMMUNICATION;
5053 }
5054 if (source != AUDIO_SOURCE_DEFAULT) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08005055 device = getDeviceAndMixForInputSource(source);
5056 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005057
Eric Laurente552edb2014-03-10 17:42:56 -07005058 return device;
5059}
5060
Eric Laurent794fde22016-03-11 09:50:45 -08005061bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
5062 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08005063 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08005064}
5065
Eric Laurente0720872014-03-11 09:30:41 -07005066uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005067 return (uint32_t)getStrategy(stream);
5068}
5069
Eric Laurente0720872014-03-11 09:30:41 -07005070audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005071 // By checking the range of stream before calling getStrategy, we avoid
5072 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
5073 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08005074 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005075 return AUDIO_DEVICE_NONE;
5076 }
Eric Laurent28d09f02016-03-08 10:43:05 -08005077 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08005078 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
5079 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08005080 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07005081 }
Eric Laurent794fde22016-03-11 09:50:45 -08005082 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08005083 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07005084 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005085 for (audio_io_handle_t output : getOutputsForDevice(curDevices, mOutputs)) {
5086 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08005087 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08005088 curDevices |= outputDesc->device();
5089 }
5090 }
5091 devices |= curDevices;
Eric Laurente552edb2014-03-10 17:42:56 -07005092 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005093
5094 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
5095 and doesn't really need to.*/
5096 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
5097 devices |= AUDIO_DEVICE_OUT_SPEAKER;
5098 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
5099 }
Eric Laurente552edb2014-03-10 17:42:56 -07005100 return devices;
5101}
5102
François Gaffie2110e042015-03-24 08:41:51 +01005103routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
5104{
Eric Laurent223fd5c2014-11-11 13:43:36 -08005105 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01005106 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005107}
5108
Eric Laurent97ac8712018-07-27 18:59:02 -07005109routing_strategy AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005110 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005111 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
Eric Laurent97ac8712018-07-27 18:59:02 -07005112 return STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005113 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005114 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
Eric Laurent97ac8712018-07-27 18:59:02 -07005115 return STRATEGY_ENFORCED_AUDIBLE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005116 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005117 // usage to strategy mapping
Eric Laurent97ac8712018-07-27 18:59:02 -07005118 return mEngine->getStrategyForUsage(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005119}
5120
Eric Laurente0720872014-03-11 09:30:41 -07005121void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005122 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005123 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07005124 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
5125 updateDevicesAndOutputs();
5126 break;
5127 default:
5128 break;
5129 }
5130}
5131
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005132uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07005133
5134 // skip beacon mute management if a dedicated TTS output is available
5135 if (mTtsOutputAvailable) {
5136 return 0;
5137 }
5138
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005139 switch(event) {
5140 case STARTING_OUTPUT:
5141 mBeaconMuteRefCount++;
5142 break;
5143 case STOPPING_OUTPUT:
5144 if (mBeaconMuteRefCount > 0) {
5145 mBeaconMuteRefCount--;
5146 }
5147 break;
5148 case STARTING_BEACON:
5149 mBeaconPlayingRefCount++;
5150 break;
5151 case STOPPING_BEACON:
5152 if (mBeaconPlayingRefCount > 0) {
5153 mBeaconPlayingRefCount--;
5154 }
5155 break;
5156 }
5157
5158 if (mBeaconMuteRefCount > 0) {
5159 // any playback causes beacon to be muted
5160 return setBeaconMute(true);
5161 } else {
5162 // no other playback: unmute when beacon starts playing, mute when it stops
5163 return setBeaconMute(mBeaconPlayingRefCount == 0);
5164 }
5165}
5166
5167uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5168 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5169 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5170 // keep track of muted state to avoid repeating mute/unmute operations
5171 if (mBeaconMuted != mute) {
5172 // mute/unmute AUDIO_STREAM_TTS on all outputs
5173 ALOGV("\t muting %d", mute);
5174 uint32_t maxLatency = 0;
5175 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005176 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005177 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07005178 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005179 0 /*delay*/, AUDIO_DEVICE_NONE);
5180 const uint32_t latency = desc->latency() * 2;
5181 if (latency > maxLatency) {
5182 maxLatency = latency;
5183 }
5184 }
5185 mBeaconMuted = mute;
5186 return maxLatency;
5187 }
5188 return 0;
5189}
5190
Eric Laurente0720872014-03-11 09:30:41 -07005191audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01005192 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005193{
Eric Laurent97ac8712018-07-27 18:59:02 -07005194 // Honor explicit routing requests only if all active clients have a preferred route in which
5195 // case the last active client route is used
5196 sp<DeviceDescriptor> deviceDesc = findPreferredDevice(mOutputs, strategy, mAvailableOutputDevices);
5197 if (deviceDesc != nullptr) {
5198 return deviceDesc->type();
Paul McLeanaa981192015-03-21 09:55:15 -07005199 }
5200
Eric Laurente552edb2014-03-10 17:42:56 -07005201 if (fromCache) {
5202 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
5203 strategy, mDeviceForStrategy[strategy]);
5204 return mDeviceForStrategy[strategy];
5205 }
François Gaffie2110e042015-03-24 08:41:51 +01005206 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07005207}
5208
Eric Laurente0720872014-03-11 09:30:41 -07005209void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005210{
5211 for (int i = 0; i < NUM_STRATEGIES; i++) {
5212 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
5213 }
5214 mPreviousOutputs = mOutputs;
5215}
5216
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005217uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005218 audio_devices_t prevDevice,
5219 uint32_t delayMs)
5220{
5221 // mute/unmute strategies using an incompatible device combination
5222 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5223 // if unmuting, unmute only after the specified delay
5224 if (outputDesc->isDuplicated()) {
5225 return 0;
5226 }
5227
5228 uint32_t muteWaitMs = 0;
5229 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07005230 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005231
5232 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
5233 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07005234 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07005235 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
5236 bool doMute = false;
5237
5238 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
5239 doMute = true;
5240 outputDesc->mStrategyMutedByDevice[i] = true;
5241 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
5242 doMute = true;
5243 outputDesc->mStrategyMutedByDevice[i] = false;
5244 }
Eric Laurent99401132014-05-07 19:48:15 -07005245 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005246 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005247 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005248 // skip output if it does not share any device with current output
5249 if ((desc->supportedDevices() & outputDesc->supportedDevices())
5250 == AUDIO_DEVICE_NONE) {
5251 continue;
5252 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005253 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07005254 mute ? "muting" : "unmuting", i, curDevice);
5255 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005256 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005257 if (mute) {
5258 // FIXME: should not need to double latency if volume could be applied
5259 // immediately by the audioflinger mixer. We must account for the delay
5260 // between now and the next time the audioflinger thread for this output
5261 // will process a buffer (which corresponds to one buffer size,
5262 // usually 1/2 or 1/4 of the latency).
5263 if (muteWaitMs < desc->latency() * 2) {
5264 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005265 }
5266 }
5267 }
5268 }
5269 }
5270 }
5271
Eric Laurent99401132014-05-07 19:48:15 -07005272 // temporary mute output if device selection changes to avoid volume bursts due to
5273 // different per device volumes
5274 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005275 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5276 // temporary mute duration is conservatively set to 4 times the reported latency
5277 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5278 if (muteWaitMs < tempMuteWaitMs) {
5279 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005280 }
Eric Laurentdc462862016-07-19 12:29:53 -07005281
Eric Laurent99401132014-05-07 19:48:15 -07005282 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005283 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005284 // make sure that we do not start the temporary mute period too early in case of
5285 // delayed device change
5286 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005287 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07005288 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07005289 }
5290 }
5291 }
5292
Eric Laurente552edb2014-03-10 17:42:56 -07005293 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5294 if (muteWaitMs > delayMs) {
5295 muteWaitMs -= delayMs;
5296 usleep(muteWaitMs * 1000);
5297 return muteWaitMs;
5298 }
5299 return 0;
5300}
5301
Eric Laurentc75307b2015-03-17 15:29:32 -07005302uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005303 audio_devices_t device,
5304 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07005305 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005306 audio_patch_handle_t *patchHandle,
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005307 const char *address,
5308 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005309{
Eric Laurentc75307b2015-03-17 15:29:32 -07005310 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005311 AudioParameter param;
5312 uint32_t muteWaitMs;
5313
5314 if (outputDesc->isDuplicated()) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005315 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs,
5316 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
5317 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs,
5318 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005319 return muteWaitMs;
5320 }
5321 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5322 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07005323 if ((device != AUDIO_DEVICE_NONE) &&
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005324 ((device & outputDesc->supportedDevices()) == AUDIO_DEVICE_NONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005325 return 0;
5326 }
5327
5328 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07005329 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07005330
5331 audio_devices_t prevDevice = outputDesc->mDevice;
5332
Paul McLeanaa981192015-03-21 09:55:15 -07005333 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005334
5335 if (device != AUDIO_DEVICE_NONE) {
5336 outputDesc->mDevice = device;
5337 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005338
5339 // if the outputs are not materially active, there is no need to mute.
5340 if (requiresMuteCheck) {
5341 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
5342 } else {
5343 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5344 muteWaitMs = 0;
5345 }
Eric Laurente552edb2014-03-10 17:42:56 -07005346
5347 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005348 // the requested device is AUDIO_DEVICE_NONE
5349 // OR the requested device is the same as current device
5350 // AND force is not specified
5351 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07005352 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07005353 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
5354 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005355 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005356 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005357 return muteWaitMs;
5358 }
5359
5360 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07005361
Eric Laurente552edb2014-03-10 17:42:56 -07005362 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07005363 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005364 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005365 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07005366 DeviceVector deviceList;
5367 if ((address == NULL) || (strlen(address) == 0)) {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005368 deviceList = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurentc40d9692016-04-13 19:14:13 -07005369 } else {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005370 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
5371 device, String8(address));
5372 if (deviceDesc) deviceList.add(deviceDesc);
Eric Laurentc40d9692016-04-13 19:14:13 -07005373 }
5374
Eric Laurent1c333e22014-05-20 10:48:17 -07005375 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005376 PatchBuilder patchBuilder;
5377 patchBuilder.addSource(outputDesc);
Eric Laurent1c333e22014-05-20 10:48:17 -07005378 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005379 patchBuilder.addSink(deviceList.itemAt(i));
Eric Laurent1c333e22014-05-20 10:48:17 -07005380 }
Mikhail Naganovdc769682018-05-04 15:34:08 -07005381 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005382 }
bryant_liuf5e7e792014-08-19 20:07:05 +08005383
5384 // inform all input as well
5385 for (size_t i = 0; i < mInputs.size(); i++) {
5386 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01005387 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08005388 AudioParameter inputCmd = AudioParameter();
5389 ALOGV("%s: inform input %d of device:%d", __func__,
5390 inputDescriptor->mIoHandle, device);
5391 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
5392 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
5393 inputCmd.toString(),
5394 delayMs);
5395 }
5396 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005397 }
Eric Laurente552edb2014-03-10 17:42:56 -07005398
5399 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07005400 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005401
5402 return muteWaitMs;
5403}
5404
Eric Laurentc75307b2015-03-17 15:29:32 -07005405status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005406 int delayMs,
5407 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005408{
Eric Laurent6a94d692014-05-20 11:18:06 -07005409 ssize_t index;
5410 if (patchHandle) {
5411 index = mAudioPatches.indexOfKey(*patchHandle);
5412 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005413 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005414 }
5415 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005416 return INVALID_OPERATION;
5417 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005418 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5419 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005420 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005421 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005422 removeAudioPatch(patchDesc->mHandle);
5423 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005424 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005425 return status;
5426}
5427
5428status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5429 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005430 bool force,
5431 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005432{
5433 status_t status = NO_ERROR;
5434
Eric Laurent1f2f2232014-06-02 12:01:23 -07005435 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005436 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5437 inputDesc->mDevice = device;
5438
Mikhail Naganov708e0382018-05-30 09:53:04 -07005439 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005440 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005441 PatchBuilder patchBuilder;
5442 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005443 // AUDIO_SOURCE_HOTWORD is for internal use only:
5444 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07005445 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5446 auto result = usecase;
5447 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5448 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5449 }
5450 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07005451 //only one input device for now
Mikhail Naganovdc769682018-05-04 15:34:08 -07005452 addSource(deviceList.itemAt(0));
5453 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005454 }
5455 }
5456 return status;
5457}
5458
Eric Laurent6a94d692014-05-20 11:18:06 -07005459status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5460 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005461{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005462 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005463 ssize_t index;
5464 if (patchHandle) {
5465 index = mAudioPatches.indexOfKey(*patchHandle);
5466 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005467 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005468 }
5469 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005470 return INVALID_OPERATION;
5471 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005472 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5473 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005474 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005475 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005476 removeAudioPatch(patchDesc->mHandle);
5477 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005478 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005479 return status;
5480}
5481
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005482sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005483 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005484 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005485 audio_format_t& format,
5486 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005487 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005488{
5489 // Choose an input profile based on the requested capture parameters: select the first available
5490 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005491 //
5492 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5493 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005494
Glenn Kasten730b9262018-03-29 15:01:26 -07005495 sp<IOProfile> firstInexact;
5496 uint32_t updatedSamplingRate = 0;
5497 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5498 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005499 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005500 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005501 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005502 //updatedFormat = format;
Eric Laurent275e8e92014-11-30 15:14:47 -08005503 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005504 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005505 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005506 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005507 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005508 &channelMask /*updatedChannelMask*/,
5509 // FIXME ugly cast
5510 (audio_output_flags_t) flags,
5511 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005512 return profile;
5513 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005514 if (firstInexact == nullptr && profile->isCompatibleProfile(device, address,
5515 samplingRate,
5516 &updatedSamplingRate,
5517 format,
5518 &updatedFormat,
5519 channelMask,
5520 &updatedChannelMask,
5521 // FIXME ugly cast
5522 (audio_output_flags_t) flags,
5523 false /*exactMatchRequiredForInputFlags*/)) {
5524 firstInexact = profile;
5525 }
5526
Eric Laurente552edb2014-03-10 17:42:56 -07005527 }
5528 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005529 if (firstInexact != nullptr) {
5530 samplingRate = updatedSamplingRate;
5531 format = updatedFormat;
5532 channelMask = updatedChannelMask;
5533 return firstInexact;
5534 }
Eric Laurente552edb2014-03-10 17:42:56 -07005535 return NULL;
5536}
5537
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005538
5539audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005540 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005541{
Eric Laurent97ac8712018-07-27 18:59:02 -07005542 // Honor explicit routing requests only if all active clients have a preferred route in which
5543 // case the last active client route is used
5544 sp<DeviceDescriptor> deviceDesc =
5545 findPreferredDevice(mInputs, inputSource, mAvailableInputDevices);
5546 if (deviceDesc != nullptr) {
5547 return deviceDesc->type();
5548 }
5549
5550
François Gaffie036e1e92015-03-19 10:16:24 +01005551 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5552 audio_devices_t selectedDeviceFromMix =
5553 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005554
François Gaffie036e1e92015-03-19 10:16:24 +01005555 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5556 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005557 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005558 return getDeviceForInputSource(inputSource);
5559}
5560
5561audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5562{
Eric Laurent97ac8712018-07-27 18:59:02 -07005563 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005564}
5565
Eric Laurente0720872014-03-11 09:30:41 -07005566float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005567 int index,
5568 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005569{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005570 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005571
5572 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5573 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5574 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5575 // the ringtone volume
5576 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5577 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5578 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5579 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5580 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5581 }
5582
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005583 // in-call: always cap volume by voice volume + some low headroom
5584 if ((stream != AUDIO_STREAM_VOICE_CALL) &&
Eric Laurent7731b5a2018-04-06 15:47:22 -07005585 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005586 switch (stream) {
5587 case AUDIO_STREAM_SYSTEM:
5588 case AUDIO_STREAM_RING:
5589 case AUDIO_STREAM_MUSIC:
5590 case AUDIO_STREAM_ALARM:
5591 case AUDIO_STREAM_NOTIFICATION:
5592 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5593 case AUDIO_STREAM_DTMF:
5594 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005595 int voiceVolumeIndex =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005596 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, device);
Eric Laurent7731b5a2018-04-06 15:47:22 -07005597 const float maxVoiceVolDb =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005598 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, device)
Eric Laurent7731b5a2018-04-06 15:47:22 -07005599 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005600 if (volumeDB > maxVoiceVolDb) {
5601 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5602 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5603 volumeDB = maxVoiceVolDb;
5604 }
5605 } break;
5606 default:
5607 break;
5608 }
5609 }
5610
Eric Laurente552edb2014-03-10 17:42:56 -07005611 // if a headset is connected, apply the following rules to ring tones and notifications
5612 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005613 // - always attenuate notifications volume by 6dB
5614 // - attenuate ring tones volume by 6dB unless music is not playing and
5615 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005616 // - if music is playing, always limit the volume to current music volume,
5617 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005618 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005619 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5620 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5621 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005622 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005623 AUDIO_DEVICE_OUT_USB_HEADSET |
5624 AUDIO_DEVICE_OUT_HEARING_AID)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005625 ((stream_strategy == STRATEGY_SONIFICATION)
5626 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005627 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005628 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005629 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005630 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005631 // when the phone is ringing we must consider that music could have been paused just before
5632 // by the music application and behave as if music was active if the last music track was
5633 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005634 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005635 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005636 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005637 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005638 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005639 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5640 musicDevice),
5641 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005642 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5643 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005644 if (volumeDB > minVolDB) {
5645 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005646 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005647 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005648 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5649 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5650 // on A2DP, also ensure notification volume is not too low compared to media when
5651 // intended to be played
5652 if ((volumeDB > -96.0f) &&
5653 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5654 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5655 stream, device,
5656 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5657 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5658 }
5659 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005660 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5661 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005662 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005663 }
5664 }
5665
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005666 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005667}
5668
Eric Laurent3839bc02018-07-10 18:33:34 -07005669int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
5670 audio_stream_type_t srcStream,
5671 audio_stream_type_t dstStream)
5672{
5673 if (srcStream == dstStream) {
5674 return srcIndex;
5675 }
5676 float minSrc = (float)mVolumeCurves->getVolumeIndexMin(srcStream);
5677 float maxSrc = (float)mVolumeCurves->getVolumeIndexMax(srcStream);
5678 float minDst = (float)mVolumeCurves->getVolumeIndexMin(dstStream);
5679 float maxDst = (float)mVolumeCurves->getVolumeIndexMax(dstStream);
5680
5681 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
5682}
5683
Eric Laurente0720872014-03-11 09:30:41 -07005684status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005685 int index,
5686 const sp<AudioOutputDescriptor>& outputDesc,
5687 audio_devices_t device,
5688 int delayMs,
5689 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005690{
Eric Laurente552edb2014-03-10 17:42:56 -07005691 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005692 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005693 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005694 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005695 return NO_ERROR;
5696 }
François Gaffie2110e042015-03-24 08:41:51 +01005697 audio_policy_forced_cfg_t forceUseForComm =
5698 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005699 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005700 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5701 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005702 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005703 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005704 return INVALID_OPERATION;
5705 }
5706
Eric Laurentc75307b2015-03-17 15:29:32 -07005707 if (device == AUDIO_DEVICE_NONE) {
5708 device = outputDesc->device();
5709 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005710
Eric Laurentffbc80f2015-03-18 18:30:19 -07005711 float volumeDb = computeVolume(stream, index, device);
HW Leeda7581e2018-05-22 18:31:34 +08005712 if (outputDesc->isFixedVolume(device) ||
5713 // Force VoIP volume to max for bluetooth SCO
5714 ((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
5715 (device & AUDIO_DEVICE_OUT_ALL_SCO) != 0)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005716 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005717 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005718
Eric Laurentffbc80f2015-03-18 18:30:19 -07005719 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005720
Eric Laurent3b73df72014-03-11 09:06:29 -07005721 if (stream == AUDIO_STREAM_VOICE_CALL ||
5722 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005723 float voiceVolume;
5724 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005725 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurent3839bc02018-07-10 18:33:34 -07005726 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005727 } else {
5728 voiceVolume = 1.0;
5729 }
5730
Eric Laurent18fba842016-03-31 14:41:26 -07005731 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005732 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5733 mLastVoiceVolume = voiceVolume;
5734 }
5735 }
5736
5737 return NO_ERROR;
5738}
5739
Eric Laurentc75307b2015-03-17 15:29:32 -07005740void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5741 audio_devices_t device,
5742 int delayMs,
5743 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005744{
Eric Laurentc75307b2015-03-17 15:29:32 -07005745 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005746
Eric Laurent794fde22016-03-11 09:50:45 -08005747 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005748 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005749 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005750 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005751 device,
5752 delayMs,
5753 force);
5754 }
5755}
5756
Eric Laurente0720872014-03-11 09:30:41 -07005757void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
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 Laurent72249d52015-06-08 11:12:15 -07005763 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5764 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005765 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005766 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005767 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005768 }
5769 }
5770}
5771
Eric Laurente0720872014-03-11 09:30:41 -07005772void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005773 bool on,
5774 const sp<AudioOutputDescriptor>& outputDesc,
5775 int delayMs,
5776 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005777{
Eric Laurente552edb2014-03-10 17:42:56 -07005778 if (device == AUDIO_DEVICE_NONE) {
5779 device = outputDesc->device();
5780 }
5781
Eric Laurentc75307b2015-03-17 15:29:32 -07005782 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5783 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005784
5785 if (on) {
5786 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005787 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005788 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005789 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005790 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005791 }
5792 }
5793 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5794 outputDesc->mMuteCount[stream]++;
5795 } else {
5796 if (outputDesc->mMuteCount[stream] == 0) {
5797 ALOGV("setStreamMute() unmuting non muted stream!");
5798 return;
5799 }
5800 if (--outputDesc->mMuteCount[stream] == 0) {
5801 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005802 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005803 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005804 device,
5805 delayMs);
5806 }
5807 }
5808}
5809
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005810audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5811{
5812 // flags to stream type mapping
5813 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5814 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5815 }
5816 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5817 return AUDIO_STREAM_BLUETOOTH_SCO;
5818 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005819 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5820 return AUDIO_STREAM_TTS;
5821 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005822
Ari Hausman-Cohen5c00d012018-06-26 17:09:11 -07005823 return audio_usage_to_stream_type(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005824}
Eric Laurente83b55d2014-11-14 10:06:21 -08005825
François Gaffie53615e22015-03-19 09:24:12 +01005826bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5827{
Eric Laurente83b55d2014-11-14 10:06:21 -08005828 // has flags that map to a strategy?
5829 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5830 return true;
5831 }
5832
5833 // has known usage?
5834 switch (paa->usage) {
5835 case AUDIO_USAGE_UNKNOWN:
5836 case AUDIO_USAGE_MEDIA:
5837 case AUDIO_USAGE_VOICE_COMMUNICATION:
5838 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5839 case AUDIO_USAGE_ALARM:
5840 case AUDIO_USAGE_NOTIFICATION:
5841 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5842 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5843 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5844 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5845 case AUDIO_USAGE_NOTIFICATION_EVENT:
5846 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5847 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5848 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5849 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005850 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005851 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005852 break;
5853 default:
5854 return false;
5855 }
5856 return true;
5857}
5858
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005859bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005860 routing_strategy strategy, uint32_t inPastMs,
5861 nsecs_t sysTime) const
5862{
5863 if ((sysTime == 0) && (inPastMs != 0)) {
5864 sysTime = systemTime();
5865 }
Eric Laurent794fde22016-03-11 09:50:45 -08005866 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005867 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurent97ac8712018-07-27 18:59:02 -07005868 (STRATEGY_NONE == strategy)) &&
François Gaffiead3183e2015-03-18 16:55:35 +01005869 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5870 return true;
5871 }
5872 }
5873 return false;
5874}
5875
Eric Laurent484e9272018-06-07 17:29:23 -07005876bool AudioPolicyManager::isStrategyActiveOnSameModule(const sp<AudioOutputDescriptor>& outputDesc,
5877 routing_strategy strategy, uint32_t inPastMs,
5878 nsecs_t sysTime) const
5879{
5880 for (size_t i = 0; i < mOutputs.size(); i++) {
5881 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5882 if (outputDesc->sharesHwModuleWith(desc)
5883 && isStrategyActive(desc, strategy, inPastMs, sysTime)) {
5884 return true;
5885 }
5886 }
5887 return false;
5888}
5889
François Gaffie2110e042015-03-24 08:41:51 +01005890audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5891{
5892 return mEngine->getForceUse(usage);
5893}
5894
5895bool AudioPolicyManager::isInCall()
5896{
5897 return isStateInCall(mEngine->getPhoneState());
5898}
5899
5900bool AudioPolicyManager::isStateInCall(int state)
5901{
5902 return is_state_in_call(state);
5903}
5904
Eric Laurentd60560a2015-04-10 11:31:20 -07005905void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5906{
5907 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005908 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5909 if (sourceDesc->srcDevice()->equals(deviceDesc)) {
5910 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->portId());
5911 stopAudioSource(sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005912 }
5913 }
5914
5915 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5916 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5917 bool release = false;
5918 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5919 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5920 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5921 source->ext.device.type == deviceDesc->type()) {
5922 release = true;
5923 }
5924 }
5925 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5926 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5927 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5928 sink->ext.device.type == deviceDesc->type()) {
5929 release = true;
5930 }
5931 }
5932 if (release) {
5933 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5934 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5935 }
5936 }
5937}
5938
Phil Burk09bc4612016-02-24 15:58:15 -08005939// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005940void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5941 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005942 // TODO Set this based on Config properties.
5943 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005944
5945 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5946 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005947 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005948
jiabin81772902018-04-02 17:52:27 -07005949 // If MANUAL, keep the supported surround sound formats as current enabled ones.
5950 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
5951 formats.clear();
5952 for (auto it = mSurroundFormats.begin(); it != mSurroundFormats.end(); it++) {
5953 formats.add(*it);
Phil Burk09bc4612016-02-24 15:58:15 -08005954 }
jiabin81772902018-04-02 17:52:27 -07005955 // Always enable IEC61937 when in MANUAL mode.
5956 formats.add(AUDIO_FORMAT_IEC61937);
5957 } else { // NEVER, AUTO or ALWAYS
5958 // Analyze original support for various formats.
5959 bool supportsAC3 = false;
5960 bool supportsOtherSurround = false;
5961 bool supportsIEC61937 = false;
5962 mSurroundFormats.clear();
5963 for (ssize_t formatIndex = 0; formatIndex < (ssize_t)formats.size(); formatIndex++) {
5964 audio_format_t format = formats[formatIndex];
5965 switch (format) {
5966 case AUDIO_FORMAT_AC3:
5967 supportsAC3 = true;
5968 break;
5969 case AUDIO_FORMAT_E_AC3:
5970 case AUDIO_FORMAT_DTS:
5971 case AUDIO_FORMAT_DTS_HD:
5972 // If ALWAYS, remove all other surround formats here
5973 // since we will add them later.
5974 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5975 formats.removeAt(formatIndex);
5976 formatIndex--;
5977 }
5978 supportsOtherSurround = true;
5979 break;
5980 case AUDIO_FORMAT_IEC61937:
5981 supportsIEC61937 = true;
5982 break;
5983 default:
5984 break;
5985 }
5986 }
Phil Burk09bc4612016-02-24 15:58:15 -08005987
jiabin81772902018-04-02 17:52:27 -07005988 // Modify formats based on surround preferences.
5989 // If NEVER, remove support for surround formats.
5990 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5991 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5992 // Remove surround sound related formats.
5993 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5994 audio_format_t format = formats[formatIndex];
5995 switch(format) {
5996 case AUDIO_FORMAT_AC3:
5997 case AUDIO_FORMAT_E_AC3:
5998 case AUDIO_FORMAT_DTS:
5999 case AUDIO_FORMAT_DTS_HD:
6000 case AUDIO_FORMAT_IEC61937:
6001 formats.removeAt(formatIndex);
6002 break;
6003 default:
6004 formatIndex++; // keep it
6005 break;
6006 }
6007 }
6008 supportsAC3 = false;
6009 supportsOtherSurround = false;
6010 supportsIEC61937 = false;
6011 }
6012 } else { // AUTO or ALWAYS
6013 // Most TVs support AC3 even if they do not report it in the EDID.
6014 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
6015 && !supportsAC3) {
6016 formats.add(AUDIO_FORMAT_AC3);
6017 supportsAC3 = true;
6018 }
6019
6020 // If ALWAYS, add support for raw surround formats if all are missing.
6021 // This assumes that if any of these formats are reported by the HAL
6022 // then the report is valid and should not be modified.
6023 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
6024 formats.add(AUDIO_FORMAT_E_AC3);
6025 formats.add(AUDIO_FORMAT_DTS);
6026 formats.add(AUDIO_FORMAT_DTS_HD);
6027 supportsOtherSurround = true;
6028 }
6029
6030 // Add support for IEC61937 if any raw surround supported.
6031 // The HAL could do this but add it here, just in case.
6032 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
6033 formats.add(AUDIO_FORMAT_IEC61937);
6034 supportsIEC61937 = true;
6035 }
6036
6037 // Add reported surround sound formats to enabled surround formats.
6038 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
Phil Burk07ac1142016-03-25 13:39:29 -07006039 audio_format_t format = formats[formatIndex];
6040 switch(format) {
6041 case AUDIO_FORMAT_AC3:
6042 case AUDIO_FORMAT_E_AC3:
6043 case AUDIO_FORMAT_DTS:
6044 case AUDIO_FORMAT_DTS_HD:
jiabin81772902018-04-02 17:52:27 -07006045 case AUDIO_FORMAT_AAC_LC:
6046 case AUDIO_FORMAT_DOLBY_TRUEHD:
6047 case AUDIO_FORMAT_E_AC3_JOC:
6048 mSurroundFormats.insert(format);
Phil Burk07ac1142016-03-25 13:39:29 -07006049 default:
Phil Burk07ac1142016-03-25 13:39:29 -07006050 break;
6051 }
Phil Burk09bc4612016-02-24 15:58:15 -08006052 }
Phil Burk07ac1142016-03-25 13:39:29 -07006053 }
Phil Burk09bc4612016-02-24 15:58:15 -08006054 }
Phil Burk0709b0a2016-03-31 12:54:57 -07006055}
6056
6057// Modify the list of channel masks supported.
6058void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
6059 ChannelsVector &channelMasks = *channelMasksPtr;
6060 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6061 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
6062
6063 // If NEVER, then remove support for channelMasks > stereo.
6064 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
6065 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
6066 audio_channel_mask_t channelMask = channelMasks[maskIndex];
6067 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
6068 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
6069 channelMasks.removeAt(maskIndex);
6070 } else {
6071 maskIndex++;
6072 }
6073 }
jiabin81772902018-04-02 17:52:27 -07006074 // If ALWAYS or MANUAL, then make sure we at least support 5.1
6075 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
6076 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006077 bool supports5dot1 = false;
6078 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006079 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006080 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
6081 supports5dot1 = true;
6082 break;
6083 }
6084 }
6085 // If not then add 5.1 support.
6086 if (!supports5dot1) {
6087 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
6088 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
6089 }
Phil Burk09bc4612016-02-24 15:58:15 -08006090 }
6091}
6092
Phil Burk00eeb322016-03-31 12:41:00 -07006093void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
6094 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01006095 AudioProfileVector &profiles)
6096{
6097 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07006098
François Gaffie112b0af2015-11-19 16:13:25 +01006099 // Format MUST be checked first to update the list of AudioProfile
6100 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006101 reply = mpClientInterface->getParameters(
6102 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07006103 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006104 AudioParameter repliedParameters(reply);
6105 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006106 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01006107 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
6108 return;
6109 }
Phil Burk09bc4612016-02-24 15:58:15 -08006110 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07006111 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006112 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07006113 }
Phil Burk09bc4612016-02-24 15:58:15 -08006114 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01006115 }
François Gaffie112b0af2015-11-19 16:13:25 +01006116
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006117 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08006118 ChannelsVector channelMasks;
6119 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01006120 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07006121 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01006122
6123 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006124 reply = mpClientInterface->getParameters(
6125 ioHandle,
6126 requestedParameters.toString() + ";" +
6127 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01006128 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006129 AudioParameter repliedParameters(reply);
6130 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006131 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006132 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01006133 }
6134 }
6135 if (profiles.hasDynamicChannelsFor(format)) {
6136 reply = mpClientInterface->getParameters(ioHandle,
6137 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07006138 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01006139 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006140 AudioParameter repliedParameters(reply);
6141 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006142 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006143 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07006144 if (device == AUDIO_DEVICE_OUT_HDMI) {
6145 filterSurroundChannelMasks(&channelMasks);
6146 }
François Gaffie112b0af2015-11-19 16:13:25 +01006147 }
6148 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08006149 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006150 }
6151}
Eric Laurentd60560a2015-04-10 11:31:20 -07006152
Mikhail Naganovdc769682018-05-04 15:34:08 -07006153status_t AudioPolicyManager::installPatch(const char *caller,
6154 audio_patch_handle_t *patchHandle,
6155 AudioIODescriptorInterface *ioDescriptor,
6156 const struct audio_patch *patch,
6157 int delayMs)
6158{
6159 ssize_t index = mAudioPatches.indexOfKey(
6160 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6161 *patchHandle : ioDescriptor->getPatchHandle());
6162 sp<AudioPatch> patchDesc;
6163 status_t status = installPatch(
6164 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6165 if (status == NO_ERROR) {
6166 ioDescriptor->setPatchHandle(patchDesc->mHandle);
6167 }
6168 return status;
6169}
6170
6171status_t AudioPolicyManager::installPatch(const char *caller,
6172 ssize_t index,
6173 audio_patch_handle_t *patchHandle,
6174 const struct audio_patch *patch,
6175 int delayMs,
6176 uid_t uid,
6177 sp<AudioPatch> *patchDescPtr)
6178{
6179 sp<AudioPatch> patchDesc;
6180 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6181 if (index >= 0) {
6182 patchDesc = mAudioPatches.valueAt(index);
6183 afPatchHandle = patchDesc->mAfPatchHandle;
6184 }
6185
6186 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6187 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6188 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6189 if (status == NO_ERROR) {
6190 if (index < 0) {
6191 patchDesc = new AudioPatch(patch, uid);
6192 addAudioPatch(patchDesc->mHandle, patchDesc);
6193 } else {
6194 patchDesc->mPatch = *patch;
6195 }
6196 patchDesc->mAfPatchHandle = afPatchHandle;
6197 if (patchHandle) {
6198 *patchHandle = patchDesc->mHandle;
6199 }
6200 nextAudioPortGeneration();
6201 mpClientInterface->onAudioPatchListUpdate();
6202 }
6203 if (patchDescPtr) *patchDescPtr = patchDesc;
6204 return status;
6205}
6206
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006207} // namespace android