blob: e8a1db41d47ecc9bcc45087f1a3dc3d5858038a9 [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"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090018
19// Need to keep the log statements even in production builds
20// to enable VERBOSE logging dynamically.
21// You can enable VERBOSE logging as follows:
22// adb shell setprop log.tag.APM_AudioPolicyManager V
23#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070024
25//#define VERY_VERBOSE_LOGGING
26#ifdef VERY_VERBOSE_LOGGING
27#define ALOGVV ALOGV
28#else
29#define ALOGVV(a...) do { } while(0)
30#endif
31
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +090032#define AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH 128
33#define AUDIO_POLICY_XML_CONFIG_FILE_NAME "audio_policy_configuration.xml"
Petri Gyntherf497f292018-04-17 18:46:10 -070034#define AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME \
35 "audio_policy_configuration_a2dp_offload_disabled.xml"
François Gaffief4ad6e52015-11-19 16:59:57 +010036
Eric Laurentd4692962014-05-05 18:13:44 -070037#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070038#include <math.h>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110039#include <vector>
Eric Laurentd4692962014-05-05 18:13:44 -070040
François Gaffie2110e042015-03-24 08:41:51 +010041#include <AudioPolicyManagerInterface.h>
42#include <AudioPolicyEngineInstance.h>
Eric Laurente552edb2014-03-10 17:42:56 -070043#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070044#include <utils/Log.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070045#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080046#include <media/AudioPolicyHelper.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070047#include <private/android_filesystem_config.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070048#include <soundtrigger/SoundTrigger.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070049#include <system/audio.h>
Mikhail Naganov9ee05402016-10-13 15:58:17 -070050#include <audio_policy_conf.h>
Eric Laurentd4692962014-05-05 18:13:44 -070051#include "AudioPolicyManager.h"
François Gaffied1ab2bd2015-12-02 18:20:06 +010052#include <Serializer.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010053#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010054#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070055
Eric Laurent3b73df72014-03-11 09:06:29 -070056namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070057
Eric Laurentdc462862016-07-19 12:29:53 -070058//FIXME: workaround for truncated touch sounds
59// to be removed when the problem is handled by system UI
60#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070061
62// Largest difference in dB on earpiece in call between the voice volume and another
63// media / notification / system volume.
64constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
65
Mikhail Naganov15be9d22017-11-08 14:18:13 +110066// Compressed formats for MSD module, ordered from most preferred to least preferred.
67static const std::vector<audio_format_t> compressedFormatsOrder = {{
68 AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
69 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
70// Channel masks for MSD module, 3D > 2D > 1D ordering (most preferred to least preferred).
71static const std::vector<audio_channel_mask_t> surroundChannelMasksOrder = {{
72 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
73 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
74 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
75
Eric Laurente552edb2014-03-10 17:42:56 -070076// ----------------------------------------------------------------------------
77// AudioPolicyInterface implementation
78// ----------------------------------------------------------------------------
79
Eric Laurente0720872014-03-11 09:30:41 -070080status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -080081 audio_policy_dev_state_t state,
82 const char *device_address,
83 const char *device_name)
Eric Laurente552edb2014-03-10 17:42:56 -070084{
jiabina7b43792018-02-15 16:04:46 -080085 status_t status = setDeviceConnectionStateInt(device, state, device_address, device_name);
86 nextAudioPortGeneration();
87 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -080088}
89
François Gaffie44481e72016-04-20 07:49:57 +020090void AudioPolicyManager::broadcastDeviceConnectionState(audio_devices_t device,
91 audio_policy_dev_state_t state,
92 const String8 &device_address)
93{
94 AudioParameter param(device_address);
95 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganov388360c2016-10-17 17:09:41 -070096 AudioParameter::keyStreamConnect : AudioParameter::keyStreamDisconnect);
François Gaffie44481e72016-04-20 07:49:57 +020097 param.addInt(key, device);
98 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
99}
100
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800101status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800102 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -0800103 const char *device_address,
104 const char *device_name)
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800105{
Paul McLeane743a472015-01-28 11:07:31 -0800106 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s",
Mikhail Naganov7e22e942017-12-07 10:04:29 -0800107 device, state, device_address, device_name);
Eric Laurente552edb2014-03-10 17:42:56 -0700108
109 // connect/disconnect only 1 device at a time
110 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
111
François Gaffie53615e22015-03-19 09:24:12 +0100112 sp<DeviceDescriptor> devDesc =
113 mHwModules.getDeviceDescriptor(device, device_address, device_name);
Paul McLeane743a472015-01-28 11:07:31 -0800114
Eric Laurente552edb2014-03-10 17:42:56 -0700115 // handle output devices
116 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700117 SortedVector <audio_io_handle_t> outputs;
118
Eric Laurent3a4311c2014-03-17 12:00:47 -0700119 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
120
Eric Laurente552edb2014-03-10 17:42:56 -0700121 // save a copy of the opened output descriptors before any output is opened or closed
122 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
123 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700124 switch (state)
125 {
126 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800127 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700128 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700129 ALOGW("setDeviceConnectionState() device already connected: %x", device);
130 return INVALID_OPERATION;
131 }
132 ALOGV("setDeviceConnectionState() connecting device %x", device);
133
Eric Laurente552edb2014-03-10 17:42:56 -0700134 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700135 index = mAvailableOutputDevices.add(devDesc);
136 if (index >= 0) {
François Gaffie53615e22015-03-19 09:24:12 +0100137 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700138 if (module == 0) {
139 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
140 device);
141 mAvailableOutputDevices.remove(devDesc);
142 return INVALID_OPERATION;
143 }
Paul McLeane743a472015-01-28 11:07:31 -0800144 mAvailableOutputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700145 } else {
146 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700147 }
148
François Gaffie44481e72016-04-20 07:49:57 +0200149 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
150 // parameters on newly connected devices (instead of opening the outputs...)
151 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
152
Eric Laurenta1d525f2015-01-29 13:36:45 -0800153 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700154 mAvailableOutputDevices.remove(devDesc);
François Gaffie44481e72016-04-20 07:49:57 +0200155
156 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
157 devDesc->mAddress);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700158 return INVALID_OPERATION;
159 }
François Gaffie2110e042015-03-24 08:41:51 +0100160 // Propagate device availability to Engine
161 mEngine->setDeviceConnectionState(devDesc, state);
162
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700163 // outputs should never be empty here
164 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
165 "checkOutputsForDevice() returned no outputs but status OK");
166 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
167 outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800168
Eric Laurent3ae5f312015-02-03 17:12:08 -0800169 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700170 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700171 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700172 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700173 ALOGW("setDeviceConnectionState() device not connected: %x", device);
174 return INVALID_OPERATION;
175 }
176
Paul McLean5c477aa2014-08-20 16:47:57 -0700177 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
178
Paul McLeane743a472015-01-28 11:07:31 -0800179 // Send Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200180 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700181
Eric Laurente552edb2014-03-10 17:42:56 -0700182 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700183 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700184
Eric Laurenta1d525f2015-01-29 13:36:45 -0800185 checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress);
François Gaffie2110e042015-03-24 08:41:51 +0100186
187 // Propagate device availability to Engine
188 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700189 } break;
190
191 default:
192 ALOGE("setDeviceConnectionState() invalid state: %x", state);
193 return BAD_VALUE;
194 }
195
Mikhail Naganov37977152018-07-11 15:54:44 -0700196 checkForDeviceAndOutputChanges([&]() {
197 // outputs must be closed after checkOutputForAllStrategies() is executed
198 if (!outputs.isEmpty()) {
199 for (audio_io_handle_t output : outputs) {
200 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
201 // close unused outputs after device disconnection or direct outputs that have been
202 // opened by checkOutputsForDevice() to query dynamic parameters
203 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
204 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
205 (desc->mDirectOpenCount == 0))) {
206 closeOutput(output);
207 }
Eric Laurente552edb2014-03-10 17:42:56 -0700208 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700209 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
210 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700211 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700212 return false;
213 });
Eric Laurente552edb2014-03-10 17:42:56 -0700214
Eric Laurent87ffa392015-05-22 10:32:38 -0700215 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700216 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
217 updateCallRouting(newDevice);
218 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100219 const audio_devices_t msdOutDevice = getMsdAudioOutDeviceTypes();
Eric Laurente552edb2014-03-10 17:42:56 -0700220 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700221 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
222 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
223 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700224 // do not force device change on duplicated output because if device is 0, it will
225 // also force a device 0 for the two outputs it is duplicated to which may override
226 // a valid device selection on those outputs.
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100227 bool force = (msdOutDevice == AUDIO_DEVICE_NONE || msdOutDevice != desc->device())
228 && !desc->isDuplicated()
François Gaffie53615e22015-03-19 09:24:12 +0100229 && (!device_distinguishes_on_address(device)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700230 // always force when disconnecting (a non-duplicated device)
231 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
Eric Laurentc75307b2015-03-17 15:29:32 -0700232 setOutputDevice(desc, newDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700233 }
Eric Laurente552edb2014-03-10 17:42:56 -0700234 }
235
Eric Laurentd60560a2015-04-10 11:31:20 -0700236 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
237 cleanUpForDevice(devDesc);
238 }
239
Eric Laurent72aa32f2014-05-30 18:51:48 -0700240 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700241 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700242 } // end if is output device
243
Eric Laurente552edb2014-03-10 17:42:56 -0700244 // handle input devices
245 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700246 SortedVector <audio_io_handle_t> inputs;
247
Eric Laurent3a4311c2014-03-17 12:00:47 -0700248 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700249 switch (state)
250 {
251 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700252 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700253 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700254 ALOGW("setDeviceConnectionState() device already connected: %d", device);
255 return INVALID_OPERATION;
256 }
François Gaffie53615e22015-03-19 09:24:12 +0100257 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700258 if (module == NULL) {
259 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
260 device);
261 return INVALID_OPERATION;
262 }
François Gaffie44481e72016-04-20 07:49:57 +0200263
264 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
265 // parameters on newly connected devices (instead of opening the inputs...)
266 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
267
Paul McLean9080a4c2015-06-18 08:24:02 -0700268 if (checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress) != NO_ERROR) {
François Gaffie44481e72016-04-20 07:49:57 +0200269 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
270 devDesc->mAddress);
Eric Laurentd4692962014-05-05 18:13:44 -0700271 return INVALID_OPERATION;
272 }
273
Eric Laurent3a4311c2014-03-17 12:00:47 -0700274 index = mAvailableInputDevices.add(devDesc);
275 if (index >= 0) {
Paul McLeane743a472015-01-28 11:07:31 -0800276 mAvailableInputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700277 } else {
278 return NO_MEMORY;
279 }
Eric Laurent3ae5f312015-02-03 17:12:08 -0800280
François Gaffie2110e042015-03-24 08:41:51 +0100281 // Propagate device availability to Engine
282 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700283 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700284
285 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700286 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700287 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700288 ALOGW("setDeviceConnectionState() device not connected: %d", device);
289 return INVALID_OPERATION;
290 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700291
292 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
293
294 // Set Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200295 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700296
Paul McLean9080a4c2015-06-18 08:24:02 -0700297 checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700298 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700299
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 default:
305 ALOGE("setDeviceConnectionState() invalid state: %x", state);
306 return BAD_VALUE;
307 }
308
Eric Laurentd4692962014-05-05 18:13:44 -0700309 closeAllInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700310 // As the input device list can impact the output device selection, update
311 // getDeviceForStrategy() cache
312 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700313
Eric Laurent87ffa392015-05-22 10:32:38 -0700314 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700315 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
316 updateCallRouting(newDevice);
317 }
318
Eric Laurentd60560a2015-04-10 11:31:20 -0700319 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
320 cleanUpForDevice(devDesc);
321 }
322
Eric Laurentb52c1522014-05-20 11:27:36 -0700323 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700324 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700325 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700326
327 ALOGW("setDeviceConnectionState() invalid device: %x", device);
328 return BAD_VALUE;
329}
330
Eric Laurente0720872014-03-11 09:30:41 -0700331audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100332 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700333{
Eric Laurent634b7142016-04-20 13:48:02 -0700334 sp<DeviceDescriptor> devDesc =
335 mHwModules.getDeviceDescriptor(device, device_address, "",
336 (strlen(device_address) != 0)/*matchAddress*/);
337
338 if (devDesc == 0) {
339 ALOGW("getDeviceConnectionState() undeclared device, type %08x, address: %s",
340 device, device_address);
341 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
342 }
François Gaffie53615e22015-03-19 09:24:12 +0100343
Eric Laurent3a4311c2014-03-17 12:00:47 -0700344 DeviceVector *deviceVector;
345
Eric Laurente552edb2014-03-10 17:42:56 -0700346 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700347 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700348 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700349 deviceVector = &mAvailableInputDevices;
350 } else {
351 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
352 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700353 }
Eric Laurent634b7142016-04-20 13:48:02 -0700354
355 return (deviceVector->getDevice(device, String8(device_address)) != 0) ?
356 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800357}
358
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800359status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
360 const char *device_address,
361 const char *device_name)
362{
363 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700364 String8 reply;
365 AudioParameter param;
366 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800367
368 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s",
369 device, device_address, device_name);
370
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800371 // connect/disconnect only 1 device at a time
372 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
373
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800374 // Check if the device is currently connected
375 sp<DeviceDescriptor> devDesc =
376 mHwModules.getDeviceDescriptor(device, device_address, device_name);
377 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
378 if (index < 0) {
379 // Nothing to do: device is not connected
380 return NO_ERROR;
381 }
382
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700383 // For offloaded A2DP, Hw modules may have the capability to
384 // configure codecs. Check if any of the loaded hw modules
385 // supports this.
386 // If supported, send a set parameter to configure A2DP codecs
387 // and return. No need to toggle device state.
388 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
389 reply = mpClientInterface->getParameters(
390 AUDIO_IO_HANDLE_NONE,
391 String8(AudioParameter::keyReconfigA2dpSupported));
392 AudioParameter repliedParameters(reply);
393 repliedParameters.getInt(
394 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
395 if (isReconfigA2dpSupported) {
396 const String8 key(AudioParameter::keyReconfigA2dp);
397 param.add(key, String8("true"));
398 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
399 return NO_ERROR;
400 }
401 }
402
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800403 // Toggle the device state: UNAVAILABLE -> AVAILABLE
404 // This will force reading again the device configuration
405 status = setDeviceConnectionState(device,
406 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
407 device_address, device_name);
408 if (status != NO_ERROR) {
409 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
410 status);
411 return status;
412 }
413
414 status = setDeviceConnectionState(device,
415 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
416 device_address, device_name);
417 if (status != NO_ERROR) {
418 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
419 status);
420 return status;
421 }
422
423 return NO_ERROR;
424}
425
Eric Laurentdc462862016-07-19 12:29:53 -0700426uint32_t AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700427{
428 bool createTxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700429 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700430
Andy Hunga76c7de2016-12-13 19:14:31 -0800431 if(!hasPrimaryOutput() || mPrimaryOutput->device() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurentdc462862016-07-19 12:29:53 -0700432 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700433 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800434 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700435 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
436
437 // release existing RX patch if any
438 if (mCallRxPatch != 0) {
439 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
440 mCallRxPatch.clear();
441 }
442 // release TX patch if any
443 if (mCallTxPatch != 0) {
444 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
445 mCallTxPatch.clear();
446 }
447
448 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
449 // via setOutputDevice() on primary output.
450 // Otherwise, create two audio patches for TX and RX path.
451 if (availablePrimaryOutputDevices() & rxDevice) {
Eric Laurentdc462862016-07-19 12:29:53 -0700452 muteWaitMs = setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700453 // If the TX device is also on the primary HW module, setOutputDevice() will take care
454 // of it due to legacy implementation. If not, create a patch.
455 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
456 == AUDIO_DEVICE_NONE) {
457 createTxPatch = true;
458 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700459 } else { // create RX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800460 mCallRxPatch = createTelephonyPatch(true /*isRx*/, rxDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700461 createTxPatch = true;
462 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700463 if (createTxPatch) { // create TX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800464 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txDevice, delayMs);
465 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700466
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800467 return muteWaitMs;
468}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700469
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800470sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
471 bool isRx, audio_devices_t device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700472 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700473
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800474 sp<DeviceDescriptor> txSourceDeviceDesc;
475 if (isRx) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700476 patchBuilder.addSink(findDevice(mAvailableOutputDevices, device)).
477 addSource(findDevice(mAvailableInputDevices, AUDIO_DEVICE_IN_TELEPHONY_RX));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800478 } else {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700479 patchBuilder.addSource(txSourceDeviceDesc = findDevice(mAvailableInputDevices, device)).
480 addSink(findDevice(mAvailableOutputDevices, AUDIO_DEVICE_OUT_TELEPHONY_TX));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800481 }
482
483 audio_devices_t outputDevice = isRx ? device : AUDIO_DEVICE_OUT_TELEPHONY_TX;
484 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(outputDevice, mOutputs);
485 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
486 // request to reuse existing output stream if one is already opened to reach the target device
487 if (output != AUDIO_IO_HANDLE_NONE) {
488 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
489 ALOG_ASSERT(!outputDesc->isDuplicated(),
490 "%s() %#x device output %d is duplicated", __func__, outputDevice, output);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700491 patchBuilder.addSource(outputDesc, { .stream = AUDIO_STREAM_PATCH });
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800492 }
493
494 if (!isRx) {
Eric Laurentc0a889f2015-10-14 14:36:34 -0700495 // terminate active capture if on the same HW module as the call TX source device
496 // FIXME: would be better to refine to only inputs whose profile connects to the
497 // call TX device but this information is not in the audio patch and logic here must be
498 // symmetric to the one in startInput()
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800499 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800500 if (activeDesc->hasSameHwModuleAs(txSourceDeviceDesc)) {
Eric Laurent8f42ea12018-08-08 09:08:25 -0700501 closeActiveClients(activeDesc);
Eric Laurentc0a889f2015-10-14 14:36:34 -0700502 }
503 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700504 }
Eric Laurentdc462862016-07-19 12:29:53 -0700505
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800506 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Mikhail Naganovdc769682018-05-04 15:34:08 -0700507 status_t status = mpClientInterface->createAudioPatch(
508 patchBuilder.patch(), &afPatchHandle, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800509 ALOGW_IF(status != NO_ERROR,
510 "%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
511 sp<AudioPatch> audioPatch;
512 if (status == NO_ERROR) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700513 audioPatch = new AudioPatch(patchBuilder.patch(), mUidCached);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800514 audioPatch->mAfPatchHandle = afPatchHandle;
515 audioPatch->mUid = mUidCached;
516 }
517 return audioPatch;
518}
519
Mikhail Naganovdc769682018-05-04 15:34:08 -0700520sp<DeviceDescriptor> AudioPolicyManager::findDevice(
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100521 const DeviceVector& devices, audio_devices_t device) const {
Mikhail Naganov708e0382018-05-30 09:53:04 -0700522 DeviceVector deviceList = devices.getDevicesFromTypeMask(device);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800523 ALOG_ASSERT(!deviceList.isEmpty(),
524 "%s() selected device type %#x is not in devices list", __func__, device);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700525 return deviceList.itemAt(0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700526}
527
Eric Laurente0720872014-03-11 09:30:41 -0700528void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700529{
530 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100531 // store previous phone state for management of sonification strategy below
532 int oldState = mEngine->getPhoneState();
533
534 if (mEngine->setPhoneState(state) != NO_ERROR) {
535 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700536 return;
537 }
François Gaffie2110e042015-03-24 08:41:51 +0100538 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700539 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700540 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700541 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800542 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700543 }
544
François Gaffie2110e042015-03-24 08:41:51 +0100545 /**
546 * Switching to or from incall state or switching between telephony and VoIP lead to force
547 * routing command.
548 */
549 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
550 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700551
552 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700553 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700554
Eric Laurente552edb2014-03-10 17:42:56 -0700555 int delayMs = 0;
556 if (isStateInCall(state)) {
557 nsecs_t sysTime = systemTime();
558 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700559 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700560 // mute media and sonification strategies and delay device switch by the largest
561 // latency of any output where either strategy is active.
562 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100563 if ((isStrategyActive(desc, STRATEGY_MEDIA,
564 SONIFICATION_HEADSET_MUSIC_DELAY,
565 sysTime) ||
566 isStrategyActive(desc, STRATEGY_SONIFICATION,
567 SONIFICATION_HEADSET_MUSIC_DELAY,
568 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700569 (delayMs < (int)desc->latency()*2)) {
570 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700571 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700572 setStrategyMute(STRATEGY_MEDIA, true, desc);
573 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700574 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700575 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
576 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700577 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
578 }
579 }
580
Eric Laurent87ffa392015-05-22 10:32:38 -0700581 if (hasPrimaryOutput()) {
582 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
583 // the device returned is not necessarily reachable via this output
584 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
585 // force routing command to audio hardware when ending call
586 // even if no device change is needed
587 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
588 rxDevice = mPrimaryOutput->device();
589 }
Eric Laurente552edb2014-03-10 17:42:56 -0700590
Eric Laurent87ffa392015-05-22 10:32:38 -0700591 if (state == AUDIO_MODE_IN_CALL) {
592 updateCallRouting(rxDevice, delayMs);
593 } else if (oldState == AUDIO_MODE_IN_CALL) {
594 if (mCallRxPatch != 0) {
595 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
596 mCallRxPatch.clear();
597 }
598 if (mCallTxPatch != 0) {
599 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
600 mCallTxPatch.clear();
601 }
602 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
603 } else {
604 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700605 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700606 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700607
608 // reevaluate routing on all outputs in case tracks have been started during the call
609 for (size_t i = 0; i < mOutputs.size(); i++) {
610 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
611 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
612 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
Yung Ti Suf60c8242018-05-10 18:07:26 +0800613 setOutputDevice(desc, newDevice, (newDevice != AUDIO_DEVICE_NONE), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700614 }
615 }
616
Eric Laurente552edb2014-03-10 17:42:56 -0700617 if (isStateInCall(state)) {
618 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700619 // force reevaluating accessibility routing when call starts
620 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700621 }
622
623 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700624 if (state == AUDIO_MODE_RINGTONE &&
625 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700626 mLimitRingtoneVolume = true;
627 } else {
628 mLimitRingtoneVolume = false;
629 }
630}
631
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700632audio_mode_t AudioPolicyManager::getPhoneState() {
633 return mEngine->getPhoneState();
634}
635
Eric Laurente0720872014-03-11 09:30:41 -0700636void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700637 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700638{
François Gaffie2110e042015-03-24 08:41:51 +0100639 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700640 if (config == mEngine->getForceUse(usage)) {
641 return;
642 }
Eric Laurente552edb2014-03-10 17:42:56 -0700643
François Gaffie2110e042015-03-24 08:41:51 +0100644 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
645 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
646 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700647 }
François Gaffie2110e042015-03-24 08:41:51 +0100648 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
649 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
650 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700651
652 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700653 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800654
Eric Laurentdc462862016-07-19 12:29:53 -0700655 //FIXME: workaround for truncated touch sounds
656 // to be removed when the problem is handled by system UI
657 uint32_t delayMs = 0;
658 uint32_t waitMs = 0;
659 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
660 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
661 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700662 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700663 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
Eric Laurentdc462862016-07-19 12:29:53 -0700664 waitMs = updateCallRouting(newDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700665 }
Eric Laurente552edb2014-03-10 17:42:56 -0700666 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700667 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
668 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
669 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700670 waitMs = setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE),
671 delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700672 }
Eric Laurente552edb2014-03-10 17:42:56 -0700673 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700674 applyStreamVolumes(outputDesc, newDevice, waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700675 }
676 }
677
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800678 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800679 audio_devices_t newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700680 // Force new input selection if the new device can not be reached via current input
Eric Laurentfb66dd92016-01-28 18:32:03 -0800681 if (activeDesc->mProfile->getSupportedDevices().types() &
682 (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
683 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700684 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800685 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700686 }
Eric Laurente552edb2014-03-10 17:42:56 -0700687 }
Eric Laurente552edb2014-03-10 17:42:56 -0700688}
689
Eric Laurente0720872014-03-11 09:30:41 -0700690void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700691{
692 ALOGV("setSystemProperty() property %s, value %s", property, value);
693}
694
Michael Chana94fbb22018-04-24 14:31:19 +1000695// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
696// search to profiles for direct outputs.
697sp<IOProfile> AudioPolicyManager::getProfileForOutput(
698 audio_devices_t device,
699 uint32_t samplingRate,
700 audio_format_t format,
701 audio_channel_mask_t channelMask,
702 audio_output_flags_t flags,
703 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700704{
Michael Chana94fbb22018-04-24 14:31:19 +1000705 if (directOnly) {
706 // only retain flags that will drive the direct output profile selection
707 // if explicitly requested
708 static const uint32_t kRelevantFlags =
709 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
710 AUDIO_OUTPUT_FLAG_VOIP_RX);
711 flags =
712 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
713 }
Eric Laurent861a6282015-05-18 15:40:16 -0700714
715 sp<IOProfile> profile;
716
Mikhail Naganovd4120142017-12-06 15:49:22 -0800717 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800718 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent861a6282015-05-18 15:40:16 -0700719 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700720 samplingRate, NULL /*updatedSamplingRate*/,
721 format, NULL /*updatedFormat*/,
722 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700723 flags)) {
724 continue;
725 }
726 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100727 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700728 continue;
729 }
Michael Chana94fbb22018-04-24 14:31:19 +1000730 if (!directOnly) return curProfile;
731 // when searching for direct outputs, if several profiles are compatible, give priority
732 // to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100733 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700734 continue;
735 }
736 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100737 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700738 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700739 }
Eric Laurente552edb2014-03-10 17:42:56 -0700740 }
741 }
Eric Laurent861a6282015-05-18 15:40:16 -0700742 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700743}
744
Eric Laurentf4e63452017-11-06 19:31:46 +0000745audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700746{
Eric Laurent3b73df72014-03-11 09:06:29 -0700747 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700748 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800749
750 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
751 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
752 // format, flags, etc. This may result in some discrepancy for functions that utilize
753 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
754 // and AudioSystem::getOutputSamplingRate().
755
Eric Laurentf4e63452017-11-06 19:31:46 +0000756 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
757 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
Eric Laurente552edb2014-03-10 17:42:56 -0700758
Eric Laurentf4e63452017-11-06 19:31:46 +0000759 ALOGV("getOutput() stream %d selected device %08x, output %d", stream, device, output);
760 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700761}
762
Eric Laurente83b55d2014-11-14 10:06:21 -0800763status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
764 audio_io_handle_t *output,
765 audio_session_t session,
766 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700767 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800768 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200769 audio_output_flags_t *flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700770 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800771 audio_port_handle_t *portId)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700772{
Eric Laurente83b55d2014-11-14 10:06:21 -0800773 audio_attributes_t attributes;
Eric Laurent8fc147b2018-07-22 19:13:55 -0700774 DeviceVector outputDevices;
775 routing_strategy strategy;
776 audio_devices_t device;
Eric Laurent97ac8712018-07-27 18:59:02 -0700777 const audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100778 audio_devices_t msdDevice = getMsdAudioOutDeviceTypes();
Eric Laurent8fc147b2018-07-22 19:13:55 -0700779
Eric Laurent8f42ea12018-08-08 09:08:25 -0700780 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
781 if (*portId != AUDIO_PORT_HANDLE_NONE) {
782 return INVALID_OPERATION;
783 }
784
Eric Laurente83b55d2014-11-14 10:06:21 -0800785 if (attr != NULL) {
786 if (!isValidAttributes(attr)) {
787 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
788 attr->usage, attr->content_type, attr->flags,
789 attr->tags);
790 return BAD_VALUE;
791 }
792 attributes = *attr;
793 } else {
794 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
795 ALOGE("getOutputForAttr(): invalid stream type");
796 return BAD_VALUE;
797 }
798 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700799 }
Eric Laurent20b9ef02016-12-05 11:03:16 -0800800
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700801 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
Eric Laurent97ac8712018-07-27 18:59:02 -0700802 " session %d selectedDeviceId %d",
803 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
804 session, requestedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700805
Eric Laurent97ac8712018-07-27 18:59:02 -0700806 *stream = streamTypefromAttributesInt(&attributes);
807
808 strategy = getStrategyForAttr(&attributes);
809
Scott Randolph7b1fd232018-06-18 15:33:03 -0700810 // First check for explicit routing (eg. setPreferredDevice)
Eric Laurent97ac8712018-07-27 18:59:02 -0700811 if (requestedDeviceId != AUDIO_PORT_HANDLE_NONE) {
812 sp<DeviceDescriptor> deviceDesc =
813 mAvailableOutputDevices.getDeviceFromId(requestedDeviceId);
814 device = deviceDesc->type();
Scott Randolph7b1fd232018-06-18 15:33:03 -0700815 } else {
816 // If no explict route, is there a matching dynamic policy that applies?
817 sp<SwAudioOutputDescriptor> desc;
818 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
819 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
820 if (!audio_has_proportional_frames(config->format)) {
821 return BAD_VALUE;
822 }
823 *stream = streamTypefromAttributesInt(&attributes);
824 *output = desc->mIoHandle;
Eric Laurent97ac8712018-07-27 18:59:02 -0700825 AudioMix *mix = desc->mPolicyMix;
826 sp<DeviceDescriptor> deviceDesc =
827 mAvailableOutputDevices.getDevice(mix->mDeviceType, mix->mDeviceAddress);
828 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Scott Randolph7b1fd232018-06-18 15:33:03 -0700829 ALOGV("getOutputForAttr() returns output %d", *output);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700830 goto exit;
Scott Randolph7b1fd232018-06-18 15:33:03 -0700831 }
832
833 // Virtual sources must always be dynamicaly or explicitly routed
834 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
835 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
836 return BAD_VALUE;
837 }
Eric Laurent97ac8712018-07-27 18:59:02 -0700838 device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700839 }
Scott Randolph7b1fd232018-06-18 15:33:03 -0700840
Eric Laurente83b55d2014-11-14 10:06:21 -0800841 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200842 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -0700843 }
844
Nadav Barb2f18162018-07-18 13:01:53 +0300845 // Set incall music only if device was explicitly set, and fallback to the device which is
846 // chosen by the engine if not.
847 // FIXME: provide a more generic approach which is not device specific and move this back
848 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +0200849 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
Nadav Barb2f18162018-07-18 13:01:53 +0300850 if (device == AUDIO_DEVICE_OUT_TELEPHONY_TX &&
Nadav Bar20919492018-11-20 10:20:51 +0200851 (*stream == AUDIO_STREAM_MUSIC || attributes.usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +0300852 audio_is_linear_pcm(config->format) &&
853 isInCall()) {
Eric Laurent97ac8712018-07-27 18:59:02 -0700854 if (requestedDeviceId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +0300855 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
856 } else {
Eric Laurent97ac8712018-07-27 18:59:02 -0700857 // Get the devce type directly from the engine to bypass preferred route logic
Nadav Barb2f18162018-07-18 13:01:53 +0300858 device = mEngine->getDeviceForStrategy(strategy);
859 }
860 }
861
Glenn Kasten49f36ba2017-12-06 13:02:02 -0800862 ALOGV("getOutputForAttr() device 0x%x, sampling rate %d, format %#x, channel mask %#x, "
863 "flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +0200864 device, config->sample_rate, config->format, config->channel_mask, *flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700865
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100866 *output = AUDIO_IO_HANDLE_NONE;
867 if (msdDevice != AUDIO_DEVICE_NONE) {
868 *output = getOutputForDevice(msdDevice, session, *stream, config, flags);
869 if (*output != AUDIO_IO_HANDLE_NONE && setMsdPatch(device) == NO_ERROR) {
870 ALOGV("%s() Using MSD device 0x%x instead of device 0x%x",
871 __func__, msdDevice, device);
872 device = msdDevice;
873 } else {
874 *output = AUDIO_IO_HANDLE_NONE;
875 }
876 }
877 if (*output == AUDIO_IO_HANDLE_NONE) {
878 *output = getOutputForDevice(device, session, *stream, config, flags);
879 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800880 if (*output == AUDIO_IO_HANDLE_NONE) {
881 return INVALID_OPERATION;
882 }
Paul McLeanaa981192015-03-21 09:55:15 -0700883
Eric Laurent8fc147b2018-07-22 19:13:55 -0700884 outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -0700885 *selectedDeviceId = outputDevices.size() > 0 ? outputDevices.itemAt(0)->getId()
886 : AUDIO_PORT_HANDLE_NONE;
887
Eric Laurent8fc147b2018-07-22 19:13:55 -0700888exit:
889 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
890 .format = config->format,
891 .channel_mask = config->channel_mask };
Eric Laurent8f42ea12018-08-08 09:08:25 -0700892 *portId = AudioPort::getNextUniqueId();
893
Eric Laurent8fc147b2018-07-22 19:13:55 -0700894 sp<TrackClientDescriptor> clientDesc =
Eric Laurent97ac8712018-07-27 18:59:02 -0700895 new TrackClientDescriptor(*portId, uid, session, attributes, clientConfig,
896 requestedDeviceId, *stream,
897 getStrategyForAttr(&attributes),
898 *flags);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700899 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Andy Hung39efb7a2018-09-26 15:39:28 -0700900 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700901
902 ALOGV(" getOutputForAttr() returns output %d selectedDeviceId %d for port ID %d",
903 *output, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -0700904
Eric Laurente83b55d2014-11-14 10:06:21 -0800905 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700906}
907
908audio_io_handle_t AudioPolicyManager::getOutputForDevice(
909 audio_devices_t device,
Kevin Rocard169753c2017-03-06 14:18:23 -0800910 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700911 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -0800912 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200913 audio_output_flags_t *flags)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700914{
Andy Hungc88b0642018-04-27 15:42:35 -0700915 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700916 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700917
Eric Laurente552edb2014-03-10 17:42:56 -0700918 // open a direct output if required by specified parameters
919 //force direct flag if offload flag is set: offloading implies a direct output stream
920 // and all common behaviors are driven by checking only the direct flag
921 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +0200922 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
923 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700924 }
Nadav Bar766fb022018-01-07 12:18:03 +0200925 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
926 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -0700927 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800928 // only allow deep buffering for music stream type
929 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +0200930 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700931 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +0200932 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700933 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
934 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +0200935 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800936 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700937 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +0200938 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700939 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +0200940 audio_is_linear_pcm(config->format) &&
941 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200942 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700943 AUDIO_OUTPUT_FLAG_DIRECT);
944 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700945 }
Eric Laurente552edb2014-03-10 17:42:56 -0700946
Nadav Bar766fb022018-01-07 12:18:03 +0200947
Eric Laurentb732cf52014-09-24 19:08:21 -0700948 sp<IOProfile> profile;
949
950 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700951 // and not explicitly requested
Nadav Bar766fb022018-01-07 12:18:03 +0200952 if (((*flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Eric Laurentfe231122017-11-17 17:48:06 -0800953 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
954 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
Eric Laurentb732cf52014-09-24 19:08:21 -0700955 goto non_direct_output;
956 }
957
Andy Hung2ddee192015-12-18 17:34:44 -0800958 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
959 // This prevents creating an offloaded track and tearing it down immediately after start
960 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700961 // FIXME: We should check the audio session here but we do not have it in this context.
962 // This may prevent offloading in rare situations where effects are left active by apps
963 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700964
Nadav Bar766fb022018-01-07 12:18:03 +0200965 if (((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800966 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Michael Chana94fbb22018-04-24 14:31:19 +1000967 profile = getProfileForOutput(device,
968 config->sample_rate,
969 config->format,
970 config->channel_mask,
971 (audio_output_flags_t)*flags,
972 true /* directOnly */);
Eric Laurente552edb2014-03-10 17:42:56 -0700973 }
974
Eric Laurent1c333e22014-05-20 10:48:17 -0700975 if (profile != 0) {
Andy Hungc88b0642018-04-27 15:42:35 -0700976 // exclusive outputs for MMAP and Offload are enforced by different session ids.
977 for (size_t i = 0; i < mOutputs.size(); i++) {
978 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
979 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
980 // reuse direct output if currently open by the same client
981 // and configured with same parameters
982 if ((config->sample_rate == desc->mSamplingRate) &&
Andy Hung5659ed52018-04-30 10:31:26 -0700983 (config->format == desc->mFormat) &&
Andy Hungc88b0642018-04-27 15:42:35 -0700984 (config->channel_mask == desc->mChannelMask) &&
985 (session == desc->mDirectClientSession)) {
986 desc->mDirectOpenCount++;
987 ALOGI("getOutputForDevice() reusing direct output %d for session %d",
988 mOutputs.keyAt(i), session);
989 return mOutputs.keyAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700990 }
991 }
992 }
Eric Laurent3974e3b2017-12-07 17:58:43 -0800993
994 if (!profile->canOpenNewIo()) {
995 goto non_direct_output;
Eric Laurente552edb2014-03-10 17:42:56 -0700996 }
Eric Laurent861a6282015-05-18 15:40:16 -0700997
Eric Laurent3974e3b2017-12-07 17:58:43 -0800998 sp<SwAudioOutputDescriptor> outputDesc =
999 new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurent53b810e2017-12-10 17:25:10 -08001000
Mikhail Naganov708e0382018-05-30 09:53:04 -07001001 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -08001002 String8 address = outputDevices.size() > 0 ? outputDevices.itemAt(0)->mAddress
1003 : String8("");
1004
Dean Wheatley3023b382018-08-09 07:42:40 +10001005 // MSD patch may be using the only output stream that can service this request. Release
1006 // MSD patch to prioritize this request over any active output on MSD.
1007 AudioPatchCollection msdPatches = getMsdPatches();
1008 for (size_t i = 0; i < msdPatches.size(); i++) {
1009 const auto& patch = msdPatches[i];
1010 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1011 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1012 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
1013 (sink->ext.device.type & device) != AUDIO_DEVICE_NONE &&
1014 (address.isEmpty() || strncmp(sink->ext.device.address, address.string(),
1015 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
1016 releaseAudioPatch(patch->mHandle, mUidCached);
1017 break;
1018 }
1019 }
1020 }
1021
Nadav Bar766fb022018-01-07 12:18:03 +02001022 status = outputDesc->open(config, device, address, stream, *flags, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07001023
1024 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001025 if (status != NO_ERROR ||
Eric Laurentfe231122017-11-17 17:48:06 -08001026 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
Andy Hung5659ed52018-04-30 10:31:26 -07001027 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->mFormat) ||
Eric Laurentfe231122017-11-17 17:48:06 -08001028 (config->channel_mask != 0 && config->channel_mask != outputDesc->mChannelMask)) {
1029 ALOGV("getOutputForDevice() failed opening direct output: output %d sample rate %d %d,"
1030 "format %d %d, channel mask %04x %04x", output, config->sample_rate,
1031 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
1032 config->channel_mask, outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001033 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001034 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07001035 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001036 // fall back to mixer output if possible when the direct output could not be open
Eric Laurentfe231122017-11-17 17:48:06 -08001037 if (audio_is_linear_pcm(config->format) &&
1038 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -08001039 goto non_direct_output;
1040 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001041 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001042 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001043 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -08001044 outputDesc->mDirectClientSession = session;
1045
Eric Laurente552edb2014-03-10 17:42:56 -07001046 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001047 mPreviousOutputs = mOutputs;
Eric Laurentf4e63452017-11-06 19:31:46 +00001048 ALOGV("getOutputForDevice() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001049 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001050 return output;
1051 }
1052
Eric Laurentb732cf52014-09-24 19:08:21 -07001053non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001054
1055 // A request for HW A/V sync cannot fallback to a mixed output because time
1056 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001057 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001058 return AUDIO_IO_HANDLE_NONE;
1059 }
1060
Eric Laurente552edb2014-03-10 17:42:56 -07001061 // ignoring channel mask due to downmix capability in mixer
1062
1063 // open a non direct output
1064
1065 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001066 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001067 // get which output is suitable for the specified stream. The actual
1068 // routing change will happen when startOutput() will be called
1069 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1070
Eric Laurent8838a382014-09-08 16:44:28 -07001071 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001072 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1073 output = selectOutput(outputs, *flags, config->format);
Eric Laurente552edb2014-03-10 17:42:56 -07001074 }
Eric Laurentf4e63452017-11-06 19:31:46 +00001075 ALOGW_IF((output == 0), "getOutputForDevice() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001076 "sampling rate %d, format %#x, channels %#x, flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +02001077 stream, config->sample_rate, config->format, config->channel_mask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001078
Eric Laurente552edb2014-03-10 17:42:56 -07001079 return output;
1080}
1081
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001082sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001083 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001084 if (msdModule != 0) {
1085 DeviceVector msdInputDevices = mAvailableInputDevices.getDevicesFromHwModule(
1086 msdModule->getHandle());
1087 if (!msdInputDevices.isEmpty()) return msdInputDevices.itemAt(0);
1088 }
1089 return 0;
1090}
1091
1092audio_devices_t AudioPolicyManager::getMsdAudioOutDeviceTypes() const {
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001093 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001094 if (msdModule != 0) {
1095 return mAvailableOutputDevices.getDeviceTypesFromHwModule(msdModule->getHandle());
1096 }
1097 return AUDIO_DEVICE_NONE;
1098}
1099
1100const AudioPatchCollection AudioPolicyManager::getMsdPatches() const {
1101 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001102 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1103 if (msdModule != 0) {
1104 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1105 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1106 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1107 const struct audio_port_config *source = &patch->mPatch.sources[j];
1108 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1109 source->ext.device.hw_module == msdModule->getHandle()) {
1110 msdPatches.addAudioPatch(patch->mHandle, patch);
1111 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001112 }
1113 }
1114 }
1115 return msdPatches;
1116}
1117
1118status_t AudioPolicyManager::getBestMsdAudioProfileFor(audio_devices_t outputDevice,
1119 bool hwAvSync, audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1120{
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001121 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001122 if (msdModule == nullptr) {
1123 ALOGE("%s() unable to get MSD module", __func__);
1124 return NO_INIT;
1125 }
1126 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(outputDevice);
1127 if (deviceModule == nullptr) {
1128 ALOGE("%s() unable to get module for %#x", __func__, outputDevice);
1129 return NO_INIT;
1130 }
1131 const InputProfileCollection &inputProfiles = msdModule->getInputProfiles();
1132 if (inputProfiles.isEmpty()) {
1133 ALOGE("%s() no input profiles for MSD module", __func__);
1134 return NO_INIT;
1135 }
1136 const OutputProfileCollection &outputProfiles = deviceModule->getOutputProfiles();
1137 if (outputProfiles.isEmpty()) {
1138 ALOGE("%s() no output profiles for device %#x", __func__, outputDevice);
1139 return NO_INIT;
1140 }
1141 AudioProfileVector msdProfiles;
1142 // Each IOProfile represents a MixPort from audio_policy_configuration.xml
1143 for (const auto &inProfile : inputProfiles) {
1144 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0)) {
1145 msdProfiles.appendVector(inProfile->getAudioProfiles());
1146 }
1147 }
1148 AudioProfileVector deviceProfiles;
1149 for (const auto &outProfile : outputProfiles) {
1150 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0)) {
1151 deviceProfiles.appendVector(outProfile->getAudioProfiles());
1152 }
1153 }
1154 struct audio_config_base bestSinkConfig;
1155 status_t result = msdProfiles.findBestMatchingOutputConfig(deviceProfiles,
1156 compressedFormatsOrder, surroundChannelMasksOrder, true /*preferHigherSamplingRates*/,
1157 &bestSinkConfig);
1158 if (result != NO_ERROR) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001159 ALOGD("%s() no matching profiles found for device: %#x, hwAvSync: %d",
1160 __func__, outputDevice, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001161 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001162 }
1163 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1164 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1165 sinkConfig->format = bestSinkConfig.format;
1166 // For encoded streams force direct flag to prevent downstream mixing.
1167 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1168 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
1169 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1170 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1171 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1172 sourceConfig->format = bestSinkConfig.format;
1173 // Copy input stream directly without any processing (e.g. resampling).
1174 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1175 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1176 if (hwAvSync) {
1177 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1178 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1179 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1180 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1181 }
1182 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1183 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1184 sinkConfig->config_mask |= config_mask;
1185 sourceConfig->config_mask |= config_mask;
1186 return NO_ERROR;
1187}
1188
1189PatchBuilder AudioPolicyManager::buildMsdPatch(audio_devices_t outputDevice) const
1190{
1191 PatchBuilder patchBuilder;
1192 patchBuilder.addSource(getMsdAudioInDevice()).
1193 addSink(findDevice(mAvailableOutputDevices, outputDevice));
1194 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1195 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
1196 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1197 // For now, we just forcefully try with HwAvSync first.
1198 status_t res = getBestMsdAudioProfileFor(outputDevice, true /*hwAvSync*/,
1199 &sourceConfig, &sinkConfig) == NO_ERROR ? NO_ERROR :
1200 getBestMsdAudioProfileFor(
1201 outputDevice, false /*hwAvSync*/, &sourceConfig, &sinkConfig);
1202 if (res == NO_ERROR) {
1203 // Found a matching profile for encoded audio. Re-create PatchBuilder with this config.
1204 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1205 }
1206 ALOGV("%s() no matching profile found. Fall through to default PCM patch"
1207 " supporting PCM format conversion.", __func__);
1208 return patchBuilder;
1209}
1210
1211status_t AudioPolicyManager::setMsdPatch(audio_devices_t outputDevice) {
1212 ALOGV("%s() for outputDevice %#x", __func__, outputDevice);
1213 if (outputDevice == AUDIO_DEVICE_NONE) {
1214 // Use media strategy for unspecified output device. This should only
1215 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1216 // therefore invalidate explicit routing requests.
1217 outputDevice = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
1218 }
1219 PatchBuilder patchBuilder = buildMsdPatch(outputDevice);
1220 const struct audio_patch* patch = patchBuilder.patch();
1221 const AudioPatchCollection msdPatches = getMsdPatches();
1222 if (!msdPatches.isEmpty()) {
1223 LOG_ALWAYS_FATAL_IF(msdPatches.size() > 1,
1224 "The current MSD prototype only supports one output patch");
1225 sp<AudioPatch> currentPatch = msdPatches.valueAt(0);
1226 if (audio_patches_are_equal(&currentPatch->mPatch, patch)) {
1227 return NO_ERROR;
1228 }
1229 releaseAudioPatch(currentPatch->mHandle, mUidCached);
1230 }
1231 status_t status = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1232 patch, 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1233 ALOGE_IF(status != NO_ERROR, "%s() error %d creating MSD audio patch", __func__, status);
1234 ALOGI_IF(status == NO_ERROR, "%s() Patch created from MSD_IN to "
1235 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__, outputDevice,
1236 patch->sources[0].format, patch->sources[0].channel_mask, patch->sources[0].sample_rate);
1237 return status;
1238}
1239
Eric Laurente0720872014-03-11 09:30:41 -07001240audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001241 audio_output_flags_t flags,
1242 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001243{
1244 // select one output among several that provide a path to a particular device or set of
1245 // devices (the list was previously build by getOutputsForDevice()).
1246 // The priority is as follows:
1247 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001248 // 2: the output with the bit depth the closest to the requested one
1249 // 3: the primary output
1250 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001251
1252 if (outputs.size() == 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001253 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001254 }
1255 if (outputs.size() == 1) {
1256 return outputs[0];
1257 }
1258
1259 int maxCommonFlags = 0;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001260 audio_io_handle_t outputForFlags = AUDIO_IO_HANDLE_NONE;
1261 audio_io_handle_t outputForPrimary = AUDIO_IO_HANDLE_NONE;
1262 audio_io_handle_t outputForFormat = AUDIO_IO_HANDLE_NONE;
Eric Laurente6930022016-02-11 10:20:40 -08001263 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1264 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001265
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001266 for (audio_io_handle_t output : outputs) {
1267 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001268 if (!outputDesc->isDuplicated()) {
chenhg1794d712018-10-09 15:20:37 -07001269 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1270 continue;
1271 }
Eric Laurent8838a382014-09-08 16:44:28 -07001272 // if a valid format is specified, skip output if not compatible
1273 if (format != AUDIO_FORMAT_INVALID) {
chenhg1794d712018-10-09 15:20:37 -07001274 if (!audio_is_linear_pcm(format)) {
Eric Laurent8838a382014-09-08 16:44:28 -07001275 continue;
1276 }
Eric Laurente6930022016-02-11 10:20:40 -08001277 if (AudioPort::isBetterFormatMatch(
1278 outputDesc->mFormat, bestFormat, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001279 outputForFormat = output;
Eric Laurente6930022016-02-11 10:20:40 -08001280 bestFormat = outputDesc->mFormat;
1281 }
Eric Laurent8838a382014-09-08 16:44:28 -07001282 }
1283
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001284 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001285 if (commonFlags >= maxCommonFlags) {
1286 if (commonFlags == maxCommonFlags) {
Andy Hungc9901522017-11-10 20:07:54 -08001287 if (format != AUDIO_FORMAT_INVALID
1288 && AudioPort::isBetterFormatMatch(
1289 outputDesc->mFormat, bestFormatForFlags, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001290 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001291 bestFormatForFlags = outputDesc->mFormat;
1292 }
1293 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001294 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001295 maxCommonFlags = commonFlags;
1296 bestFormatForFlags = outputDesc->mFormat;
1297 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001298 ALOGV("selectOutput() commonFlags for output %d, %04x", output, commonFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001299 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001300 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001301 outputForPrimary = output;
Eric Laurente552edb2014-03-10 17:42:56 -07001302 }
1303 }
1304 }
1305
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001306 if (outputForFlags != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001307 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001308 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001309 if (outputForFormat != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001310 return outputForFormat;
1311 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001312 if (outputForPrimary != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001313 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001314 }
1315
1316 return outputs[0];
1317}
1318
Eric Laurent8fc147b2018-07-22 19:13:55 -07001319status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001320{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001321 ALOGV("%s portId %d", __FUNCTION__, portId);
1322
1323 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1324 if (outputDesc == 0) {
1325 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001326 return BAD_VALUE;
1327 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001328 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001329
Eric Laurent8fc147b2018-07-22 19:13:55 -07001330 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001331 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001332
Eric Laurent733ce942017-12-07 12:18:25 -08001333 status_t status = outputDesc->start();
1334 if (status != NO_ERROR) {
1335 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001336 }
1337
Eric Laurent97ac8712018-07-27 18:59:02 -07001338 uint32_t delayMs;
1339 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001340
1341 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001342 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001343 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001344 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001345 if (delayMs != 0) {
1346 usleep(delayMs * 1000);
1347 }
1348
1349 return status;
1350}
1351
Eric Laurent97ac8712018-07-27 18:59:02 -07001352status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1353 const sp<TrackClientDescriptor>& client,
1354 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001355{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001356 // cannot start playback of STREAM_TTS if any other output is being used
1357 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001358
1359 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001360 audio_stream_type_t stream = client->stream();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001361 if (stream == AUDIO_STREAM_TTS) {
1362 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001363 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001364 return INVALID_OPERATION;
1365 } else {
1366 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1367 }
1368 } else {
1369 // some playback other than beacon starts
1370 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1371 }
1372
Eric Laurent77305a62016-07-25 16:39:22 -07001373 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001374 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001375 bool force = !outputDesc->isActive() &&
1376 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001377
Eric Laurent97ac8712018-07-27 18:59:02 -07001378 audio_devices_t device = AUDIO_DEVICE_NONE;
1379 AudioMix *policyMix = NULL;
1380 const char *address = NULL;
1381 if (outputDesc->mPolicyMix != NULL) {
1382 policyMix = outputDesc->mPolicyMix;
1383 address = policyMix->mDeviceAddress.string();
1384 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1385 device = policyMix->mDeviceType;
1386 } else {
1387 device = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1388 }
1389 }
1390
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001391 // requiresMuteCheck is false when we can bypass mute strategy.
1392 // It covers a common case when there is no materially active audio
1393 // and muting would result in unnecessary delay and dropped audio.
1394 const uint32_t outputLatencyMs = outputDesc->latency();
1395 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1396
Eric Laurente552edb2014-03-10 17:42:56 -07001397 // increment usage count for this stream on the requested output:
1398 // NOTE that the usage count is the same for duplicated output and hardware output which is
1399 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001400 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001401
1402 if (client->hasPreferredDevice(true)) {
1403 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
1404 if (device != outputDesc->device()) {
1405 checkStrategyRoute(getStrategy(stream), outputDesc->mIoHandle);
1406 }
1407 }
Eric Laurente552edb2014-03-10 17:42:56 -07001408
Eric Laurent36829f92017-04-07 19:04:42 -07001409 if (stream == AUDIO_STREAM_MUSIC) {
1410 selectOutputForMusicEffects();
1411 }
1412
Eric Laurent592dd7b2018-08-05 18:58:48 -07001413 if (outputDesc->streamActiveCount(stream) == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001414 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001415 if (device == AUDIO_DEVICE_NONE) {
1416 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001417 }
Eric Laurent36829f92017-04-07 19:04:42 -07001418
Eric Laurente552edb2014-03-10 17:42:56 -07001419 routing_strategy strategy = getStrategy(stream);
1420 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001421 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1422 (beaconMuteLatency > 0);
1423 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001424 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001425 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001426 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001427 // An output has a shared device if
1428 // - managed by the same hw module
1429 // - supports the currently selected device
1430 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
1431 && (desc->supportedDevices() & device) != AUDIO_DEVICE_NONE;
1432
Eric Laurent77305a62016-07-25 16:39:22 -07001433 // force a device change if any other output is:
1434 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001435 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001436 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001437 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001438 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001439 // change the device currently selected by the other output.
1440 if (sharedDevice &&
Eric Laurent77305a62016-07-25 16:39:22 -07001441 desc->device() != device &&
Eric Laurent77305a62016-07-25 16:39:22 -07001442 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001443 force = true;
1444 }
1445 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001446 // a notification so that audio focus effect can propagate, or that a mute/unmute
1447 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001448 const uint32_t latencyMs = desc->latency();
1449 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1450
1451 if (shouldWait && isActive && (waitMs < latencyMs)) {
1452 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001453 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001454
1455 // Require mute check if another output is on a shared device
1456 // and currently active to have proper drain and avoid pops.
1457 // Note restoring AudioTracks onto this output needs to invoke
1458 // a volume ramp if there is no mute.
1459 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001460 }
1461 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001462
1463 const uint32_t muteWaitMs =
1464 setOutputDevice(outputDesc, device, force, 0, NULL, address, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001465
Eric Laurente552edb2014-03-10 17:42:56 -07001466 // apply volume rules for current stream and device if necessary
1467 checkAndSetVolume(stream,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001468 mVolumeCurves->getVolumeIndex(stream, outputDesc->device()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001469 outputDesc,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001470 outputDesc->device());
Eric Laurente552edb2014-03-10 17:42:56 -07001471
1472 // update the outputs if starting an output with a stream that can affect notification
1473 // routing
1474 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001475
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001476 // force reevaluating accessibility routing when ringtone or alarm starts
1477 if (strategy == STRATEGY_SONIFICATION) {
1478 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1479 }
Eric Laurentdc462862016-07-19 12:29:53 -07001480
1481 if (waitMs > muteWaitMs) {
1482 *delayMs = waitMs - muteWaitMs;
1483 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001484
1485 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1486 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1487 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1488 // change occurs after the MixerThread starts and causes a stream volume
1489 // glitch.
1490 //
1491 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001492 }
Eric Laurentdc462862016-07-19 12:29:53 -07001493
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001494 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1495 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1496 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1497 }
1498
Eric Laurent97ac8712018-07-27 18:59:02 -07001499 // Automatically enable the remote submix input when output is started on a re routing mix
1500 // of type MIX_TYPE_RECORDERS
1501 if (audio_is_remote_submix_device(device) && policyMix != NULL &&
1502 policyMix->mMixType == MIX_TYPE_RECORDERS) {
1503 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1504 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1505 address,
1506 "remote-submix");
1507 }
1508
Eric Laurente552edb2014-03-10 17:42:56 -07001509 return NO_ERROR;
1510}
1511
Eric Laurent8fc147b2018-07-22 19:13:55 -07001512status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001513{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001514 ALOGV("%s portId %d", __FUNCTION__, portId);
1515
1516 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1517 if (outputDesc == 0) {
1518 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001519 return BAD_VALUE;
1520 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001521 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001522
Eric Laurent97ac8712018-07-27 18:59:02 -07001523 ALOGV("stopOutput() output %d, stream %d, session %d",
1524 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07001525
Eric Laurent97ac8712018-07-27 18:59:02 -07001526 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08001527
Eric Laurent733ce942017-12-07 12:18:25 -08001528 if (status == NO_ERROR ) {
1529 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001530 }
1531 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001532}
1533
Eric Laurent97ac8712018-07-27 18:59:02 -07001534status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1535 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07001536{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001537 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07001538 audio_stream_type_t stream = client->stream();
1539
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001540 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1541
Eric Laurent592dd7b2018-08-05 18:58:48 -07001542 if (outputDesc->streamActiveCount(stream) > 0) {
1543 if (outputDesc->streamActiveCount(stream) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001544 // Automatically disable the remote submix input when output is stopped on a
1545 // re routing mix of type MIX_TYPE_RECORDERS
1546 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1547 outputDesc->mPolicyMix != NULL &&
1548 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1549 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1550 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1551 outputDesc->mPolicyMix->mDeviceAddress,
1552 "remote-submix");
1553 }
1554 }
1555 bool forceDeviceUpdate = false;
1556 if (client->hasPreferredDevice(true)) {
1557 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1558 forceDeviceUpdate = true;
1559 }
1560
Eric Laurente552edb2014-03-10 17:42:56 -07001561 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07001562 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07001563
Eric Laurente552edb2014-03-10 17:42:56 -07001564 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001565 if (outputDesc->streamActiveCount(stream) == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001566 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001567 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001568 // delay the device switch by twice the latency because stopOutput() is executed when
1569 // the track stop() command is received and at that time the audio track buffer can
1570 // still contain data that needs to be drained. The latency only covers the audio HAL
1571 // and kernel buffers. Also the latency does not always include additional delay in the
1572 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001573 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001574
1575 // force restoring the device selection on other active outputs if it differs from the
1576 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001577 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001578 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001579 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001580 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001581 desc->isActive() &&
1582 outputDesc->sharesHwModuleWith(desc) &&
1583 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001584 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1585 bool force = desc->device() != newDevice2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001586
Eric Laurentc75307b2015-03-17 15:29:32 -07001587 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001588 newDevice2,
1589 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001590 delayMs);
1591 // re-apply device specific volume if not done by setOutputDevice()
1592 if (!force) {
1593 applyStreamVolumes(desc, newDevice2, delayMs);
1594 }
Eric Laurente552edb2014-03-10 17:42:56 -07001595 }
1596 }
1597 // update the outputs if stopping one with a stream that can affect notification routing
1598 handleNotificationRoutingForStream(stream);
1599 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001600
1601 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1602 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1603 setStrategyMute(STRATEGY_SONIFICATION, false, outputDesc);
1604 }
1605
Eric Laurent36829f92017-04-07 19:04:42 -07001606 if (stream == AUDIO_STREAM_MUSIC) {
1607 selectOutputForMusicEffects();
1608 }
Eric Laurente552edb2014-03-10 17:42:56 -07001609 return NO_ERROR;
1610 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001611 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001612 return INVALID_OPERATION;
1613 }
1614}
1615
Eric Laurent8fc147b2018-07-22 19:13:55 -07001616void AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001617{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001618 ALOGV("%s portId %d", __FUNCTION__, portId);
1619
1620 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1621 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07001622 // If an output descriptor is closed due to a device routing change,
1623 // then there are race conditions with releaseOutput from tracks
1624 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
1625 // destroyed shortly thereafter.
1626 //
1627 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07001628 ALOGW("releaseOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001629 return;
1630 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001631
1632 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001633
Eric Laurent8fc147b2018-07-22 19:13:55 -07001634 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1635 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001636 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07001637 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001638 return;
1639 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001640 if (--outputDesc->mDirectOpenCount == 0) {
1641 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07001642 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001643 }
1644 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001645 // stopOutput() needs to be successfully called before releaseOutput()
1646 // otherwise there may be inaccurate stream reference counts.
1647 // This is checked in outputDesc->removeClient below.
1648 outputDesc->removeClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001649}
1650
Eric Laurentcaf7f482014-11-25 17:50:47 -08001651status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1652 audio_io_handle_t *input,
1653 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001654 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001655 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001656 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001657 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001658 input_type_t *inputType,
1659 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001660{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001661 ALOGV("getInputForAttr() source %d, sampling rate %d, format %#x, channel mask %#x,"
Eric Laurentcaf7f482014-11-25 17:50:47 -08001662 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001663 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001664
Eric Laurentad2e7b92017-09-14 20:06:42 -07001665 status_t status = NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -08001666 // handle legacy remote submix case where the address was not always specified
1667 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001668 audio_source_t halInputSource;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001669 audio_source_t inputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001670 AudioMix *policyMix = NULL;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001671 DeviceVector inputDevices;
Eric Laurent8fc147b2018-07-22 19:13:55 -07001672 sp<AudioInputDescriptor> inputDesc;
1673 sp<RecordClientDescriptor> clientDesc;
1674 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001675 bool isSoundTrigger;
1676 audio_devices_t device;
1677
1678 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1679 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1680 return INVALID_OPERATION;
1681 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001682
Eric Laurentfe231122017-11-17 17:48:06 -08001683 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1684 inputSource = AUDIO_SOURCE_MIC;
1685 }
1686
Paul McLean466dc8e2015-04-17 13:15:36 -06001687 // Explicit routing?
1688 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -07001689 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
jiabinc0c831a2018-01-29 17:55:15 -08001690 deviceDesc = mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001691 }
Paul McLean466dc8e2015-04-17 13:15:36 -06001692
Eric Laurentad2e7b92017-09-14 20:06:42 -07001693 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1694 // possible
1695 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1696 *input != AUDIO_IO_HANDLE_NONE) {
1697 ssize_t index = mInputs.indexOfKey(*input);
1698 if (index < 0) {
1699 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1700 status = BAD_VALUE;
1701 goto error;
1702 }
1703 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001704 RecordClientVector clients = inputDesc->getClientsForSession(session);
1705 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001706 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1707 status = BAD_VALUE;
1708 goto error;
1709 }
1710 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1711 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001712 // corresponds to a new client and is only permitted from the same UID.
1713 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07001714 if (clients.size() > 1) {
1715 for (const auto& client : clients) {
1716 // The client map is ordered by key values (portId) and portIds are allocated
1717 // incrementaly. So the first client in this list is the one opened by audio flinger
1718 // when the mmap stream is created and should be ignored as it does not correspond
1719 // to an actual client
1720 if (client == *clients.cbegin()) {
1721 continue;
1722 }
1723 if (uid != client->uid() && !client->isSilenced()) {
1724 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
1725 uid, client->portId(), client->uid());
1726 status = INVALID_OPERATION;
1727 goto error;
1728 }
Eric Laurent331679c2018-04-16 17:03:16 -07001729 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001730 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001731 *inputType = API_INPUT_LEGACY;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001732 device = inputDesc->mDevice;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001733
Eric Laurent8f42ea12018-08-08 09:08:25 -07001734 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001735 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001736 }
1737
1738 *input = AUDIO_IO_HANDLE_NONE;
1739 *inputType = API_INPUT_INVALID;
1740
Eric Laurentad2e7b92017-09-14 20:06:42 -07001741 halInputSource = inputSource;
1742
Eric Laurentc447ded2015-01-06 08:47:05 -08001743 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001744 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001745 status = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
1746 if (status != NO_ERROR) {
1747 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001748 }
1749 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001750 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1751 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001752 } else {
Eric Laurent97ac8712018-07-27 18:59:02 -07001753 if (deviceDesc != 0) {
1754 device = deviceDesc->type();
1755 } else {
1756 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
1757 }
Eric Laurent275e8e92014-11-30 15:14:47 -08001758 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001759 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001760 status = BAD_VALUE;
1761 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001762 }
Eric Laurentc722f302014-12-10 11:21:49 -08001763 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001764 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001765 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1766 // there is an external policy, but this input is attached to a mix of recorders,
1767 // meaning it receives audio injected into the framework, so the recorder doesn't
1768 // know about it and is therefore considered "legacy"
1769 *inputType = API_INPUT_LEGACY;
1770 } else {
1771 // recording a mix of players defined by an external policy, we're rerouting for
1772 // an external policy
1773 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1774 }
Eric Laurentc722f302014-12-10 11:21:49 -08001775 } else if (audio_is_remote_submix_device(device)) {
1776 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001777 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001778 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1779 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001780 } else {
1781 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001782 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001783
Eric Laurent599c7582015-12-07 18:05:55 -08001784 }
1785
Eric Laurent8f42ea12018-08-08 09:08:25 -07001786 *input = getInputForDevice(device, address, session, inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001787 config, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001788 policyMix);
1789 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001790 status = INVALID_OPERATION;
1791 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001792 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001793
Eric Laurent8f42ea12018-08-08 09:08:25 -07001794exit:
1795
Mikhail Naganov708e0382018-05-30 09:53:04 -07001796 inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -07001797 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
Eric Laurent8f42ea12018-08-08 09:08:25 -07001798 : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07001799
Eric Laurent8f42ea12018-08-08 09:08:25 -07001800 isSoundTrigger = inputSource == AUDIO_SOURCE_HOTWORD &&
1801 mSoundTriggerSessions.indexOfKey(session) > 0;
1802 *portId = AudioPort::getNextUniqueId();
1803
Eric Laurent8fc147b2018-07-22 19:13:55 -07001804 clientDesc = new RecordClientDescriptor(*portId, uid, session,
Eric Laurent8f42ea12018-08-08 09:08:25 -07001805 *attr, *config, requestedDeviceId,
1806 inputSource,flags, isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001807 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07001808 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001809
1810 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
1811 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001812
Eric Laurent599c7582015-12-07 18:05:55 -08001813 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001814
1815error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07001816 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001817}
1818
1819
1820audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1821 String8 address,
1822 audio_session_t session,
Eric Laurent599c7582015-12-07 18:05:55 -08001823 audio_source_t inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001824 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08001825 audio_input_flags_t flags,
1826 AudioMix *policyMix)
1827{
1828 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1829 audio_source_t halInputSource = inputSource;
1830 bool isSoundTrigger = false;
1831
1832 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1833 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1834 if (index >= 0) {
1835 input = mSoundTriggerSessions.valueFor(session);
1836 isSoundTrigger = true;
1837 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1838 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1839 } else {
1840 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001841 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001842 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08001843 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001844 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001845 }
1846
Andy Hungf129b032015-04-07 13:45:50 -07001847 // find a compatible input profile (not necessarily identical in parameters)
1848 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08001849 // sampling rate and flags may be updated by getInputProfile
1850 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
1851 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07001852 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08001853 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07001854 audio_input_flags_t profileFlags = flags;
1855 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07001856 profileFormat = config->format; // reset each time through loop, in case it is updated
Eric Laurent275e8e92014-11-30 15:14:47 -08001857 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001858 profileSamplingRate, profileFormat, profileChannelMask,
1859 profileFlags);
1860 if (profile != 0) {
1861 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001862 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1863 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001864 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1865 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1866 } else { // fail
Glenn Kastenfaa10a62017-05-25 15:52:05 -07001867 ALOGW("getInputForDevice() could not find profile for device 0x%X, "
Eric Laurentfe231122017-11-17 17:48:06 -08001868 "sampling rate %u, format %#x, channel mask 0x%X, flags %#x",
1869 device, config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001870 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001871 }
Eric Laurente552edb2014-03-10 17:42:56 -07001872 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001873 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08001874 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08001875 if (samplingRate == 0) {
1876 samplingRate = profileSamplingRate;
1877 }
Eric Laurente552edb2014-03-10 17:42:56 -07001878
Eric Laurent322b4d22015-04-03 15:57:54 -07001879 if (profile->getModuleHandle() == 0) {
1880 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001881 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001882 }
1883
Eric Laurent3974e3b2017-12-07 17:58:43 -08001884 if (!profile->canOpenNewIo()) {
1885 return AUDIO_IO_HANDLE_NONE;
1886 }
1887
Eric Laurentfe231122017-11-17 17:48:06 -08001888 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001889
Eric Laurentfe231122017-11-17 17:48:06 -08001890 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
1891 lConfig.sample_rate = profileSamplingRate;
1892 lConfig.channel_mask = profileChannelMask;
1893 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07001894
Eric Laurent53b810e2017-12-10 17:25:10 -08001895 if (address == "") {
Mikhail Naganov708e0382018-05-30 09:53:04 -07001896 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -08001897 // the inputs vector must be of size >= 1, but we don't want to crash here
1898 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress : String8("");
1899 }
1900
Eric Laurentfe231122017-11-17 17:48:06 -08001901 status_t status = inputDesc->open(&lConfig, device, address,
1902 halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001903
1904 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001905 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08001906 (profileSamplingRate != lConfig.sample_rate) ||
1907 !audio_formats_match(profileFormat, lConfig.format) ||
1908 (profileChannelMask != lConfig.channel_mask)) {
1909 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001910 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08001911 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001912 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001913 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07001914 }
Eric Laurent599c7582015-12-07 18:05:55 -08001915 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001916 }
1917
Eric Laurentc722f302014-12-10 11:21:49 -08001918 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001919
Eric Laurent599c7582015-12-07 18:05:55 -08001920 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001921 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001922
Eric Laurent599c7582015-12-07 18:05:55 -08001923 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001924}
1925
Eric Laurentbb948092017-01-23 18:33:30 -08001926//static
1927bool AudioPolicyManager::isConcurrentSource(audio_source_t source)
1928{
1929 return (source == AUDIO_SOURCE_HOTWORD) ||
1930 (source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
1931 (source == AUDIO_SOURCE_FM_TUNER);
1932}
1933
Chris Thornton2b864642017-06-27 21:26:07 -07001934// FIXME: remove when concurrent capture is ready. This is a hack to work around bug b/63083537.
1935bool AudioPolicyManager::soundTriggerSupportsConcurrentCapture() {
1936 if (!mHasComputedSoundTriggerSupportsConcurrentCapture) {
1937 bool soundTriggerSupportsConcurrentCapture = false;
1938 unsigned int numModules = 0;
1939 struct sound_trigger_module_descriptor* nModules = NULL;
1940
1941 status_t status = SoundTrigger::listModules(nModules, &numModules);
1942 if (status == NO_ERROR && numModules != 0) {
1943 nModules = (struct sound_trigger_module_descriptor*) calloc(
1944 numModules, sizeof(struct sound_trigger_module_descriptor));
1945 if (nModules == NULL) {
1946 // We failed to malloc the buffer, so just say no for now, and hope that we have more
1947 // ram the next time this function is called.
1948 ALOGE("Failed to allocate buffer for module descriptors");
1949 return false;
1950 }
1951
1952 status = SoundTrigger::listModules(nModules, &numModules);
1953 if (status == NO_ERROR) {
1954 soundTriggerSupportsConcurrentCapture = true;
1955 for (size_t i = 0; i < numModules; ++i) {
1956 soundTriggerSupportsConcurrentCapture &=
1957 nModules[i].properties.concurrent_capture;
1958 }
1959 }
1960 free(nModules);
1961 }
1962 mSoundTriggerSupportsConcurrentCapture = soundTriggerSupportsConcurrentCapture;
1963 mHasComputedSoundTriggerSupportsConcurrentCapture = true;
1964 }
1965 return mSoundTriggerSupportsConcurrentCapture;
1966}
1967
Eric Laurentfb66dd92016-01-28 18:32:03 -08001968
Eric Laurent8fc147b2018-07-22 19:13:55 -07001969status_t AudioPolicyManager::startInput(audio_port_handle_t portId,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001970 bool silenced,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001971 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07001972{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001973 *concurrency = API_INPUT_CONCURRENCY_NONE;
1974
1975 ALOGV("%s portId %d", __FUNCTION__, portId);
1976
1977 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
1978 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07001979 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001980 return BAD_VALUE;
1981 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001982 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07001983 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001984 if (client->active()) {
1985 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
1986 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07001987 }
1988
Eric Laurent8f42ea12018-08-08 09:08:25 -07001989 audio_session_t session = client->session();
1990
1991 ALOGV("%s input:%d, session:%d, silenced:%d, concurrency:%d)",
1992 __FUNCTION__, input, session, silenced, *concurrency);
1993
Eric Laurent74708e72017-04-07 17:13:42 -07001994 if (!is_virtual_input_device(inputDesc->mDevice)) {
1995 if (mCallTxPatch != 0 &&
1996 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1997 ALOGW("startInput(%d) failed: call in progress", input);
Ray Essick84e84a52018-05-03 18:45:07 -07001998 *concurrency |= API_INPUT_CONCURRENCY_CALL;
Eric Laurent74708e72017-04-07 17:13:42 -07001999 return INVALID_OPERATION;
2000 }
2001
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002002 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002003
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002004 // If a UID is idle and records silence and another not silenced recording starts
2005 // from another UID (idle or active) we stop the current idle UID recording in
2006 // favor of the new one - "There can be only one" TM
2007 if (!silenced) {
2008 for (const auto& activeDesc : activeInputs) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002009 if ((activeDesc->getAudioPort()->getFlags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002010 activeDesc->getId() == inputDesc->getId()) {
2011 continue;
2012 }
2013
Eric Laurent8f42ea12018-08-08 09:08:25 -07002014 RecordClientVector activeClients = activeDesc->clientsList(true /*activeOnly*/);
2015 for (const auto& activeClient : activeClients) {
2016 if (activeClient->isSilenced()) {
2017 closeClient(activeClient->portId());
2018 ALOGV("%s client %d stopping silenced client %d", __FUNCTION__,
2019 portId, activeClient->portId());
2020 activeInputs = mInputs.getActiveInputs();
2021 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002022 }
2023 }
2024 }
2025
2026 for (const auto& activeDesc : activeInputs) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002027 if ((client->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
Eric Laurentcb4dae22017-07-01 19:39:32 -07002028 activeDesc->getId() == inputDesc->getId()) {
2029 continue;
2030 }
2031
Eric Laurent74708e72017-04-07 17:13:42 -07002032 audio_source_t activeSource = activeDesc->inputSource(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002033 if (client->source() == AUDIO_SOURCE_HOTWORD) {
Eric Laurent74708e72017-04-07 17:13:42 -07002034 if (activeSource == AUDIO_SOURCE_HOTWORD) {
2035 if (activeDesc->hasPreemptedSession(session)) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002036 ALOGW("%s input %d failed for HOTWORD: "
2037 "other input %d already started for HOTWORD", __FUNCTION__,
Eric Laurent74708e72017-04-07 17:13:42 -07002038 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07002039 *concurrency |= API_INPUT_CONCURRENCY_HOTWORD;
Eric Laurent74708e72017-04-07 17:13:42 -07002040 return INVALID_OPERATION;
2041 }
2042 } else {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002043 ALOGV("%s input %d failed for HOTWORD: other input %d already started",
2044 __FUNCTION__, input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07002045 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07002046 return INVALID_OPERATION;
2047 }
2048 } else {
2049 if (activeSource != AUDIO_SOURCE_HOTWORD) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002050 ALOGW("%s input %d failed: other input %d already started", __FUNCTION__,
Eric Laurent74708e72017-04-07 17:13:42 -07002051 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07002052 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07002053 return INVALID_OPERATION;
2054 }
2055 }
2056 }
2057
Chris Thornton2b864642017-06-27 21:26:07 -07002058 // We only need to check if the sound trigger session supports concurrent capture if the
2059 // input is also a sound trigger input. Otherwise, we should preempt any hotword stream
2060 // that's running.
2061 const bool allowConcurrentWithSoundTrigger =
2062 inputDesc->isSoundTrigger() ? soundTriggerSupportsConcurrentCapture() : false;
2063
Eric Laurent74708e72017-04-07 17:13:42 -07002064 // if capture is allowed, preempt currently active HOTWORD captures
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002065 for (const auto& activeDesc : activeInputs) {
Chris Thornton2b864642017-06-27 21:26:07 -07002066 if (allowConcurrentWithSoundTrigger && activeDesc->isSoundTrigger()) {
2067 continue;
2068 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002069 RecordClientVector activeHotwordClients =
2070 activeDesc->clientsList(true, AUDIO_SOURCE_HOTWORD);
2071 if (activeHotwordClients.size() > 0) {
Eric Laurent74708e72017-04-07 17:13:42 -07002072 SortedVector<audio_session_t> sessions = activeDesc->getPreemptedSessions();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002073
2074 for (const auto& activeClient : activeHotwordClients) {
2075 *concurrency |= API_INPUT_CONCURRENCY_PREEMPT;
2076 sessions.add(activeClient->session());
2077 closeClient(activeClient->portId());
2078 ALOGV("%s input %d for HOTWORD preempting HOTWORD input %d", __FUNCTION__,
2079 input, activeDesc->mIoHandle);
2080 }
2081
Eric Laurent74708e72017-04-07 17:13:42 -07002082 inputDesc->setPreemptedSessions(sessions);
Eric Laurent74708e72017-04-07 17:13:42 -07002083 }
2084 }
2085 }
Eric Laurente552edb2014-03-10 17:42:56 -07002086
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002087 // Make sure we start with the correct silence state
Eric Laurent8f42ea12018-08-08 09:08:25 -07002088 client->setSilenced(silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002089
Eric Laurent313d1e72016-01-29 09:56:57 -08002090 // increment activity count before calling getNewInputDevice() below as only active sessions
2091 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002092 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002093
Eric Laurent8f42ea12018-08-08 09:08:25 -07002094 // indicate active capture to sound trigger service if starting capture from a mic on
2095 // primary HW module
2096 audio_devices_t device = getNewInputDevice(inputDesc);
2097 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002098
Eric Laurent8f42ea12018-08-08 09:08:25 -07002099 status_t status = inputDesc->start();
2100 if (status != NO_ERROR) {
2101 inputDesc->setClientActive(client, false);
2102 return status;
2103 }
2104
2105 if (inputDesc->activeCount() == 1) {
2106 // if input maps to a dynamic policy with an activity listener, notify of state change
2107 if ((inputDesc->mPolicyMix != NULL)
2108 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2109 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2110 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002111 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002112
Eric Laurent8f42ea12018-08-08 09:08:25 -07002113 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2114 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2115 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
2116 SoundTrigger::setCaptureState(true);
2117 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002118
Eric Laurent8f42ea12018-08-08 09:08:25 -07002119 // automatically enable the remote submix output when input is started if not
2120 // used by a policy mix of type MIX_TYPE_RECORDERS
2121 // For remote submix (a virtual device), we open only one input per capture request.
2122 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2123 String8 address = String8("");
2124 if (inputDesc->mPolicyMix == NULL) {
2125 address = String8("0");
2126 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2127 address = inputDesc->mPolicyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002128 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002129 if (address != "") {
2130 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2131 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2132 address, "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08002133 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002134 }
Eric Laurente552edb2014-03-10 17:42:56 -07002135 }
2136
Eric Laurent8f42ea12018-08-08 09:08:25 -07002137 ALOGV("%s input %d source = %d exit", __FUNCTION__, input, client->source());
Eric Laurente552edb2014-03-10 17:42:56 -07002138
Eric Laurente552edb2014-03-10 17:42:56 -07002139 return NO_ERROR;
2140}
2141
Eric Laurent8fc147b2018-07-22 19:13:55 -07002142status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002143{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002144 ALOGV("%s portId %d", __FUNCTION__, portId);
2145
2146 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2147 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002148 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002149 return BAD_VALUE;
2150 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002151 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002152 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002153 if (!client->active()) {
2154 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002155 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002156 }
2157
Eric Laurent8f42ea12018-08-08 09:08:25 -07002158 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002159
Eric Laurent8f42ea12018-08-08 09:08:25 -07002160 inputDesc->stop();
2161 if (inputDesc->isActive()) {
2162 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2163 } else {
2164 // if input maps to a dynamic policy with an activity listener, notify of state change
2165 if ((inputDesc->mPolicyMix != NULL)
2166 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2167 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2168 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002169 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002170
2171 // automatically disable the remote submix output when input is stopped if not
2172 // used by a policy mix of type MIX_TYPE_RECORDERS
2173 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2174 String8 address = String8("");
2175 if (inputDesc->mPolicyMix == NULL) {
2176 address = String8("0");
2177 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2178 address = inputDesc->mPolicyMix->mDeviceAddress;
2179 }
2180 if (address != "") {
2181 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2182 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2183 address, "remote-submix");
2184 }
2185 }
2186
2187 audio_devices_t device = inputDesc->mDevice;
2188 resetInputDevice(input);
2189
2190 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2191 // primary HW module
2192 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2193 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2194 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
2195 SoundTrigger::setCaptureState(false);
2196 }
2197 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002198 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002199 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002200}
2201
Eric Laurent8fc147b2018-07-22 19:13:55 -07002202void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002203{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002204 ALOGV("%s portId %d", __FUNCTION__, portId);
2205
2206 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2207 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002208 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002209 return;
2210 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002211 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002212 audio_io_handle_t input = inputDesc->mIoHandle;
2213
Eric Laurent8f42ea12018-08-08 09:08:25 -07002214 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002215
Andy Hung39efb7a2018-09-26 15:39:28 -07002216 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002217
Andy Hung39efb7a2018-09-26 15:39:28 -07002218 if (inputDesc->getClientCount() > 0) {
2219 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002220 return;
2221 }
2222
Eric Laurent05b90f82014-08-27 15:32:29 -07002223 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002224 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002225 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002226}
2227
Eric Laurent8f42ea12018-08-08 09:08:25 -07002228void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002229{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002230 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002231
2232 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002233 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002234 }
2235}
2236
Eric Laurent8f42ea12018-08-08 09:08:25 -07002237void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2238{
2239 stopInput(portId);
2240 releaseInput(portId);
2241}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002242
Eric Laurentd4692962014-05-05 18:13:44 -07002243void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002244 bool patchRemoved = false;
2245
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002246 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002247 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002248 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002249 if (patch_index >= 0) {
2250 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002251 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002252 mAudioPatches.removeItemsAt(patch_index);
2253 patchRemoved = true;
2254 }
Eric Laurentfe231122017-11-17 17:48:06 -08002255 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002256 }
2257 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002258 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002259 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002260
2261 if (patchRemoved) {
2262 mpClientInterface->onAudioPatchListUpdate();
2263 }
Eric Laurentd4692962014-05-05 18:13:44 -07002264}
2265
Eric Laurente0720872014-03-11 09:30:41 -07002266void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002267 int indexMin,
2268 int indexMax)
2269{
2270 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002271 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002272
2273 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002274 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2275 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002276 continue;
2277 }
2278 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002279 }
Eric Laurente552edb2014-03-10 17:42:56 -07002280}
2281
Eric Laurente0720872014-03-11 09:30:41 -07002282status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002283 int index,
2284 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002285{
2286
Nadav Bar7c605f62017-12-25 00:01:52 +02002287 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2288 // app that has MODIFY_PHONE_STATE permission.
2289 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
2290 !(stream == AUDIO_STREAM_VOICE_CALL && index == 0)) ||
François Gaffied1ab2bd2015-12-02 18:20:06 +01002291 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002292 return BAD_VALUE;
2293 }
2294 if (!audio_is_output_device(device)) {
2295 return BAD_VALUE;
2296 }
2297
2298 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002299 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002300
Eric Laurent1fd372e2016-04-06 14:23:53 -07002301 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002302 stream, device, index);
2303
Eric Laurent28d09f02016-03-08 10:43:05 -08002304 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002305 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2306 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002307 continue;
2308 }
2309 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2310 }
Eric Laurente552edb2014-03-10 17:42:56 -07002311
Eric Laurent1fd372e2016-04-06 14:23:53 -07002312 // update volume on all outputs and streams matching the following:
2313 // - The requested stream (or a stream matching for volume control) is active on the output
2314 // - The device (or devices) selected by the strategy corresponding to this stream includes
2315 // the requested device
2316 // - For non default requested device, currently selected device on the output is either the
2317 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002318 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2319 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002320 status_t status = NO_ERROR;
2321 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002322 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2323 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08002324 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
Eric Laurent3839bc02018-07-10 18:33:34 -07002325 if (!(streamsMatchForvolume(stream, (audio_stream_type_t)curStream))) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002326 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002327 }
Eric Laurentdcd4ab12018-06-29 17:45:13 -07002328 if (!(desc->isStreamActive((audio_stream_type_t)curStream) || isInCall())) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002329 continue;
2330 }
Eric Laurent794fde22016-03-11 09:50:45 -08002331 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002332 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2333 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002334 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2335 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002336 continue;
2337 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002338 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002339 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002340 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07002341 applyVolume = (curDevice & curStreamDevice) != 0;
2342 } else {
2343 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002344 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002345 }
Eric Laurent3839bc02018-07-10 18:33:34 -07002346 // rescale index before applying to curStream as ranges may be different for
2347 // stream and curStream
2348 int idx = rescaleVolumeIndex(index, stream, (audio_stream_type_t)curStream);
Eric Laurente76f29c2016-09-14 17:17:53 -07002349 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002350 //FIXME: workaround for truncated touch sounds
2351 // delayed volume change for system stream to be removed when the problem is
2352 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002353 status_t volStatus =
Eric Laurent3839bc02018-07-10 18:33:34 -07002354 checkAndSetVolume((audio_stream_type_t)curStream, idx, desc, curDevice,
Eric Laurentdc462862016-07-19 12:29:53 -07002355 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002356 if (volStatus != NO_ERROR) {
2357 status = volStatus;
2358 }
2359 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002360 }
Eric Laurente552edb2014-03-10 17:42:56 -07002361 }
2362 return status;
2363}
2364
Eric Laurente0720872014-03-11 09:30:41 -07002365status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002366 int *index,
2367 audio_devices_t device)
2368{
2369 if (index == NULL) {
2370 return BAD_VALUE;
2371 }
2372 if (!audio_is_output_device(device)) {
2373 return BAD_VALUE;
2374 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002375 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002376 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002377 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002378 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2379 }
François Gaffiedfd74092015-03-19 12:10:59 +01002380 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002381
François Gaffied1ab2bd2015-12-02 18:20:06 +01002382 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002383 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2384 return NO_ERROR;
2385}
2386
Eric Laurent36829f92017-04-07 19:04:42 -07002387audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002388{
2389 // select one output among several suitable for global effects.
2390 // The priority is as follows:
2391 // 1: An offloaded output. If the effect ends up not being offloadable,
2392 // AudioFlinger will invalidate the track and the offloaded output
2393 // will be closed causing the effect to be moved to a PCM output.
2394 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002395 // 3: The primary output
2396 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002397
Eric Laurent3b73df72014-03-11 09:06:29 -07002398 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002399 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent36829f92017-04-07 19:04:42 -07002400 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002401
Eric Laurent36829f92017-04-07 19:04:42 -07002402 if (outputs.size() == 0) {
2403 return AUDIO_IO_HANDLE_NONE;
2404 }
Eric Laurente552edb2014-03-10 17:42:56 -07002405
Eric Laurent36829f92017-04-07 19:04:42 -07002406 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2407 bool activeOnly = true;
2408
2409 while (output == AUDIO_IO_HANDLE_NONE) {
2410 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2411 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2412 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2413
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002414 for (audio_io_handle_t output : outputs) {
2415 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002416 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2417 continue;
2418 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002419 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2420 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002421 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002422 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002423 }
2424 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002425 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002426 }
2427 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002428 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002429 }
2430 }
2431 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2432 output = outputOffloaded;
2433 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2434 output = outputDeepBuffer;
2435 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2436 output = outputPrimary;
2437 } else {
2438 output = outputs[0];
2439 }
2440 activeOnly = false;
2441 }
2442
2443 if (output != mMusicEffectOutput) {
2444 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2445 mMusicEffectOutput = output;
2446 }
2447
2448 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002449 return output;
2450}
2451
Eric Laurent36829f92017-04-07 19:04:42 -07002452audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2453{
2454 return selectOutputForMusicEffects();
2455}
2456
Eric Laurente0720872014-03-11 09:30:41 -07002457status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002458 audio_io_handle_t io,
2459 uint32_t strategy,
2460 int session,
2461 int id)
2462{
2463 ssize_t index = mOutputs.indexOfKey(io);
2464 if (index < 0) {
2465 index = mInputs.indexOfKey(io);
2466 if (index < 0) {
2467 ALOGW("registerEffect() unknown io %d", io);
2468 return INVALID_OPERATION;
2469 }
2470 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002471 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002472}
2473
Eric Laurentc75307b2015-03-17 15:29:32 -07002474bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2475{
Eric Laurent28d09f02016-03-08 10:43:05 -08002476 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002477 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2478 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002479 continue;
2480 }
2481 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2482 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002483 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002484}
2485
2486bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2487{
2488 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2489}
2490
Eric Laurente0720872014-03-11 09:30:41 -07002491bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002492{
2493 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002494 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002495 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002496 return true;
2497 }
2498 }
2499 return false;
2500}
2501
Eric Laurent275e8e92014-11-30 15:14:47 -08002502// Register a list of custom mixes with their attributes and format.
2503// When a mix is registered, corresponding input and output profiles are
2504// added to the remote submix hw module. The profile contains only the
2505// parameters (sampling rate, format...) specified by the mix.
2506// The corresponding input remote submix device is also connected.
2507//
2508// When a remote submix device is connected, the address is checked to select the
2509// appropriate profile and the corresponding input or output stream is opened.
2510//
2511// When capture starts, getInputForAttr() will:
2512// - 1 look for a mix matching the address passed in attribtutes tags if any
2513// - 2 if none found, getDeviceForInputSource() will:
2514// - 2.1 look for a mix matching the attributes source
2515// - 2.2 if none found, default to device selection by policy rules
2516// At this time, the corresponding output remote submix device is also connected
2517// and active playback use cases can be transferred to this mix if needed when reconnecting
2518// after AudioTracks are invalidated
2519//
2520// When playback starts, getOutputForAttr() will:
2521// - 1 look for a mix matching the address passed in attribtutes tags if any
2522// - 2 if none found, look for a mix matching the attributes usage
2523// - 3 if none found, default to device and output selection by policy rules.
2524
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002525status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002526{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002527 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2528 status_t res = NO_ERROR;
2529
2530 sp<HwModule> rSubmixModule;
2531 // examine each mix's route type
2532 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002533 AudioMix mix = mixes[i];
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002534 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
Eric Laurent97ac8712018-07-27 18:59:02 -07002535 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002536 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002537 break;
2538 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002539 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002540 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002541 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002542 rSubmixModule = mHwModules.getModuleFromName(
2543 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2544 if (rSubmixModule == 0) {
2545 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2546 i);
2547 res = INVALID_OPERATION;
2548 break;
2549 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002550 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002551
Eric Laurent97ac8712018-07-27 18:59:02 -07002552 String8 address = mix.mDeviceAddress;
2553 if (mix.mMixType == MIX_TYPE_PLAYERS) {
2554 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2555 } else {
2556 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
2557 }
François Gaffie036e1e92015-03-19 10:16:24 +01002558
Eric Laurent97ac8712018-07-27 18:59:02 -07002559 if (mPolicyMixes.registerMix(address, mix, 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002560 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002561 res = INVALID_OPERATION;
2562 break;
2563 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002564 audio_config_t outputConfig = mix.mFormat;
2565 audio_config_t inputConfig = mix.mFormat;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002566 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2567 // stereo and let audio flinger do the channel conversion if needed.
2568 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2569 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2570 rSubmixModule->addOutputProfile(address, &outputConfig,
2571 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2572 rSubmixModule->addInputProfile(address, &inputConfig,
2573 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002574
Eric Laurent97ac8712018-07-27 18:59:02 -07002575 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002576 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2577 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2578 address.string(), "remote-submix");
2579 } else {
2580 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2581 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2582 address.string(), "remote-submix");
2583 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002584 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2585 String8 address = mix.mDeviceAddress;
2586 audio_devices_t device = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002587 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2588 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002589
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002590 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002591 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2592 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2593 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2594 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2595 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2596 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002597 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2598 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002599 if (mPolicyMixes.registerMix(address, mix, desc) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002600 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002601 } else {
2602 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002603 }
2604 break;
2605 }
2606 }
2607
2608 if (res != NO_ERROR) {
2609 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002610 i, device, address.string());
2611 res = INVALID_OPERATION;
2612 break;
2613 } else if (!foundOutput) {
2614 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2615 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002616 res = INVALID_OPERATION;
2617 break;
2618 }
Eric Laurentc722f302014-12-10 11:21:49 -08002619 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002620 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002621 if (res != NO_ERROR) {
2622 unregisterPolicyMixes(mixes);
2623 }
2624 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002625}
2626
2627status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2628{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002629 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002630 status_t res = NO_ERROR;
2631 sp<HwModule> rSubmixModule;
2632 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002633 for (const auto& mix : mixes) {
2634 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002635
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002636 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002637 rSubmixModule = mHwModules.getModuleFromName(
2638 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2639 if (rSubmixModule == 0) {
2640 res = INVALID_OPERATION;
2641 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002642 }
2643 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002644
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002645 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002646
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002647 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2648 res = INVALID_OPERATION;
2649 continue;
2650 }
2651
2652 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2653 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2654 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2655 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2656 address.string(), "remote-submix");
2657 }
2658 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2659 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2660 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2661 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2662 address.string(), "remote-submix");
2663 }
2664 rSubmixModule->removeOutputProfile(address);
2665 rSubmixModule->removeInputProfile(address);
2666
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002667 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2668 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002669 res = INVALID_OPERATION;
2670 continue;
2671 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002672 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002673 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002674 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002675}
2676
Andy Hungc29d82b2018-10-05 12:23:17 -07002677void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07002678{
Andy Hungc29d82b2018-10-05 12:23:17 -07002679 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
2680 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07002681 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002682 std::string stateLiteral;
2683 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07002684 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002685 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
2686 "communications", "media", "record", "dock", "system",
2687 "HDMI system audio", "encoded surround output", "vibrate ringing" };
2688 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
2689 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Andy Hungc29d82b2018-10-05 12:23:17 -07002690 dst->appendFormat(" Force use for %s: %d\n",
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002691 forceUses[i], mEngine->getForceUse(i));
2692 }
Andy Hungc29d82b2018-10-05 12:23:17 -07002693 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
2694 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
2695 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
2696 mAvailableOutputDevices.dump(dst, String8("Available output"));
2697 mAvailableInputDevices.dump(dst, String8("Available input"));
2698 mHwModulesAll.dump(dst);
2699 mOutputs.dump(dst);
2700 mInputs.dump(dst);
2701 mVolumeCurves->dump(dst);
2702 mEffects.dump(dst);
2703 mAudioPatches.dump(dst);
2704 mPolicyMixes.dump(dst);
2705 mAudioSources.dump(dst);
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002706 if (!mSurroundFormats.empty()) {
Andy Hungc29d82b2018-10-05 12:23:17 -07002707 dst->append("\nEnabled Surround Formats:\n");
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002708 size_t i = 0;
2709 for (const auto& fmt : mSurroundFormats) {
Andy Hungc29d82b2018-10-05 12:23:17 -07002710 dst->append(i++ == 0 ? " " : ", ");
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002711 std::string sfmt;
2712 FormatConverter::toString(fmt, sfmt);
Andy Hungc29d82b2018-10-05 12:23:17 -07002713 dst->append(sfmt.c_str());
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002714 }
Andy Hungc29d82b2018-10-05 12:23:17 -07002715 dst->append("\n");
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002716 }
Andy Hungc29d82b2018-10-05 12:23:17 -07002717}
2718
2719status_t AudioPolicyManager::dump(int fd)
2720{
2721 String8 result;
2722 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07002723 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002724 return NO_ERROR;
2725}
2726
2727// This function checks for the parameters which can be offloaded.
2728// This can be enhanced depending on the capability of the DSP and policy
2729// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002730bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002731{
2732 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002733 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002734 offloadInfo.sample_rate, offloadInfo.channel_mask,
2735 offloadInfo.format,
2736 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2737 offloadInfo.has_video);
2738
Andy Hung2ddee192015-12-18 17:34:44 -08002739 if (mMasterMono) {
2740 return false; // no offloading if mono is set.
2741 }
2742
Eric Laurente552edb2014-03-10 17:42:56 -07002743 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07002744 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
2745 ALOGV("offload disabled by audio.offload.disable");
2746 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002747 }
2748
2749 // Check if stream type is music, then only allow offload as of now.
2750 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2751 {
2752 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2753 return false;
2754 }
2755
2756 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002757 const bool allowOffloadWithVideo =
2758 property_get_bool("audio.offload.video", false /* default_value */);
2759 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002760 ALOGV("isOffloadSupported: has_video == true, returning false");
2761 return false;
2762 }
2763
2764 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07002765 const int min_duration_secs = property_get_int32(
2766 "audio.offload.min.duration.secs", -1 /* default_value */);
2767 if (min_duration_secs >= 0) {
2768 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
2769 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%d)",
2770 min_duration_secs);
Eric Laurente552edb2014-03-10 17:42:56 -07002771 return false;
2772 }
2773 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2774 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2775 return false;
2776 }
2777
2778 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2779 // creating an offloaded track and tearing it down immediately after start when audioflinger
2780 // detects there is an active non offloadable effect.
2781 // FIXME: We should check the audio session here but we do not have it in this context.
2782 // This may prevent offloading in rare situations where effects are left active by apps
2783 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002784 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002785 return false;
2786 }
2787
2788 // See if there is a profile to support this.
2789 // AUDIO_DEVICE_NONE
Michael Chana94fbb22018-04-24 14:31:19 +10002790 sp<IOProfile> profile = getProfileForOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002791 offloadInfo.sample_rate,
2792 offloadInfo.format,
2793 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10002794 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
2795 true /* directOnly */);
Eric Laurent1c333e22014-05-20 10:48:17 -07002796 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2797 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002798}
2799
Michael Chana94fbb22018-04-24 14:31:19 +10002800bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
2801 const audio_attributes_t& attributes) {
2802 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
2803 audio_attributes_flags_to_audio_output_flags(attributes.flags, output_flags);
2804 sp<IOProfile> profile = getProfileForOutput(AUDIO_DEVICE_NONE /*ignore device */,
2805 config.sample_rate,
2806 config.format,
2807 config.channel_mask,
2808 output_flags,
2809 true /* directOnly */);
2810 ALOGV("%s() profile %sfound with name: %s, "
2811 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
2812 __FUNCTION__, profile != 0 ? "" : "NOT ",
2813 (profile != 0 ? profile->getTagName().string() : "null"),
2814 config.sample_rate, config.format, config.channel_mask, output_flags);
2815 return (profile != 0);
2816}
2817
Eric Laurent6a94d692014-05-20 11:18:06 -07002818status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2819 audio_port_type_t type,
2820 unsigned int *num_ports,
2821 struct audio_port *ports,
2822 unsigned int *generation)
2823{
2824 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2825 generation == NULL) {
2826 return BAD_VALUE;
2827 }
2828 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2829 if (ports == NULL) {
2830 *num_ports = 0;
2831 }
2832
2833 size_t portsWritten = 0;
2834 size_t portsMax = *num_ports;
2835 *num_ports = 0;
2836 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002837 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2838 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002839 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002840 for (const auto& dev : mAvailableOutputDevices) {
2841 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002842 continue;
2843 }
2844 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002845 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002846 }
2847 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002848 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002849 }
2850 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002851 for (const auto& dev : mAvailableInputDevices) {
2852 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002853 continue;
2854 }
2855 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002856 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002857 }
2858 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002859 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002860 }
2861 }
2862 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2863 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2864 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2865 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2866 }
2867 *num_ports += mInputs.size();
2868 }
2869 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002870 size_t numOutputs = 0;
2871 for (size_t i = 0; i < mOutputs.size(); i++) {
2872 if (!mOutputs[i]->isDuplicated()) {
2873 numOutputs++;
2874 if (portsWritten < portsMax) {
2875 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2876 }
2877 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002878 }
Eric Laurent84c70242014-06-23 08:46:27 -07002879 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002880 }
2881 }
2882 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002883 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002884 return NO_ERROR;
2885}
2886
Eric Laurent99fcae42018-05-17 16:59:18 -07002887status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07002888{
Eric Laurent99fcae42018-05-17 16:59:18 -07002889 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
2890 return BAD_VALUE;
2891 }
2892 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
2893 if (dev != 0) {
2894 dev->toAudioPort(port);
2895 return NO_ERROR;
2896 }
2897 dev = mAvailableInputDevices.getDeviceFromId(port->id);
2898 if (dev != 0) {
2899 dev->toAudioPort(port);
2900 return NO_ERROR;
2901 }
2902 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
2903 if (out != 0) {
2904 out->toAudioPort(port);
2905 return NO_ERROR;
2906 }
2907 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
2908 if (in != 0) {
2909 in->toAudioPort(port);
2910 return NO_ERROR;
2911 }
2912 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002913}
2914
Eric Laurent6a94d692014-05-20 11:18:06 -07002915status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2916 audio_patch_handle_t *handle,
2917 uid_t uid)
2918{
2919 ALOGV("createAudioPatch()");
2920
2921 if (handle == NULL || patch == NULL) {
2922 return BAD_VALUE;
2923 }
2924 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2925
Mikhail Naganovac9858b2018-06-15 13:12:37 -07002926 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07002927 return BAD_VALUE;
2928 }
2929 // only one source per audio patch supported for now
2930 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002931 return INVALID_OPERATION;
2932 }
Eric Laurent874c42872014-08-08 15:13:39 -07002933
2934 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002935 return INVALID_OPERATION;
2936 }
Eric Laurent874c42872014-08-08 15:13:39 -07002937 for (size_t i = 0; i < patch->num_sinks; i++) {
2938 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2939 return INVALID_OPERATION;
2940 }
2941 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002942
2943 sp<AudioPatch> patchDesc;
2944 ssize_t index = mAudioPatches.indexOfKey(*handle);
2945
Eric Laurent6a94d692014-05-20 11:18:06 -07002946 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2947 patch->sources[0].role,
2948 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002949#if LOG_NDEBUG == 0
2950 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002951 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002952 patch->sinks[i].role,
2953 patch->sinks[i].type);
2954 }
2955#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002956
2957 if (index >= 0) {
2958 patchDesc = mAudioPatches.valueAt(index);
2959 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2960 mUidCached, patchDesc->mUid, uid);
2961 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2962 return INVALID_OPERATION;
2963 }
2964 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002965 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002966 }
2967
2968 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002969 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002970 if (outputDesc == NULL) {
2971 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2972 return BAD_VALUE;
2973 }
Eric Laurent84c70242014-06-23 08:46:27 -07002974 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2975 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002976 if (patchDesc != 0) {
2977 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2978 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2979 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2980 return BAD_VALUE;
2981 }
2982 }
Eric Laurent874c42872014-08-08 15:13:39 -07002983 DeviceVector devices;
2984 for (size_t i = 0; i < patch->num_sinks; i++) {
2985 // Only support mix to devices connection
2986 // TODO add support for mix to mix connection
2987 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2988 ALOGV("createAudioPatch() source mix but sink is not a device");
2989 return INVALID_OPERATION;
2990 }
2991 sp<DeviceDescriptor> devDesc =
2992 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2993 if (devDesc == 0) {
2994 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2995 return BAD_VALUE;
2996 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002997
François Gaffie53615e22015-03-19 09:24:12 +01002998 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002999 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07003000 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01003001 NULL, // updatedSamplingRate
3002 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003003 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01003004 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003005 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01003006 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07003007 ALOGV("createAudioPatch() profile not supported for device %08x",
3008 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07003009 return INVALID_OPERATION;
3010 }
3011 devices.add(devDesc);
3012 }
3013 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003014 return INVALID_OPERATION;
3015 }
Eric Laurent874c42872014-08-08 15:13:39 -07003016
Eric Laurent6a94d692014-05-20 11:18:06 -07003017 // TODO: reconfigure output format and channels here
3018 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07003019 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07003020 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003021 index = mAudioPatches.indexOfKey(*handle);
3022 if (index >= 0) {
3023 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3024 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
3025 }
3026 patchDesc = mAudioPatches.valueAt(index);
3027 patchDesc->mUid = uid;
3028 ALOGV("createAudioPatch() success");
3029 } else {
3030 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
3031 return INVALID_OPERATION;
3032 }
3033 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3034 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3035 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003036 // only one sink supported when connecting an input device to a mix
3037 if (patch->num_sinks > 1) {
3038 return INVALID_OPERATION;
3039 }
François Gaffie53615e22015-03-19 09:24:12 +01003040 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003041 if (inputDesc == NULL) {
3042 return BAD_VALUE;
3043 }
3044 if (patchDesc != 0) {
3045 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3046 return BAD_VALUE;
3047 }
3048 }
3049 sp<DeviceDescriptor> devDesc =
3050 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
3051 if (devDesc == 0) {
3052 return BAD_VALUE;
3053 }
3054
François Gaffie53615e22015-03-19 09:24:12 +01003055 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08003056 devDesc->mAddress,
3057 patch->sinks[0].sample_rate,
3058 NULL, /*updatedSampleRate*/
3059 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003060 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003061 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003062 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003063 // FIXME for the parameter type,
3064 // and the NONE
3065 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003066 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003067 return INVALID_OPERATION;
3068 }
3069 // TODO: reconfigure output format and channels here
3070 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01003071 devDesc->type(), inputDesc->mIoHandle);
3072 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003073 index = mAudioPatches.indexOfKey(*handle);
3074 if (index >= 0) {
3075 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3076 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
3077 }
3078 patchDesc = mAudioPatches.valueAt(index);
3079 patchDesc->mUid = uid;
3080 ALOGV("createAudioPatch() success");
3081 } else {
3082 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
3083 return INVALID_OPERATION;
3084 }
3085 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3086 // device to device connection
3087 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003088 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003089 return BAD_VALUE;
3090 }
3091 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003092 sp<DeviceDescriptor> srcDeviceDesc =
3093 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07003094 if (srcDeviceDesc == 0) {
3095 return BAD_VALUE;
3096 }
Eric Laurent874c42872014-08-08 15:13:39 -07003097
Eric Laurent6a94d692014-05-20 11:18:06 -07003098 //update source and sink with our own data as the data passed in the patch may
3099 // be incomplete.
3100 struct audio_patch newPatch = *patch;
3101 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003102
Eric Laurent874c42872014-08-08 15:13:39 -07003103 for (size_t i = 0; i < patch->num_sinks; i++) {
3104 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3105 ALOGV("createAudioPatch() source device but one sink is not a device");
3106 return INVALID_OPERATION;
3107 }
3108
3109 sp<DeviceDescriptor> sinkDeviceDesc =
3110 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3111 if (sinkDeviceDesc == 0) {
3112 return BAD_VALUE;
3113 }
3114 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
3115
Eric Laurent3bcf8592015-04-03 12:13:24 -07003116 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003117 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003118 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08003119 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003120 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003121 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003122 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003123 return INVALID_OPERATION;
3124 }
Eric Laurent874c42872014-08-08 15:13:39 -07003125 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01003126 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003127 // if the sink device is reachable via an opened output stream, request to go via
3128 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07003129 audio_io_handle_t output = selectOutput(outputs,
3130 AUDIO_OUTPUT_FLAG_NONE,
3131 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07003132 if (output != AUDIO_IO_HANDLE_NONE) {
3133 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3134 if (outputDesc->isDuplicated()) {
3135 return INVALID_OPERATION;
3136 }
3137 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003138 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003139 newPatch.num_sources = 2;
3140 }
Eric Laurent83b88082014-06-20 18:31:16 -07003141 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003142 }
3143 // TODO: check from routing capabilities in config file and other conflicting patches
3144
Mikhail Naganovdc769682018-05-04 15:34:08 -07003145 status_t status = installPatch(__func__, index, handle, &newPatch, 0, uid, &patchDesc);
3146 if (status != NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003147 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3148 status);
3149 return INVALID_OPERATION;
3150 }
3151 } else {
3152 return BAD_VALUE;
3153 }
3154 } else {
3155 return BAD_VALUE;
3156 }
3157 return NO_ERROR;
3158}
3159
3160status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3161 uid_t uid)
3162{
3163 ALOGV("releaseAudioPatch() patch %d", handle);
3164
3165 ssize_t index = mAudioPatches.indexOfKey(handle);
3166
3167 if (index < 0) {
3168 return BAD_VALUE;
3169 }
3170 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3171 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3172 mUidCached, patchDesc->mUid, uid);
3173 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3174 return INVALID_OPERATION;
3175 }
3176
3177 struct audio_patch *patch = &patchDesc->mPatch;
3178 patchDesc->mUid = mUidCached;
3179 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003180 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003181 if (outputDesc == NULL) {
3182 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3183 return BAD_VALUE;
3184 }
3185
Eric Laurentc75307b2015-03-17 15:29:32 -07003186 setOutputDevice(outputDesc,
3187 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07003188 true,
3189 0,
3190 NULL);
3191 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3192 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003193 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003194 if (inputDesc == NULL) {
3195 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3196 return BAD_VALUE;
3197 }
3198 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003199 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003200 true,
3201 NULL);
3202 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003203 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3204 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3205 status, patchDesc->mAfPatchHandle);
3206 removeAudioPatch(patchDesc->mHandle);
3207 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003208 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003209 } else {
3210 return BAD_VALUE;
3211 }
3212 } else {
3213 return BAD_VALUE;
3214 }
3215 return NO_ERROR;
3216}
3217
3218status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3219 struct audio_patch *patches,
3220 unsigned int *generation)
3221{
François Gaffie53615e22015-03-19 09:24:12 +01003222 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003223 return BAD_VALUE;
3224 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003225 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003226 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003227}
3228
Eric Laurente1715a42014-05-20 11:30:42 -07003229status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003230{
Eric Laurente1715a42014-05-20 11:30:42 -07003231 ALOGV("setAudioPortConfig()");
3232
3233 if (config == NULL) {
3234 return BAD_VALUE;
3235 }
3236 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3237 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003238 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3239 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003240 }
3241
Eric Laurenta121f902014-06-03 13:32:54 -07003242 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003243 if (config->type == AUDIO_PORT_TYPE_MIX) {
3244 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003245 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003246 if (outputDesc == NULL) {
3247 return BAD_VALUE;
3248 }
Eric Laurent84c70242014-06-23 08:46:27 -07003249 ALOG_ASSERT(!outputDesc->isDuplicated(),
3250 "setAudioPortConfig() called on duplicated output %d",
3251 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003252 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003253 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003254 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003255 if (inputDesc == NULL) {
3256 return BAD_VALUE;
3257 }
Eric Laurenta121f902014-06-03 13:32:54 -07003258 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003259 } else {
3260 return BAD_VALUE;
3261 }
3262 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3263 sp<DeviceDescriptor> deviceDesc;
3264 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3265 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3266 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3267 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3268 } else {
3269 return BAD_VALUE;
3270 }
3271 if (deviceDesc == NULL) {
3272 return BAD_VALUE;
3273 }
Eric Laurenta121f902014-06-03 13:32:54 -07003274 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003275 } else {
3276 return BAD_VALUE;
3277 }
3278
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003279 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003280 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3281 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003282 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003283 audioPortConfig->toAudioPortConfig(&newConfig, config);
3284 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003285 }
Eric Laurenta121f902014-06-03 13:32:54 -07003286 if (status != NO_ERROR) {
3287 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003288 }
Eric Laurente1715a42014-05-20 11:30:42 -07003289
3290 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003291}
3292
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003293void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3294{
Eric Laurentd60560a2015-04-10 11:31:20 -07003295 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003296 clearAudioPatches(uid);
3297 clearSessionRoutes(uid);
3298}
3299
Eric Laurent6a94d692014-05-20 11:18:06 -07003300void AudioPolicyManager::clearAudioPatches(uid_t uid)
3301{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003302 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003303 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3304 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003305 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003306 }
3307 }
3308}
3309
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003310void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3311 audio_io_handle_t ouptutToSkip)
3312{
3313 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3314 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3315 for (size_t j = 0; j < mOutputs.size(); j++) {
3316 if (mOutputs.keyAt(j) == ouptutToSkip) {
3317 continue;
3318 }
3319 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3320 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3321 continue;
3322 }
3323 // If the default device for this strategy is on another output mix,
3324 // invalidate all tracks in this strategy to force re connection.
3325 // Otherwise select new device on the output mix.
3326 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003327 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003328 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3329 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3330 }
3331 }
3332 } else {
3333 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3334 setOutputDevice(outputDesc, newDevice, false);
3335 }
3336 }
3337}
3338
3339void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3340{
3341 // remove output routes associated with this uid
3342 SortedVector<routing_strategy> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07003343 for (size_t i = 0; i < mOutputs.size(); i++) {
3344 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003345 for (const auto& client : outputDesc->getClientIterable()) {
3346 if (client->hasPreferredDevice() && client->uid() == uid) {
3347 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3348 affectedStrategies.add(getStrategy(client->stream()));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003349 }
3350 }
3351 }
3352 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003353 for (const auto& strategy : affectedStrategies) {
3354 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003355 }
3356
3357 // remove input routes associated with this uid
3358 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07003359 for (size_t i = 0; i < mInputs.size(); i++) {
3360 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003361 for (const auto& client : inputDesc->getClientIterable()) {
3362 if (client->hasPreferredDevice() && client->uid() == uid) {
3363 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3364 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003365 }
3366 }
3367 }
3368 // reroute inputs if necessary
3369 SortedVector<audio_io_handle_t> inputsToClose;
3370 for (size_t i = 0; i < mInputs.size(); i++) {
3371 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003372 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003373 inputsToClose.add(inputDesc->mIoHandle);
3374 }
3375 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003376 for (const auto& input : inputsToClose) {
3377 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003378 }
3379}
3380
Eric Laurentd60560a2015-04-10 11:31:20 -07003381void AudioPolicyManager::clearAudioSources(uid_t uid)
3382{
3383 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003384 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3385 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07003386 stopAudioSource(mAudioSources.keyAt(i));
3387 }
3388 }
3389}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003390
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003391status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3392 audio_io_handle_t *ioHandle,
3393 audio_devices_t *device)
3394{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003395 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3396 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003397 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003398
François Gaffiedf372692015-03-19 10:43:27 +01003399 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003400}
3401
Eric Laurentd60560a2015-04-10 11:31:20 -07003402status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003403 const audio_attributes_t *attributes,
3404 audio_port_handle_t *portId,
3405 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003406{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003407 ALOGV("%s", __FUNCTION__);
3408 *portId = AUDIO_PORT_HANDLE_NONE;
3409
3410 if (source == NULL || attributes == NULL || portId == NULL) {
3411 ALOGW("%s invalid argument: source %p attributes %p handle %p",
3412 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003413 return BAD_VALUE;
3414 }
3415
Eric Laurentd60560a2015-04-10 11:31:20 -07003416 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3417 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003418 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
3419 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003420 return INVALID_OPERATION;
3421 }
3422
3423 sp<DeviceDescriptor> srcDeviceDesc =
3424 mAvailableInputDevices.getDevice(source->ext.device.type,
3425 String8(source->ext.device.address));
3426 if (srcDeviceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003427 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003428 return BAD_VALUE;
3429 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003430
3431 *portId = AudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07003432
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003433 struct audio_patch dummyPatch = {};
Eric Laurentd60560a2015-04-10 11:31:20 -07003434 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003435
3436 sp<SourceClientDescriptor> sourceDesc =
3437 new SourceClientDescriptor(*portId, uid, *attributes, patchDesc, srcDeviceDesc,
Eric Laurent97ac8712018-07-27 18:59:02 -07003438 streamTypefromAttributesInt(attributes),
3439 getStrategyForAttr(attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07003440
3441 status_t status = connectAudioSource(sourceDesc);
3442 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003443 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003444 }
3445 return status;
3446}
3447
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003448status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003449{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003450 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003451
3452 // make sure we only have one patch per source.
3453 disconnectAudioSource(sourceDesc);
3454
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003455 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003456 routing_strategy strategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003457 audio_stream_type_t stream = sourceDesc->stream();
3458 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->srcDevice();
Eric Laurentd60560a2015-04-10 11:31:20 -07003459
3460 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3461 sp<DeviceDescriptor> sinkDeviceDesc =
3462 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3463
3464 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003465
3466 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3467 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003468 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003469 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3470 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3471 // create patch between src device and output device
3472 // create Hwoutput and add to mHwOutputs
3473 } else {
3474 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3475 audio_io_handle_t output =
3476 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3477 if (output == AUDIO_IO_HANDLE_NONE) {
3478 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3479 return INVALID_OPERATION;
3480 }
3481 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3482 if (outputDesc->isDuplicated()) {
3483 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3484 return INVALID_OPERATION;
3485 }
Eric Laurent733ce942017-12-07 12:18:25 -08003486 status_t status = outputDesc->start();
3487 if (status != NO_ERROR) {
3488 return status;
3489 }
3490
Eric Laurentd60560a2015-04-10 11:31:20 -07003491 // create a special patch with no sink and two sources:
3492 // - the second source indicates to PatchPanel through which output mix this patch should
3493 // be connected as well as the stream type for volume control
3494 // - the sink is defined by whatever output device is currently selected for the output
3495 // though which this patch is routed.
Mikhail Naganovdc769682018-05-04 15:34:08 -07003496 PatchBuilder patchBuilder;
3497 patchBuilder.addSource(srcDeviceDesc).addSource(outputDesc, { .stream = stream });
3498 status = mpClientInterface->createAudioPatch(patchBuilder.patch(),
Eric Laurentd60560a2015-04-10 11:31:20 -07003499 &afPatchHandle,
3500 0);
3501 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3502 status, afPatchHandle);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003503 sourceDesc->patchDesc()->mPatch = *patchBuilder.patch();
Eric Laurentd60560a2015-04-10 11:31:20 -07003504 if (status != NO_ERROR) {
3505 ALOGW("%s patch panel could not connect device patch, error %d",
3506 __FUNCTION__, status);
3507 return INVALID_OPERATION;
3508 }
3509 uint32_t delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07003510 status = startSource(outputDesc, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003511
3512 if (status != NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003513 mpClientInterface->releaseAudioPatch(sourceDesc->patchDesc()->mAfPatchHandle, 0);
Eric Laurentd60560a2015-04-10 11:31:20 -07003514 return status;
3515 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003516 sourceDesc->setSwOutput(outputDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003517 if (delayMs != 0) {
3518 usleep(delayMs * 1000);
3519 }
3520 }
3521
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003522 sourceDesc->patchDesc()->mAfPatchHandle = afPatchHandle;
3523 addAudioPatch(sourceDesc->patchDesc()->mHandle, sourceDesc->patchDesc());
Eric Laurentd60560a2015-04-10 11:31:20 -07003524
3525 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003526}
3527
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003528status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07003529{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003530 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
3531 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003532 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003533 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003534 return BAD_VALUE;
3535 }
3536 status_t status = disconnectAudioSource(sourceDesc);
3537
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003538 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003539 return status;
3540}
3541
Andy Hung2ddee192015-12-18 17:34:44 -08003542status_t AudioPolicyManager::setMasterMono(bool mono)
3543{
3544 if (mMasterMono == mono) {
3545 return NO_ERROR;
3546 }
3547 mMasterMono = mono;
3548 // if enabling mono we close all offloaded devices, which will invalidate the
3549 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3550 // for recreating the new AudioTrack as non-offloaded PCM.
3551 //
3552 // If disabling mono, we leave all tracks as is: we don't know which clients
3553 // and tracks are able to be recreated as offloaded. The next "song" should
3554 // play back offloaded.
3555 if (mMasterMono) {
3556 Vector<audio_io_handle_t> offloaded;
3557 for (size_t i = 0; i < mOutputs.size(); ++i) {
3558 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3559 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3560 offloaded.push(desc->mIoHandle);
3561 }
3562 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003563 for (const auto& handle : offloaded) {
3564 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003565 }
3566 }
3567 // update master mono for all remaining outputs
3568 for (size_t i = 0; i < mOutputs.size(); ++i) {
3569 updateMono(mOutputs.keyAt(i));
3570 }
3571 return NO_ERROR;
3572}
3573
3574status_t AudioPolicyManager::getMasterMono(bool *mono)
3575{
3576 *mono = mMasterMono;
3577 return NO_ERROR;
3578}
3579
Eric Laurentac9cef52017-06-09 15:46:26 -07003580float AudioPolicyManager::getStreamVolumeDB(
3581 audio_stream_type_t stream, int index, audio_devices_t device)
3582{
3583 return computeVolume(stream, index, device);
3584}
3585
jiabin81772902018-04-02 17:52:27 -07003586status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3587 audio_format_t *surroundFormats,
3588 bool *surroundFormatsEnabled,
3589 bool reported)
3590{
3591 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3592 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3593 return BAD_VALUE;
3594 }
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003595 ALOGV("getSurroundFormats() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p"
3596 " reported %d", *numSurroundFormats, surroundFormats, surroundFormatsEnabled, reported);
jiabin81772902018-04-02 17:52:27 -07003597
3598 // Only return value if there is HDMI output.
3599 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3600 return INVALID_OPERATION;
3601 }
3602
3603 size_t formatsWritten = 0;
3604 size_t formatsMax = *numSurroundFormats;
3605 *numSurroundFormats = 0;
Mikhail Naganov2563f232018-09-27 14:48:01 -07003606 std::unordered_set<audio_format_t> formats;
jiabin81772902018-04-02 17:52:27 -07003607 if (reported) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003608 // Return formats from HDMI profiles, that have already been resolved by
3609 // checkOutputsForDevice().
3610 DeviceVector hdmiOutputDevs = mAvailableOutputDevices.getDevicesFromTypeMask(
3611 AUDIO_DEVICE_OUT_HDMI);
3612 for (size_t i = 0; i < hdmiOutputDevs.size(); i++) {
3613 FormatVector supportedFormats =
3614 hdmiOutputDevs[i]->getAudioPort()->getAudioProfiles().getSupportedFormats();
3615 for (size_t j = 0; j < supportedFormats.size(); j++) {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003616 if (mConfig.getSurroundFormats().count(supportedFormats[j]) != 0) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003617 formats.insert(supportedFormats[j]);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003618 } else {
3619 for (const auto& pair : mConfig.getSurroundFormats()) {
3620 if (pair.second.count(supportedFormats[j]) != 0) {
3621 formats.insert(pair.first);
3622 break;
3623 }
3624 }
Mikhail Naganov2563f232018-09-27 14:48:01 -07003625 }
3626 }
jiabin81772902018-04-02 17:52:27 -07003627 }
3628 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003629 for (const auto& pair : mConfig.getSurroundFormats()) {
3630 formats.insert(pair.first);
jiabin81772902018-04-02 17:52:27 -07003631 }
3632 }
Mikhail Naganov2563f232018-09-27 14:48:01 -07003633 for (const auto& format: formats) {
jiabin81772902018-04-02 17:52:27 -07003634 if (formatsWritten < formatsMax) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003635 surroundFormats[formatsWritten] = format;
jiabin81772902018-04-02 17:52:27 -07003636 bool formatEnabled = false;
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003637 if (mConfig.getSurroundFormats().count(format) == 0) {
3638 // Check sub-formats
3639 for (const auto& pair : mConfig.getSurroundFormats()) {
3640 for (const auto& subformat : pair.second) {
3641 formatEnabled = mSurroundFormats.count(subformat) != 0;
3642 if (formatEnabled) break;
3643 }
3644 if (formatEnabled) break;
jiabin81772902018-04-02 17:52:27 -07003645 }
3646 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003647 formatEnabled = mSurroundFormats.count(format) != 0;
jiabin81772902018-04-02 17:52:27 -07003648 }
3649 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3650 }
3651 (*numSurroundFormats)++;
3652 }
3653 return NO_ERROR;
3654}
3655
3656status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3657{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003658 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
jiabin81772902018-04-02 17:52:27 -07003659 // Check if audio format is a surround formats.
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003660 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
3661 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003662 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07003663 return BAD_VALUE;
3664 }
3665
3666 // Should only be called when MANUAL.
3667 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3668 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
3669 if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003670 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07003671 return INVALID_OPERATION;
3672 }
3673
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003674 if ((mSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07003675 return NO_ERROR;
3676 }
3677
3678 // The operation is valid only when there is HDMI output available.
3679 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003680 ALOGW("%s() no HDMI out devices found", __func__);
jiabin81772902018-04-02 17:52:27 -07003681 return INVALID_OPERATION;
3682 }
3683
Mikhail Naganov2563f232018-09-27 14:48:01 -07003684 std::unordered_set<audio_format_t> surroundFormatsBackup(mSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07003685 if (enabled) {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003686 mSurroundFormats.insert(audioFormat);
3687 for (const auto& subFormat : formatIter->second) {
3688 mSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07003689 }
3690 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003691 mSurroundFormats.erase(audioFormat);
3692 for (const auto& subFormat : formatIter->second) {
3693 mSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07003694 }
3695 }
3696
3697 sp<SwAudioOutputDescriptor> outputDesc;
3698 bool profileUpdated = false;
Mikhail Naganov708e0382018-05-30 09:53:04 -07003699 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003700 AUDIO_DEVICE_OUT_HDMI);
3701 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3702 // Simulate reconnection to update enabled surround sound formats.
3703 String8 address = hdmiOutputDevices[i]->mAddress;
3704 String8 name = hdmiOutputDevices[i]->getName();
3705 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3706 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3707 address.c_str(),
3708 name.c_str());
3709 if (status != NO_ERROR) {
3710 continue;
3711 }
3712 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3713 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3714 address.c_str(),
3715 name.c_str());
3716 profileUpdated |= (status == NO_ERROR);
3717 }
Mikhail Naganov708e0382018-05-30 09:53:04 -07003718 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003719 AUDIO_DEVICE_IN_HDMI);
3720 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3721 // Simulate reconnection to update enabled surround sound formats.
3722 String8 address = hdmiInputDevices[i]->mAddress;
3723 String8 name = hdmiInputDevices[i]->getName();
3724 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3725 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3726 address.c_str(),
3727 name.c_str());
3728 if (status != NO_ERROR) {
3729 continue;
3730 }
3731 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3732 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3733 address.c_str(),
3734 name.c_str());
3735 profileUpdated |= (status == NO_ERROR);
3736 }
3737
jiabin81772902018-04-02 17:52:27 -07003738 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003739 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov2563f232018-09-27 14:48:01 -07003740 mSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07003741 }
3742
3743 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3744}
3745
Eric Laurentf32108e2018-10-04 17:22:04 -07003746void AudioPolicyManager::setAppState(uid_t uid, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003747{
Eric Laurentf32108e2018-10-04 17:22:04 -07003748 Vector<sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
3749 bool silenced = state == APP_STATE_IDLE;
3750
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003751 ALOGV("AudioPolicyManager:setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
3752
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003753 for (size_t i = 0; i < activeInputs.size(); i++) {
3754 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
Eric Laurent8f42ea12018-08-08 09:08:25 -07003755 RecordClientVector clients = activeDesc->clientsList(true /*activeOnly*/);
3756 for (const auto& client : clients) {
3757 if (uid == client->uid()) {
3758 client->setSilenced(silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003759 }
3760 }
3761 }
3762}
3763
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003764status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003765{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003766 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003767
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003768 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003769 if (patchDesc == 0) {
3770 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003771 sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003772 return BAD_VALUE;
3773 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003774 removeAudioPatch(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003775
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003776 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003777 if (swOutputDesc != 0) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003778 status_t status = stopSource(swOutputDesc, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08003779 if (status == NO_ERROR) {
3780 swOutputDesc->stop();
3781 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003782 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3783 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003784 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003785 if (hwOutputDesc != 0) {
3786 // release patch between src device and output device
3787 // close Hwoutput and remove from mHwOutputs
3788 } else {
3789 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3790 }
3791 }
3792 return NO_ERROR;
3793}
3794
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003795sp<SourceClientDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
Eric Laurentd60560a2015-04-10 11:31:20 -07003796 audio_io_handle_t output, routing_strategy strategy)
3797{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003798 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07003799 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003800 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3801 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003802 routing_strategy sourceStrategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003803 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003804 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3805 source = sourceDesc;
3806 break;
3807 }
3808 }
3809 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003810}
3811
Eric Laurente552edb2014-03-10 17:42:56 -07003812// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003813// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003814// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003815uint32_t AudioPolicyManager::nextAudioPortGeneration()
3816{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003817 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003818}
3819
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003820// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3821static const char *kConfigLocationList[] =
3822 {"/odm/etc", "/vendor/etc", "/system/etc"};
3823static const int kConfigLocationListSize =
3824 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3825
3826static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3827 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07003828 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003829 status_t ret;
3830
Petri Gyntherf497f292018-04-17 18:46:10 -07003831 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
3832 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
3833 // A2DP offload supported but disabled: try to use special XML file
3834 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
3835 }
3836 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3837
3838 for (const char* fileName : fileNames) {
3839 for (int i = 0; i < kConfigLocationListSize; i++) {
Petri Gyntherf497f292018-04-17 18:46:10 -07003840 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
3841 "%s/%s", kConfigLocationList[i], fileName);
Mikhail Naganova289aea2018-09-17 15:26:23 -07003842 ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile, &config);
Petri Gyntherf497f292018-04-17 18:46:10 -07003843 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003844 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07003845 return ret;
3846 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003847 }
3848 }
3849 return ret;
3850}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003851
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003852AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
3853 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07003854 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07003855 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003856 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07003857 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003858 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003859 mVolumeCurves(new VolumeCurvesCollection()),
3860 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08003861 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003862 mAudioPortGeneration(1),
3863 mBeaconMuteRefCount(0),
3864 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003865 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003866 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003867 mMasterMono(false),
Chris Thornton2b864642017-06-27 21:26:07 -07003868 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE),
3869 mHasComputedSoundTriggerSupportsConcurrentCapture(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003870{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003871}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003872
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003873AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
3874 : AudioPolicyManager(clientInterface, false /*forTesting*/)
3875{
3876 loadConfig();
3877 initialize();
3878}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003879
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07003880// This check is to catch any legacy platform updating to Q without having
3881// switched to XML since its deprecation on O.
3882// TODO: after Q release, remove this check and flag as XML is now the only
3883// option and all legacy platform should have transitioned to XML.
3884#ifndef USE_XML_AUDIO_POLICY_CONF
3885#error Audio policy no longer supports legacy .conf configuration format
François Gaffied1ab2bd2015-12-02 18:20:06 +01003886#endif
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07003887
3888void AudioPolicyManager::loadConfig() {
3889 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003890 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003891 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01003892 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003893}
3894
3895status_t AudioPolicyManager::initialize() {
3896 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01003897
3898 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003899 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3900 if (!engineInstance) {
3901 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003902 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003903 }
3904 // Retrieve the Policy Manager Interface
3905 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3906 if (mEngine == NULL) {
3907 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003908 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003909 }
3910 mEngine->setObserver(this);
3911 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003912 if (status != NO_ERROR) {
3913 LOG_FATAL("Policy engine not initialized(err=%d)", status);
3914 return status;
3915 }
François Gaffie2110e042015-03-24 08:41:51 +01003916
Eric Laurent3a4311c2014-03-17 12:00:47 -07003917 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003918 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003919 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3920 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Mikhail Naganovd4120142017-12-06 15:49:22 -08003921 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003922 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08003923 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
3924 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003925 continue;
3926 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08003927 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07003928 // open all output streams needed to access attached devices
3929 // except for direct output streams that are only opened when they are actually
3930 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003931 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003932 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003933 if (!outProfile->canOpenNewIo()) {
3934 ALOGE("Invalid Output profile max open count %u for profile %s",
3935 outProfile->maxOpenCount, outProfile->getTagName().c_str());
3936 continue;
3937 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003938 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003939 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003940 continue;
3941 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003942 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003943 mTtsOutputAvailable = true;
3944 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003945
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003946 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003947 continue;
3948 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003949 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003950 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3951 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003952 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003953 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003954 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003955 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003956 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003957 if ((profileType & outputDeviceTypes) == 0) {
3958 continue;
3959 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003960 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3961 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003962 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov708e0382018-05-30 09:53:04 -07003963 const DeviceVector &devicesForType = supportedDevices.getDevicesFromTypeMask(
3964 profileType);
Eric Laurentc40d9692016-04-13 19:14:13 -07003965 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3966 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003967 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08003968 status_t status = outputDesc->open(nullptr, profileType, address,
3969 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07003970
3971 if (status != NO_ERROR) {
3972 ALOGW("Cannot open output stream for device %08x on hw module %s",
3973 outputDesc->mDevice,
Mikhail Naganovd4120142017-12-06 15:49:22 -08003974 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003975 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003976 for (const auto& dev : supportedDevices) {
3977 ssize_t index = mAvailableOutputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07003978 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003979 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003980 mAvailableOutputDevices[index]->attach(hwModule);
Eric Laurentd78f1532014-09-16 16:38:20 -07003981 }
3982 }
3983 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003984 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003985 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003986 }
3987 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003988 setOutputDevice(outputDesc,
Eric Laurentfe231122017-11-17 17:48:06 -08003989 profileType,
Eric Laurentc40d9692016-04-13 19:14:13 -07003990 true,
3991 0,
3992 NULL,
Eric Laurentfe231122017-11-17 17:48:06 -08003993 address);
Eric Laurentd78f1532014-09-16 16:38:20 -07003994 }
Eric Laurente552edb2014-03-10 17:42:56 -07003995 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003996 // open input streams needed to access attached devices to validate
3997 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003998 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003999 if (!inProfile->canOpenNewIo()) {
4000 ALOGE("Invalid Input profile max open count %u for profile %s",
4001 inProfile->maxOpenCount, inProfile->getTagName().c_str());
4002 continue;
4003 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004004 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004005 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004006 continue;
4007 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004008 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07004009 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004010 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
4011
Eric Laurentd78f1532014-09-16 16:38:20 -07004012 if ((profileType & inputDeviceTypes) == 0) {
4013 continue;
4014 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08004015 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08004016 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004017
Mikhail Naganov708e0382018-05-30 09:53:04 -07004018 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(profileType);
Eric Laurent53b810e2017-12-10 17:25:10 -08004019 // the inputs vector must be of size >= 1, but we don't want to crash here
4020 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
4021 : String8("");
4022 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
4023 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
4024
Eric Laurentd78f1532014-09-16 16:38:20 -07004025 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004026 status_t status = inputDesc->open(nullptr,
4027 profileType,
Eric Laurent53b810e2017-12-10 17:25:10 -08004028 address,
Eric Laurentfe231122017-11-17 17:48:06 -08004029 AUDIO_SOURCE_MIC,
4030 AUDIO_INPUT_FLAG_NONE,
4031 &input);
Eric Laurentd78f1532014-09-16 16:38:20 -07004032
4033 if (status == NO_ERROR) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004034 for (const auto& dev : inProfile->getSupportedDevices()) {
4035 ssize_t index = mAvailableInputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07004036 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07004037 if (index >= 0) {
4038 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
4039 if (!devDesc->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004040 devDesc->attach(hwModule);
Eric Laurent83efe1c2017-07-09 16:51:08 -07004041 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07004042 }
Eric Laurentd78f1532014-09-16 16:38:20 -07004043 }
4044 }
Eric Laurentfe231122017-11-17 17:48:06 -08004045 inputDesc->close();
Eric Laurentd78f1532014-09-16 16:38:20 -07004046 } else {
4047 ALOGW("Cannot open input stream for device %08x on hw module %s",
Eric Laurentfe231122017-11-17 17:48:06 -08004048 profileType,
Mikhail Naganovd4120142017-12-06 15:49:22 -08004049 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07004050 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004051 }
4052 }
4053 // make sure all attached devices have been allocated a unique ID
4054 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004055 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004056 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004057 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
4058 continue;
4059 }
François Gaffie2110e042015-03-24 08:41:51 +01004060 // The device is now validated and can be appended to the available devices of the engine
4061 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
4062 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004063 i++;
4064 }
4065 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004066 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01004067 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004068 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
4069 continue;
4070 }
François Gaffie2110e042015-03-24 08:41:51 +01004071 // The device is now validated and can be appended to the available devices of the engine
4072 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
4073 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004074 i++;
4075 }
4076 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004077 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01004078 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004079 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004080 }
jiabin9ff780e2018-03-19 18:19:52 -07004081 // If microphones address is empty, set it according to device type
4082 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
4083 if (mAvailableInputDevices[i]->mAddress.isEmpty()) {
4084 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
4085 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
4086 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
4087 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BACK_MICROPHONE_ADDRESS);
4088 }
4089 }
4090 }
Eric Laurente552edb2014-03-10 17:42:56 -07004091
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004092 if (mPrimaryOutput == 0) {
4093 ALOGE("Failed to open primary output");
4094 status = NO_INIT;
4095 }
Eric Laurente552edb2014-03-10 17:42:56 -07004096
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09004097 // Silence ALOGV statements
4098 property_set("log.tag." LOG_TAG, "D");
4099
Eric Laurente552edb2014-03-10 17:42:56 -07004100 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004101 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004102}
4103
Eric Laurente0720872014-03-11 09:30:41 -07004104AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004105{
Eric Laurente552edb2014-03-10 17:42:56 -07004106 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004107 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004108 }
4109 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004110 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004111 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004112 mAvailableOutputDevices.clear();
4113 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004114 mOutputs.clear();
4115 mInputs.clear();
4116 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004117 mHwModulesAll.clear();
jiabin81772902018-04-02 17:52:27 -07004118 mSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004119}
4120
Eric Laurente0720872014-03-11 09:30:41 -07004121status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004122{
Eric Laurent87ffa392015-05-22 10:32:38 -07004123 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004124}
4125
Eric Laurente552edb2014-03-10 17:42:56 -07004126// ---
4127
Eric Laurent98e38192018-02-15 18:31:53 -08004128void AudioPolicyManager::addOutput(audio_io_handle_t output,
4129 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004130{
Eric Laurent1c333e22014-05-20 10:48:17 -07004131 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08004132 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004133 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004134 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004135 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004136}
4137
François Gaffie53615e22015-03-19 09:24:12 +01004138void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4139{
4140 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004141 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004142}
4143
Eric Laurent98e38192018-02-15 18:31:53 -08004144void AudioPolicyManager::addInput(audio_io_handle_t input,
4145 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004146{
Eric Laurent1c333e22014-05-20 10:48:17 -07004147 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004148 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004149}
Eric Laurente552edb2014-03-10 17:42:56 -07004150
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004151void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08004152 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004153 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004154 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08004155 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004156 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08004157 if (devDesc != 0) {
4158 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
4159 desc->mIoHandle, address.string());
4160 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004161 }
4162}
4163
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004164status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004165 audio_policy_dev_state_t state,
4166 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004167 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07004168{
François Gaffie53615e22015-03-19 09:24:12 +01004169 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07004170 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004171
4172 if (audio_device_is_digital(device)) {
4173 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004174 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004175 }
Eric Laurente552edb2014-03-10 17:42:56 -07004176
Eric Laurent3b73df72014-03-11 09:06:29 -07004177 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004178 // first list already open outputs that can be routed to this device
4179 for (size_t i = 0; i < mOutputs.size(); i++) {
4180 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07004181 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004182 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004183 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
4184 outputs.add(mOutputs.keyAt(i));
4185 } else {
4186 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08004187 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004188 }
Eric Laurente552edb2014-03-10 17:42:56 -07004189 }
4190 }
4191 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004192 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004193 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004194 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4195 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004196 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004197 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004198 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004199 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004200 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4201 j, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004202 }
Eric Laurente552edb2014-03-10 17:42:56 -07004203 }
4204 }
4205 }
4206
Eric Laurent7b279bb2015-12-14 10:18:23 -08004207 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004208
Eric Laurente552edb2014-03-10 17:42:56 -07004209 if (profiles.isEmpty() && outputs.isEmpty()) {
4210 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4211 return BAD_VALUE;
4212 }
4213
4214 // open outputs for matching profiles if needed. Direct outputs are also opened to
4215 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4216 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004217 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004218
4219 // nothing to do if one output is already opened for this profile
4220 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004221 for (j = 0; j < outputs.size(); j++) {
4222 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004223 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004224 // matching profile: save the sample rates, format and channel masks supported
4225 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07004226 if (audio_device_is_digital(device)) {
4227 devDesc->importAudioPort(profile);
4228 }
Eric Laurente552edb2014-03-10 17:42:56 -07004229 break;
4230 }
4231 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004232 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004233 continue;
4234 }
4235
Eric Laurent3974e3b2017-12-07 17:58:43 -08004236 if (!profile->canOpenNewIo()) {
4237 ALOGW("Max Output number %u already opened for this profile %s",
4238 profile->maxOpenCount, profile->getTagName().c_str());
4239 continue;
4240 }
4241
Eric Laurent83efe1c2017-07-09 16:51:08 -07004242 ALOGV("opening output for device %08x with params %s profile %p name %s",
4243 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004244 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004245 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004246 status_t status = desc->open(nullptr, device, address,
4247 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004248
Eric Laurentfe231122017-11-17 17:48:06 -08004249 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004250 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004251 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004252 char *param = audio_device_address_to_parameter(device, address);
4253 mpClientInterface->setParameters(output, String8(param));
4254 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004255 }
Phil Burk00eeb322016-03-31 12:41:00 -07004256 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004257 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004258 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004259 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004260 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004261 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004262 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004263 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004264 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4265 profile->pickAudioProfile(
4266 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004267 config.offload_info.sample_rate = config.sample_rate;
4268 config.offload_info.channel_mask = config.channel_mask;
4269 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004270
4271 status_t status = desc->open(&config, device, address, AUDIO_STREAM_DEFAULT,
4272 AUDIO_OUTPUT_FLAG_NONE, &output);
4273 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004274 output = AUDIO_IO_HANDLE_NONE;
4275 }
Eric Laurentd4692962014-05-05 18:13:44 -07004276 }
4277
Eric Laurentcf2c0212014-07-25 16:20:43 -07004278 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004279 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01004280 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004281 sp<AudioPolicyMix> policyMix;
4282 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004283 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
4284 address.string());
4285 }
François Gaffie036e1e92015-03-19 10:16:24 +01004286 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07004287 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01004288
Eric Laurent87ffa392015-05-22 10:32:38 -07004289 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4290 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004291 // no duplicated output for direct outputs and
4292 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004293 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004294
Eric Laurentd4692962014-05-05 18:13:44 -07004295 //TODO: configure audio effect output stage here
4296
4297 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004298 sp<SwAudioOutputDescriptor> dupOutputDesc =
4299 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4300 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4301 &duplicatedOutput);
4302 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004303 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004304 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004305 } else {
4306 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004307 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004308 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004309 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004310 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004311 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004312 }
Eric Laurente552edb2014-03-10 17:42:56 -07004313 }
4314 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004315 } else {
4316 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004317 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004318 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004319 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004320 profiles.removeAt(profile_index);
4321 profile_index--;
4322 } else {
4323 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004324 // Load digital format info only for digital devices
4325 if (audio_device_is_digital(device)) {
4326 devDesc->importAudioPort(profile);
4327 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004328
François Gaffie53615e22015-03-19 09:24:12 +01004329 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004330 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4331 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004332 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004333 NULL/*patch handle*/, address.string());
4334 }
Eric Laurente552edb2014-03-10 17:42:56 -07004335 ALOGV("checkOutputsForDevice(): adding output %d", output);
4336 }
4337 }
4338
4339 if (profiles.isEmpty()) {
4340 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4341 return BAD_VALUE;
4342 }
Eric Laurentd4692962014-05-05 18:13:44 -07004343 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004344 // check if one opened output is not needed any more after disconnecting one device
4345 for (size_t i = 0; i < mOutputs.size(); i++) {
4346 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004347 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004348 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004349 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004350 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004351 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004352 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004353 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4354 mOutputs.keyAt(i));
4355 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004356 }
Eric Laurente552edb2014-03-10 17:42:56 -07004357 }
4358 }
Eric Laurentd4692962014-05-05 18:13:44 -07004359 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004360 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004361 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4362 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004363 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004364 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004365 "clearing direct output profile %zu on module %s",
4366 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004367 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004368 }
4369 }
4370 }
4371 }
4372 return NO_ERROR;
4373}
4374
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004375status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004376 audio_policy_dev_state_t state,
4377 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004378 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004379{
Paul McLean9080a4c2015-06-18 08:24:02 -07004380 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004381 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004382
4383 if (audio_device_is_digital(device)) {
4384 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004385 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004386 }
4387
Eric Laurentd4692962014-05-05 18:13:44 -07004388 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4389 // first list already open inputs that can be routed to this device
4390 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4391 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004392 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004393 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4394 inputs.add(mInputs.keyAt(input_index));
4395 }
4396 }
4397
4398 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004399 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004400 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004401 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004402 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004403 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004404 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004405
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004406 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004407 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004408 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004409 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004410 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4411 profile_index, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004412 }
Eric Laurentd4692962014-05-05 18:13:44 -07004413 }
4414 }
4415 }
4416
4417 if (profiles.isEmpty() && inputs.isEmpty()) {
4418 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4419 return BAD_VALUE;
4420 }
4421
4422 // open inputs for matching profiles if needed. Direct inputs are also opened to
4423 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4424 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4425
Eric Laurent1c333e22014-05-20 10:48:17 -07004426 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004427
Eric Laurentd4692962014-05-05 18:13:44 -07004428 // nothing to do if one input is already opened for this profile
4429 size_t input_index;
4430 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4431 desc = mInputs.valueAt(input_index);
4432 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004433 if (audio_device_is_digital(device)) {
4434 devDesc->importAudioPort(profile);
4435 }
Eric Laurentd4692962014-05-05 18:13:44 -07004436 break;
4437 }
4438 }
4439 if (input_index != mInputs.size()) {
4440 continue;
4441 }
4442
Eric Laurent3974e3b2017-12-07 17:58:43 -08004443 if (!profile->canOpenNewIo()) {
4444 ALOGW("Max Input number %u already opened for this profile %s",
4445 profile->maxOpenCount, profile->getTagName().c_str());
4446 continue;
4447 }
4448
Eric Laurentfe231122017-11-17 17:48:06 -08004449 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004450 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004451 status_t status = desc->open(nullptr,
4452 device,
4453 address,
4454 AUDIO_SOURCE_MIC,
4455 AUDIO_INPUT_FLAG_NONE,
4456 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004457
Eric Laurentcf2c0212014-07-25 16:20:43 -07004458 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004459 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004460 char *param = audio_device_address_to_parameter(device, address);
4461 mpClientInterface->setParameters(input, String8(param));
4462 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004463 }
Phil Burk00eeb322016-03-31 12:41:00 -07004464 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004465 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004466 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004467 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004468 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004469 }
4470
4471 if (input != 0) {
4472 addInput(input, desc);
4473 }
4474 } // endif input != 0
4475
Eric Laurentcf2c0212014-07-25 16:20:43 -07004476 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004477 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004478 profiles.removeAt(profile_index);
4479 profile_index--;
4480 } else {
4481 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004482 if (audio_device_is_digital(device)) {
4483 devDesc->importAudioPort(profile);
4484 }
Eric Laurentd4692962014-05-05 18:13:44 -07004485 ALOGV("checkInputsForDevice(): adding input %d", input);
4486 }
4487 } // end scan profiles
4488
4489 if (profiles.isEmpty()) {
4490 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4491 return BAD_VALUE;
4492 }
4493 } else {
4494 // Disconnect
4495 // check if one opened input is not needed any more after disconnecting one device
4496 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4497 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004498 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004499 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4500 mInputs.keyAt(input_index));
4501 inputs.add(mInputs.keyAt(input_index));
4502 }
4503 }
4504 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004505 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004506 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004507 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004508 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004509 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004510 if (profile->supportDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004511 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4512 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004513 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004514 }
4515 }
4516 }
4517 } // end disconnect
4518
4519 return NO_ERROR;
4520}
4521
4522
Eric Laurente0720872014-03-11 09:30:41 -07004523void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004524{
4525 ALOGV("closeOutput(%d)", output);
4526
Eric Laurentc75307b2015-03-17 15:29:32 -07004527 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004528 if (outputDesc == NULL) {
4529 ALOGW("closeOutput() unknown output %d", output);
4530 return;
4531 }
François Gaffie036e1e92015-03-19 10:16:24 +01004532 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004533
Eric Laurente552edb2014-03-10 17:42:56 -07004534 // look for duplicated outputs connected to the output being removed.
4535 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004536 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004537 if (dupOutputDesc->isDuplicated() &&
4538 (dupOutputDesc->mOutput1 == outputDesc ||
4539 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004540 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004541 if (dupOutputDesc->mOutput1 == outputDesc) {
4542 outputDesc2 = dupOutputDesc->mOutput2;
4543 } else {
4544 outputDesc2 = dupOutputDesc->mOutput1;
4545 }
4546 // As all active tracks on duplicated output will be deleted,
4547 // and as they were also referenced on the other output, the reference
4548 // count for their stream type must be adjusted accordingly on
4549 // the other output.
Andy Hungaf036da2018-09-21 10:46:21 -07004550 const bool wasActive = outputDesc2->isActive();
4551 for (const auto &clientPair : dupOutputDesc->getActiveClients()) {
4552 outputDesc2->changeStreamActiveCount(clientPair.first, -clientPair.second);
Eric Laurente552edb2014-03-10 17:42:56 -07004553 }
Eric Laurent733ce942017-12-07 12:18:25 -08004554 // stop() will be a no op if the output is still active but is needed in case all
4555 // active streams refcounts where cleared above
4556 if (wasActive) {
4557 outputDesc2->stop();
4558 }
Eric Laurente552edb2014-03-10 17:42:56 -07004559 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4560 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4561
4562 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004563 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004564 }
4565 }
4566
Eric Laurent05b90f82014-08-27 15:32:29 -07004567 nextAudioPortGeneration();
4568
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004569 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004570 if (index >= 0) {
4571 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004572 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004573 mAudioPatches.removeItemsAt(index);
4574 mpClientInterface->onAudioPatchListUpdate();
4575 }
4576
Eric Laurentfe231122017-11-17 17:48:06 -08004577 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004578
François Gaffie53615e22015-03-19 09:24:12 +01004579 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004580 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10004581
4582 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
4583 // no direct outputs are open.
4584 if (getMsdAudioOutDeviceTypes() != AUDIO_DEVICE_NONE) {
4585 bool directOutputOpen = false;
4586 for (size_t i = 0; i < mOutputs.size(); i++) {
4587 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
4588 directOutputOpen = true;
4589 break;
4590 }
4591 }
4592 if (!directOutputOpen) {
4593 ALOGV("no direct outputs open, reset MSD patch");
4594 setMsdPatch();
4595 }
4596 }
Eric Laurent05b90f82014-08-27 15:32:29 -07004597}
4598
4599void AudioPolicyManager::closeInput(audio_io_handle_t input)
4600{
4601 ALOGV("closeInput(%d)", input);
4602
4603 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4604 if (inputDesc == NULL) {
4605 ALOGW("closeInput() unknown input %d", input);
4606 return;
4607 }
4608
Eric Laurent6a94d692014-05-20 11:18:06 -07004609 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004610
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004611 audio_devices_t device = inputDesc->mDevice;
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004612 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004613 if (index >= 0) {
4614 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004615 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004616 mAudioPatches.removeItemsAt(index);
4617 mpClientInterface->onAudioPatchListUpdate();
4618 }
4619
Eric Laurentfe231122017-11-17 17:48:06 -08004620 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004621 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004622
4623 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
4624 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
4625 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
4626 SoundTrigger::setCaptureState(false);
4627 }
Eric Laurente552edb2014-03-10 17:42:56 -07004628}
4629
Eric Laurentc75307b2015-03-17 15:29:32 -07004630SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4631 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004632 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004633{
4634 SortedVector<audio_io_handle_t> outputs;
4635
4636 ALOGVV("getOutputsForDevice() device %04x", device);
4637 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004638 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004639 i, openOutputs.valueAt(i)->isDuplicated(),
4640 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004641 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4642 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4643 outputs.add(openOutputs.keyAt(i));
4644 }
4645 }
4646 return outputs;
4647}
4648
Mikhail Naganov37977152018-07-11 15:54:44 -07004649void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
4650{
4651 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
4652 // output is suspended before any tracks are moved to it
4653 checkA2dpSuspend();
4654 checkOutputForAllStrategies();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004655 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07004656 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00004657 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004658 setMsdPatch();
4659 }
Mikhail Naganov37977152018-07-11 15:54:44 -07004660}
4661
Eric Laurente0720872014-03-11 09:30:41 -07004662void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004663{
4664 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4665 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4666 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4667 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4668
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004669 // also take into account external policy-related changes: add all outputs which are
4670 // associated with policies in the "before" and "after" output vectors
4671 ALOGVV("checkOutputForStrategy(): policy related outputs");
4672 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004673 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004674 if (desc != 0 && desc->mPolicyMix != NULL) {
4675 srcOutputs.add(desc->mIoHandle);
4676 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4677 }
4678 }
4679 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004680 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004681 if (desc != 0 && desc->mPolicyMix != NULL) {
4682 dstOutputs.add(desc->mIoHandle);
4683 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4684 }
4685 }
4686
Mikhail Naganov9de8bd12018-07-23 16:41:31 -07004687 if (srcOutputs != dstOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004688 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4689 // audio from invalidated tracks will be rendered when unmuting
4690 uint32_t maxLatency = 0;
4691 for (audio_io_handle_t srcOut : srcOutputs) {
4692 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4693 if (desc != 0 && maxLatency < desc->latency()) {
4694 maxLatency = desc->latency();
4695 }
4696 }
Eric Laurente552edb2014-03-10 17:42:56 -07004697 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4698 strategy, srcOutputs[0], dstOutputs[0]);
4699 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004700 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004701 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4702 if (desc != 0 && isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004703 setStrategyMute(strategy, true, desc);
Eric Laurentac3a6902018-05-11 16:39:10 -07004704 setStrategyMute(strategy, false, desc, maxLatency * LATENCY_MUTE_FACTOR, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004705 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004706 sp<SourceClientDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004707 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004708 if (source != 0){
4709 connectAudioSource(source);
4710 }
Eric Laurente552edb2014-03-10 17:42:56 -07004711 }
4712
4713 // Move effects associated to this strategy from previous output to new output
4714 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004715 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004716 }
4717 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004718 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004719 if (getStrategy((audio_stream_type_t)i) == strategy) {
4720 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004721 }
4722 }
4723 }
4724}
4725
Eric Laurente0720872014-03-11 09:30:41 -07004726void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004727{
François Gaffie2110e042015-03-24 08:41:51 +01004728 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004729 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004730 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004731 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004732 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004733 checkOutputForStrategy(STRATEGY_SONIFICATION);
4734 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004735 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004736 checkOutputForStrategy(STRATEGY_MEDIA);
4737 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004738 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004739}
4740
Eric Laurente0720872014-03-11 09:30:41 -07004741void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004742{
François Gaffie53615e22015-03-19 09:24:12 +01004743 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004744 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004745 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004746 return;
4747 }
4748
Eric Laurent3a4311c2014-03-17 12:00:47 -07004749 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004750 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4751 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4752 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004753
4754 // if suspended, restore A2DP output if:
4755 // ((SCO device is NOT connected) ||
4756 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4757 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004758 //
Eric Laurentf732e072016-08-03 19:30:28 -07004759 // if not suspended, suspend A2DP output if:
4760 // (SCO device is connected) &&
4761 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4762 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004763 //
4764 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004765 if (!isScoConnected ||
4766 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4767 AUDIO_POLICY_FORCE_BT_SCO) &&
4768 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4769 AUDIO_POLICY_FORCE_BT_SCO) &&
4770 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004771 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004772
4773 mpClientInterface->restoreOutput(a2dpOutput);
4774 mA2dpSuspended = false;
4775 }
4776 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004777 if (isScoConnected &&
4778 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4779 AUDIO_POLICY_FORCE_BT_SCO) ||
4780 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4781 AUDIO_POLICY_FORCE_BT_SCO) ||
4782 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004783 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004784
4785 mpClientInterface->suspendOutput(a2dpOutput);
4786 mA2dpSuspended = true;
4787 }
4788 }
4789}
4790
Eric Laurent97ac8712018-07-27 18:59:02 -07004791template <class IoDescriptor, class Filter>
4792sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4793 IoDescriptor& desc, Filter filter, bool& active, const DeviceVector& devices)
4794{
4795 auto activeClients = desc->clientsList(true /*activeOnly*/);
4796 auto activeClientsWithRoute =
4797 desc->clientsList(true /*activeOnly*/, filter, true /*preferredDevice*/);
4798 active = activeClients.size() > 0;
4799 if (active && activeClients.size() == activeClientsWithRoute.size()) {
4800 return devices.getDeviceFromId(activeClientsWithRoute[0]->preferredDeviceId());
4801 }
4802 return nullptr;
4803}
4804
4805template <class IoCollection, class Filter>
4806sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4807 IoCollection& ioCollection, Filter filter, const DeviceVector& devices)
4808{
4809 sp<DeviceDescriptor> device;
4810 for (size_t i = 0; i < ioCollection.size(); i++) {
4811 auto desc = ioCollection.valueAt(i);
4812 bool active;
4813 sp<DeviceDescriptor> curDevice = findPreferredDevice(desc, filter, active, devices);
4814 if (active && curDevice == nullptr) {
4815 return nullptr;
4816 } else if (curDevice != nullptr) {
4817 device = curDevice;
4818 }
4819 }
4820 return device;
4821}
4822
Eric Laurentc75307b2015-03-17 15:29:32 -07004823audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4824 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004825{
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004826 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004827 if (index >= 0) {
4828 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4829 if (patchDesc->mUid != mUidCached) {
4830 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004831 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004832 return outputDesc->device();
4833 }
4834 }
4835
Eric Laurent97ac8712018-07-27 18:59:02 -07004836 // Honor explicit routing requests only if no client using default routing is active on this
4837 // input: a specific app can not force routing for other apps by setting a preferred device.
4838 bool active; // unused
4839 sp<DeviceDescriptor> deviceDesc =
4840 findPreferredDevice(outputDesc, STRATEGY_NONE, active, mAvailableOutputDevices);
4841 if (deviceDesc != nullptr) {
4842 return deviceDesc->type();
Eric Laurentf3a5a602018-05-22 18:42:55 -07004843 }
4844
Eric Laurente552edb2014-03-10 17:42:56 -07004845 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004846 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004847 // use device for strategy enforced audible
4848 // 2: we are in call or the strategy phone is active on the output:
4849 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004850 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004851 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004852 // 4: the strategy for enforced audible is active but not enforced on the output:
4853 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004854 // 5: the strategy accessibility is active on the output:
4855 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004856 // 6: the strategy "respectful" sonification is active on the output:
4857 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004858 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004859 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004860 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004861 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004862 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004863 // use device for strategy t-t-s
Eric Laurent484e9272018-06-07 17:29:23 -07004864
4865 // FIXME: extend use of isStrategyActiveOnSameModule() to all strategies
4866 // with a refined rule considering mutually exclusive devices (using same backend)
4867 // as opposed to all streams on the same audio HAL module.
Eric Laurent97ac8712018-07-27 18:59:02 -07004868 audio_devices_t device = AUDIO_DEVICE_NONE;
François Gaffiead3183e2015-03-18 16:55:35 +01004869 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004870 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004871 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4872 } else if (isInCall() ||
Eric Laurent484e9272018-06-07 17:29:23 -07004873 isStrategyActiveOnSameModule(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004874 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
Yung Ti Su3e7eb5e2018-06-13 11:48:42 +08004875 } else if (isStrategyActiveOnSameModule(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004876 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004877 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
4878 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004879 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4880 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004881 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004882 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004883 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004884 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004885 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004886 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004887 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004888 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004889 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004890 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004891 }
4892
Eric Laurent1c333e22014-05-20 10:48:17 -07004893 ALOGV("getNewOutputDevice() selected device %x", device);
4894 return device;
4895}
4896
Eric Laurentfb66dd92016-01-28 18:32:03 -08004897audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004898{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004899 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004900
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004901 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004902 if (index >= 0) {
4903 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4904 if (patchDesc->mUid != mUidCached) {
4905 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004906 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004907 return inputDesc->mDevice;
4908 }
4909 }
4910
Eric Laurent97ac8712018-07-27 18:59:02 -07004911 // Honor explicit routing requests only if no client using default routing is active on this
4912 // input: a specific app can not force routing for other apps by setting a preferred device.
4913 bool active;
4914 sp<DeviceDescriptor> deviceDesc =
4915 findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
4916 if (deviceDesc != nullptr) {
4917 return deviceDesc->type();
4918 }
4919
Eric Laurentdc95a252018-04-12 12:46:56 -07004920 // If we are not in call and no client is active on this input, this methods returns
4921 // AUDIO_DEVICE_NONE, causing the patch on the input stream to be released.
Eric Laurentfb66dd92016-01-28 18:32:03 -08004922 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
Eric Laurentdc95a252018-04-12 12:46:56 -07004923 if (source == AUDIO_SOURCE_DEFAULT && isInCall()) {
4924 source = AUDIO_SOURCE_VOICE_COMMUNICATION;
4925 }
4926 if (source != AUDIO_SOURCE_DEFAULT) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08004927 device = getDeviceAndMixForInputSource(source);
4928 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004929
Eric Laurente552edb2014-03-10 17:42:56 -07004930 return device;
4931}
4932
Eric Laurent794fde22016-03-11 09:50:45 -08004933bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4934 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004935 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004936}
4937
Eric Laurente0720872014-03-11 09:30:41 -07004938uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004939 return (uint32_t)getStrategy(stream);
4940}
4941
Eric Laurente0720872014-03-11 09:30:41 -07004942audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004943 // By checking the range of stream before calling getStrategy, we avoid
4944 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4945 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004946 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004947 return AUDIO_DEVICE_NONE;
4948 }
Eric Laurentb0688d62018-08-14 15:49:18 -07004949 audio_devices_t activeDevices = AUDIO_DEVICE_NONE;
Eric Laurent28d09f02016-03-08 10:43:05 -08004950 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004951 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4952 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004953 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004954 }
Eric Laurent794fde22016-03-11 09:50:45 -08004955 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004956 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004957 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Eric Laurentb0688d62018-08-14 15:49:18 -07004958 devices |= curDevices;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004959 for (audio_io_handle_t output : getOutputsForDevice(curDevices, mOutputs)) {
4960 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08004961 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurentb0688d62018-08-14 15:49:18 -07004962 activeDevices |= outputDesc->device();
Eric Laurent28d09f02016-03-08 10:43:05 -08004963 }
4964 }
Eric Laurente552edb2014-03-10 17:42:56 -07004965 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004966
Eric Laurentb0688d62018-08-14 15:49:18 -07004967 // Favor devices selected on active streams if any to report correct device in case of
4968 // explicit device selection
4969 if (activeDevices != AUDIO_DEVICE_NONE) {
4970 devices = activeDevices;
4971 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004972 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4973 and doesn't really need to.*/
4974 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4975 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4976 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4977 }
Eric Laurente552edb2014-03-10 17:42:56 -07004978 return devices;
4979}
4980
François Gaffie2110e042015-03-24 08:41:51 +01004981routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4982{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004983 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004984 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004985}
4986
Eric Laurent97ac8712018-07-27 18:59:02 -07004987routing_strategy AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004988 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004989 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004990 return STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004991 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004992 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004993 return STRATEGY_ENFORCED_AUDIBLE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004994 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004995 // usage to strategy mapping
Eric Laurent97ac8712018-07-27 18:59:02 -07004996 return mEngine->getStrategyForUsage(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004997}
4998
Eric Laurente0720872014-03-11 09:30:41 -07004999void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005000 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005001 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07005002 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
5003 updateDevicesAndOutputs();
5004 break;
5005 default:
5006 break;
5007 }
5008}
5009
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005010uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07005011
5012 // skip beacon mute management if a dedicated TTS output is available
5013 if (mTtsOutputAvailable) {
5014 return 0;
5015 }
5016
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005017 switch(event) {
5018 case STARTING_OUTPUT:
5019 mBeaconMuteRefCount++;
5020 break;
5021 case STOPPING_OUTPUT:
5022 if (mBeaconMuteRefCount > 0) {
5023 mBeaconMuteRefCount--;
5024 }
5025 break;
5026 case STARTING_BEACON:
5027 mBeaconPlayingRefCount++;
5028 break;
5029 case STOPPING_BEACON:
5030 if (mBeaconPlayingRefCount > 0) {
5031 mBeaconPlayingRefCount--;
5032 }
5033 break;
5034 }
5035
5036 if (mBeaconMuteRefCount > 0) {
5037 // any playback causes beacon to be muted
5038 return setBeaconMute(true);
5039 } else {
5040 // no other playback: unmute when beacon starts playing, mute when it stops
5041 return setBeaconMute(mBeaconPlayingRefCount == 0);
5042 }
5043}
5044
5045uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5046 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5047 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5048 // keep track of muted state to avoid repeating mute/unmute operations
5049 if (mBeaconMuted != mute) {
5050 // mute/unmute AUDIO_STREAM_TTS on all outputs
5051 ALOGV("\t muting %d", mute);
5052 uint32_t maxLatency = 0;
5053 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005054 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005055 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07005056 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005057 0 /*delay*/, AUDIO_DEVICE_NONE);
5058 const uint32_t latency = desc->latency() * 2;
5059 if (latency > maxLatency) {
5060 maxLatency = latency;
5061 }
5062 }
5063 mBeaconMuted = mute;
5064 return maxLatency;
5065 }
5066 return 0;
5067}
5068
Eric Laurente0720872014-03-11 09:30:41 -07005069audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01005070 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005071{
Eric Laurent97ac8712018-07-27 18:59:02 -07005072 // Honor explicit routing requests only if all active clients have a preferred route in which
5073 // case the last active client route is used
5074 sp<DeviceDescriptor> deviceDesc = findPreferredDevice(mOutputs, strategy, mAvailableOutputDevices);
5075 if (deviceDesc != nullptr) {
5076 return deviceDesc->type();
Paul McLeanaa981192015-03-21 09:55:15 -07005077 }
5078
Eric Laurente552edb2014-03-10 17:42:56 -07005079 if (fromCache) {
5080 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
5081 strategy, mDeviceForStrategy[strategy]);
5082 return mDeviceForStrategy[strategy];
5083 }
François Gaffie2110e042015-03-24 08:41:51 +01005084 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07005085}
5086
Eric Laurente0720872014-03-11 09:30:41 -07005087void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005088{
5089 for (int i = 0; i < NUM_STRATEGIES; i++) {
5090 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
5091 }
5092 mPreviousOutputs = mOutputs;
5093}
5094
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005095uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005096 audio_devices_t prevDevice,
5097 uint32_t delayMs)
5098{
5099 // mute/unmute strategies using an incompatible device combination
5100 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5101 // if unmuting, unmute only after the specified delay
5102 if (outputDesc->isDuplicated()) {
5103 return 0;
5104 }
5105
5106 uint32_t muteWaitMs = 0;
5107 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07005108 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005109
5110 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
5111 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07005112 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07005113 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
5114 bool doMute = false;
5115
5116 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
5117 doMute = true;
5118 outputDesc->mStrategyMutedByDevice[i] = true;
5119 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
5120 doMute = true;
5121 outputDesc->mStrategyMutedByDevice[i] = false;
5122 }
Eric Laurent99401132014-05-07 19:48:15 -07005123 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005124 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005125 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005126 // skip output if it does not share any device with current output
5127 if ((desc->supportedDevices() & outputDesc->supportedDevices())
5128 == AUDIO_DEVICE_NONE) {
5129 continue;
5130 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005131 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07005132 mute ? "muting" : "unmuting", i, curDevice);
5133 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005134 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005135 if (mute) {
5136 // FIXME: should not need to double latency if volume could be applied
5137 // immediately by the audioflinger mixer. We must account for the delay
5138 // between now and the next time the audioflinger thread for this output
5139 // will process a buffer (which corresponds to one buffer size,
5140 // usually 1/2 or 1/4 of the latency).
5141 if (muteWaitMs < desc->latency() * 2) {
5142 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005143 }
5144 }
5145 }
5146 }
5147 }
5148 }
5149
Eric Laurent99401132014-05-07 19:48:15 -07005150 // temporary mute output if device selection changes to avoid volume bursts due to
5151 // different per device volumes
5152 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005153 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5154 // temporary mute duration is conservatively set to 4 times the reported latency
5155 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5156 if (muteWaitMs < tempMuteWaitMs) {
5157 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005158 }
Eric Laurentdc462862016-07-19 12:29:53 -07005159
Eric Laurent99401132014-05-07 19:48:15 -07005160 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005161 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005162 // make sure that we do not start the temporary mute period too early in case of
5163 // delayed device change
5164 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005165 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07005166 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07005167 }
5168 }
5169 }
5170
Eric Laurente552edb2014-03-10 17:42:56 -07005171 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5172 if (muteWaitMs > delayMs) {
5173 muteWaitMs -= delayMs;
5174 usleep(muteWaitMs * 1000);
5175 return muteWaitMs;
5176 }
5177 return 0;
5178}
5179
Eric Laurentc75307b2015-03-17 15:29:32 -07005180uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005181 audio_devices_t device,
5182 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07005183 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005184 audio_patch_handle_t *patchHandle,
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005185 const char *address,
5186 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005187{
Eric Laurentc75307b2015-03-17 15:29:32 -07005188 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005189 AudioParameter param;
5190 uint32_t muteWaitMs;
5191
5192 if (outputDesc->isDuplicated()) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005193 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs,
5194 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
5195 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs,
5196 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005197 return muteWaitMs;
5198 }
5199 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5200 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07005201 if ((device != AUDIO_DEVICE_NONE) &&
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005202 ((device & outputDesc->supportedDevices()) == AUDIO_DEVICE_NONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005203 return 0;
5204 }
5205
5206 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07005207 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07005208
5209 audio_devices_t prevDevice = outputDesc->mDevice;
5210
Paul McLeanaa981192015-03-21 09:55:15 -07005211 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005212
5213 if (device != AUDIO_DEVICE_NONE) {
5214 outputDesc->mDevice = device;
5215 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005216
5217 // if the outputs are not materially active, there is no need to mute.
5218 if (requiresMuteCheck) {
5219 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
5220 } else {
5221 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5222 muteWaitMs = 0;
5223 }
Eric Laurente552edb2014-03-10 17:42:56 -07005224
5225 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005226 // the requested device is AUDIO_DEVICE_NONE
5227 // OR the requested device is the same as current device
5228 // AND force is not specified
5229 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07005230 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07005231 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
5232 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005233 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005234 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005235 return muteWaitMs;
5236 }
5237
5238 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07005239
Eric Laurente552edb2014-03-10 17:42:56 -07005240 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07005241 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005242 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005243 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07005244 DeviceVector deviceList;
5245 if ((address == NULL) || (strlen(address) == 0)) {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005246 deviceList = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurentc40d9692016-04-13 19:14:13 -07005247 } else {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005248 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
5249 device, String8(address));
5250 if (deviceDesc) deviceList.add(deviceDesc);
Eric Laurentc40d9692016-04-13 19:14:13 -07005251 }
5252
Eric Laurent1c333e22014-05-20 10:48:17 -07005253 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005254 PatchBuilder patchBuilder;
5255 patchBuilder.addSource(outputDesc);
Eric Laurent1c333e22014-05-20 10:48:17 -07005256 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005257 patchBuilder.addSink(deviceList.itemAt(i));
Eric Laurent1c333e22014-05-20 10:48:17 -07005258 }
Mikhail Naganovdc769682018-05-04 15:34:08 -07005259 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005260 }
bryant_liuf5e7e792014-08-19 20:07:05 +08005261
5262 // inform all input as well
5263 for (size_t i = 0; i < mInputs.size(); i++) {
5264 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01005265 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08005266 AudioParameter inputCmd = AudioParameter();
5267 ALOGV("%s: inform input %d of device:%d", __func__,
5268 inputDescriptor->mIoHandle, device);
5269 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
5270 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
5271 inputCmd.toString(),
5272 delayMs);
5273 }
5274 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005275 }
Eric Laurente552edb2014-03-10 17:42:56 -07005276
5277 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07005278 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005279
5280 return muteWaitMs;
5281}
5282
Eric Laurentc75307b2015-03-17 15:29:32 -07005283status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005284 int delayMs,
5285 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005286{
Eric Laurent6a94d692014-05-20 11:18:06 -07005287 ssize_t index;
5288 if (patchHandle) {
5289 index = mAudioPatches.indexOfKey(*patchHandle);
5290 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005291 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005292 }
5293 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005294 return INVALID_OPERATION;
5295 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005296 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5297 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005298 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005299 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005300 removeAudioPatch(patchDesc->mHandle);
5301 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005302 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005303 return status;
5304}
5305
5306status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5307 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005308 bool force,
5309 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005310{
5311 status_t status = NO_ERROR;
5312
Eric Laurent1f2f2232014-06-02 12:01:23 -07005313 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005314 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5315 inputDesc->mDevice = device;
5316
Mikhail Naganov708e0382018-05-30 09:53:04 -07005317 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005318 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005319 PatchBuilder patchBuilder;
5320 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005321 // AUDIO_SOURCE_HOTWORD is for internal use only:
5322 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07005323 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5324 auto result = usecase;
5325 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5326 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5327 }
5328 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07005329 //only one input device for now
Mikhail Naganovdc769682018-05-04 15:34:08 -07005330 addSource(deviceList.itemAt(0));
5331 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005332 }
5333 }
5334 return status;
5335}
5336
Eric Laurent6a94d692014-05-20 11:18:06 -07005337status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5338 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005339{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005340 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005341 ssize_t index;
5342 if (patchHandle) {
5343 index = mAudioPatches.indexOfKey(*patchHandle);
5344 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005345 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005346 }
5347 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005348 return INVALID_OPERATION;
5349 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005350 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5351 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005352 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005353 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005354 removeAudioPatch(patchDesc->mHandle);
5355 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005356 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005357 return status;
5358}
5359
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005360sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005361 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005362 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005363 audio_format_t& format,
5364 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005365 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005366{
5367 // Choose an input profile based on the requested capture parameters: select the first available
5368 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005369 //
5370 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5371 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005372
Glenn Kasten730b9262018-03-29 15:01:26 -07005373 sp<IOProfile> firstInexact;
5374 uint32_t updatedSamplingRate = 0;
5375 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5376 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005377 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005378 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005379 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005380 //updatedFormat = format;
Eric Laurent275e8e92014-11-30 15:14:47 -08005381 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005382 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005383 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005384 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005385 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005386 &channelMask /*updatedChannelMask*/,
5387 // FIXME ugly cast
5388 (audio_output_flags_t) flags,
5389 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005390 return profile;
5391 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005392 if (firstInexact == nullptr && profile->isCompatibleProfile(device, address,
5393 samplingRate,
5394 &updatedSamplingRate,
5395 format,
5396 &updatedFormat,
5397 channelMask,
5398 &updatedChannelMask,
5399 // FIXME ugly cast
5400 (audio_output_flags_t) flags,
5401 false /*exactMatchRequiredForInputFlags*/)) {
5402 firstInexact = profile;
5403 }
5404
Eric Laurente552edb2014-03-10 17:42:56 -07005405 }
5406 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005407 if (firstInexact != nullptr) {
5408 samplingRate = updatedSamplingRate;
5409 format = updatedFormat;
5410 channelMask = updatedChannelMask;
5411 return firstInexact;
5412 }
Eric Laurente552edb2014-03-10 17:42:56 -07005413 return NULL;
5414}
5415
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005416
5417audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005418 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005419{
Eric Laurent97ac8712018-07-27 18:59:02 -07005420 // Honor explicit routing requests only if all active clients have a preferred route in which
5421 // case the last active client route is used
5422 sp<DeviceDescriptor> deviceDesc =
5423 findPreferredDevice(mInputs, inputSource, mAvailableInputDevices);
5424 if (deviceDesc != nullptr) {
5425 return deviceDesc->type();
5426 }
5427
5428
François Gaffie036e1e92015-03-19 10:16:24 +01005429 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5430 audio_devices_t selectedDeviceFromMix =
5431 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005432
François Gaffie036e1e92015-03-19 10:16:24 +01005433 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5434 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005435 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005436 return getDeviceForInputSource(inputSource);
5437}
5438
5439audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5440{
Eric Laurent97ac8712018-07-27 18:59:02 -07005441 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005442}
5443
Eric Laurente0720872014-03-11 09:30:41 -07005444float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005445 int index,
5446 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005447{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005448 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005449
5450 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5451 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5452 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5453 // the ringtone volume
5454 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5455 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5456 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5457 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5458 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5459 }
5460
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005461 // in-call: always cap volume by voice volume + some low headroom
5462 if ((stream != AUDIO_STREAM_VOICE_CALL) &&
Eric Laurent7731b5a2018-04-06 15:47:22 -07005463 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005464 switch (stream) {
5465 case AUDIO_STREAM_SYSTEM:
5466 case AUDIO_STREAM_RING:
5467 case AUDIO_STREAM_MUSIC:
5468 case AUDIO_STREAM_ALARM:
5469 case AUDIO_STREAM_NOTIFICATION:
5470 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5471 case AUDIO_STREAM_DTMF:
5472 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005473 int voiceVolumeIndex =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005474 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, device);
Eric Laurent7731b5a2018-04-06 15:47:22 -07005475 const float maxVoiceVolDb =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005476 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, device)
Eric Laurent7731b5a2018-04-06 15:47:22 -07005477 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005478 if (volumeDB > maxVoiceVolDb) {
5479 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5480 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5481 volumeDB = maxVoiceVolDb;
5482 }
5483 } break;
5484 default:
5485 break;
5486 }
5487 }
5488
Eric Laurente552edb2014-03-10 17:42:56 -07005489 // if a headset is connected, apply the following rules to ring tones and notifications
5490 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005491 // - always attenuate notifications volume by 6dB
5492 // - attenuate ring tones volume by 6dB unless music is not playing and
5493 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005494 // - if music is playing, always limit the volume to current music volume,
5495 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005496 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005497 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5498 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5499 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005500 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005501 AUDIO_DEVICE_OUT_USB_HEADSET |
5502 AUDIO_DEVICE_OUT_HEARING_AID)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005503 ((stream_strategy == STRATEGY_SONIFICATION)
5504 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005505 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005506 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005507 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005508 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005509 // when the phone is ringing we must consider that music could have been paused just before
5510 // by the music application and behave as if music was active if the last music track was
5511 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005512 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005513 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005514 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005515 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005516 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005517 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5518 musicDevice),
5519 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005520 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5521 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005522 if (volumeDB > minVolDB) {
5523 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005524 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005525 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005526 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5527 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5528 // on A2DP, also ensure notification volume is not too low compared to media when
5529 // intended to be played
5530 if ((volumeDB > -96.0f) &&
5531 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5532 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5533 stream, device,
5534 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5535 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5536 }
5537 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005538 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5539 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005540 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005541 }
5542 }
5543
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005544 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005545}
5546
Eric Laurent3839bc02018-07-10 18:33:34 -07005547int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
5548 audio_stream_type_t srcStream,
5549 audio_stream_type_t dstStream)
5550{
5551 if (srcStream == dstStream) {
5552 return srcIndex;
5553 }
5554 float minSrc = (float)mVolumeCurves->getVolumeIndexMin(srcStream);
5555 float maxSrc = (float)mVolumeCurves->getVolumeIndexMax(srcStream);
5556 float minDst = (float)mVolumeCurves->getVolumeIndexMin(dstStream);
5557 float maxDst = (float)mVolumeCurves->getVolumeIndexMax(dstStream);
5558
5559 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
5560}
5561
Eric Laurente0720872014-03-11 09:30:41 -07005562status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005563 int index,
5564 const sp<AudioOutputDescriptor>& outputDesc,
5565 audio_devices_t device,
5566 int delayMs,
5567 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005568{
Eric Laurente552edb2014-03-10 17:42:56 -07005569 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005570 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005571 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005572 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005573 return NO_ERROR;
5574 }
François Gaffie2110e042015-03-24 08:41:51 +01005575 audio_policy_forced_cfg_t forceUseForComm =
5576 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005577 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005578 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5579 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005580 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005581 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005582 return INVALID_OPERATION;
5583 }
5584
Eric Laurentc75307b2015-03-17 15:29:32 -07005585 if (device == AUDIO_DEVICE_NONE) {
5586 device = outputDesc->device();
5587 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005588
Eric Laurentffbc80f2015-03-18 18:30:19 -07005589 float volumeDb = computeVolume(stream, index, device);
HW Leeda7581e2018-05-22 18:31:34 +08005590 if (outputDesc->isFixedVolume(device) ||
5591 // Force VoIP volume to max for bluetooth SCO
5592 ((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
5593 (device & AUDIO_DEVICE_OUT_ALL_SCO) != 0)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005594 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005595 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005596
Eric Laurentffbc80f2015-03-18 18:30:19 -07005597 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005598
Eric Laurent3b73df72014-03-11 09:06:29 -07005599 if (stream == AUDIO_STREAM_VOICE_CALL ||
5600 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005601 float voiceVolume;
5602 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005603 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurent3839bc02018-07-10 18:33:34 -07005604 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005605 } else {
5606 voiceVolume = 1.0;
5607 }
5608
Eric Laurent18fba842016-03-31 14:41:26 -07005609 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005610 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5611 mLastVoiceVolume = voiceVolume;
5612 }
5613 }
5614
5615 return NO_ERROR;
5616}
5617
Eric Laurentc75307b2015-03-17 15:29:32 -07005618void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5619 audio_devices_t device,
5620 int delayMs,
5621 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005622{
Eric Laurentc75307b2015-03-17 15:29:32 -07005623 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005624
Eric Laurent794fde22016-03-11 09:50:45 -08005625 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005626 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005627 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005628 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005629 device,
5630 delayMs,
5631 force);
5632 }
5633}
5634
Eric Laurente0720872014-03-11 09:30:41 -07005635void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005636 bool on,
5637 const sp<AudioOutputDescriptor>& outputDesc,
5638 int delayMs,
5639 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005640{
Eric Laurent72249d52015-06-08 11:12:15 -07005641 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5642 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005643 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005644 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005645 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005646 }
5647 }
5648}
5649
Eric Laurente0720872014-03-11 09:30:41 -07005650void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005651 bool on,
5652 const sp<AudioOutputDescriptor>& outputDesc,
5653 int delayMs,
5654 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005655{
Eric Laurente552edb2014-03-10 17:42:56 -07005656 if (device == AUDIO_DEVICE_NONE) {
5657 device = outputDesc->device();
5658 }
5659
Eric Laurentc75307b2015-03-17 15:29:32 -07005660 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5661 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005662
5663 if (on) {
5664 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005665 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005666 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005667 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005668 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005669 }
5670 }
5671 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5672 outputDesc->mMuteCount[stream]++;
5673 } else {
5674 if (outputDesc->mMuteCount[stream] == 0) {
5675 ALOGV("setStreamMute() unmuting non muted stream!");
5676 return;
5677 }
5678 if (--outputDesc->mMuteCount[stream] == 0) {
5679 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005680 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005681 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005682 device,
5683 delayMs);
5684 }
5685 }
5686}
5687
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005688audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5689{
5690 // flags to stream type mapping
5691 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5692 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5693 }
5694 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5695 return AUDIO_STREAM_BLUETOOTH_SCO;
5696 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005697 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5698 return AUDIO_STREAM_TTS;
5699 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005700
Ari Hausman-Cohen5c00d012018-06-26 17:09:11 -07005701 return audio_usage_to_stream_type(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005702}
Eric Laurente83b55d2014-11-14 10:06:21 -08005703
François Gaffie53615e22015-03-19 09:24:12 +01005704bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5705{
Eric Laurente83b55d2014-11-14 10:06:21 -08005706 // has flags that map to a strategy?
5707 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5708 return true;
5709 }
5710
5711 // has known usage?
5712 switch (paa->usage) {
5713 case AUDIO_USAGE_UNKNOWN:
5714 case AUDIO_USAGE_MEDIA:
5715 case AUDIO_USAGE_VOICE_COMMUNICATION:
5716 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5717 case AUDIO_USAGE_ALARM:
5718 case AUDIO_USAGE_NOTIFICATION:
5719 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5720 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5721 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5722 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5723 case AUDIO_USAGE_NOTIFICATION_EVENT:
5724 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5725 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5726 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5727 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005728 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005729 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005730 break;
5731 default:
5732 return false;
5733 }
5734 return true;
5735}
5736
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005737bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005738 routing_strategy strategy, uint32_t inPastMs,
5739 nsecs_t sysTime) const
5740{
5741 if ((sysTime == 0) && (inPastMs != 0)) {
5742 sysTime = systemTime();
5743 }
Eric Laurent794fde22016-03-11 09:50:45 -08005744 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005745 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurent97ac8712018-07-27 18:59:02 -07005746 (STRATEGY_NONE == strategy)) &&
François Gaffiead3183e2015-03-18 16:55:35 +01005747 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5748 return true;
5749 }
5750 }
5751 return false;
5752}
5753
Eric Laurent484e9272018-06-07 17:29:23 -07005754bool AudioPolicyManager::isStrategyActiveOnSameModule(const sp<AudioOutputDescriptor>& outputDesc,
5755 routing_strategy strategy, uint32_t inPastMs,
5756 nsecs_t sysTime) const
5757{
5758 for (size_t i = 0; i < mOutputs.size(); i++) {
5759 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5760 if (outputDesc->sharesHwModuleWith(desc)
5761 && isStrategyActive(desc, strategy, inPastMs, sysTime)) {
5762 return true;
5763 }
5764 }
5765 return false;
5766}
5767
François Gaffie2110e042015-03-24 08:41:51 +01005768audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5769{
5770 return mEngine->getForceUse(usage);
5771}
5772
5773bool AudioPolicyManager::isInCall()
5774{
5775 return isStateInCall(mEngine->getPhoneState());
5776}
5777
5778bool AudioPolicyManager::isStateInCall(int state)
5779{
5780 return is_state_in_call(state);
5781}
5782
Eric Laurentd60560a2015-04-10 11:31:20 -07005783void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5784{
5785 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005786 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5787 if (sourceDesc->srcDevice()->equals(deviceDesc)) {
5788 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->portId());
5789 stopAudioSource(sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005790 }
5791 }
5792
5793 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5794 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5795 bool release = false;
5796 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5797 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5798 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5799 source->ext.device.type == deviceDesc->type()) {
5800 release = true;
5801 }
5802 }
5803 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5804 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5805 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5806 sink->ext.device.type == deviceDesc->type()) {
5807 release = true;
5808 }
5809 }
5810 if (release) {
5811 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5812 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5813 }
5814 }
5815}
5816
Phil Burk09bc4612016-02-24 15:58:15 -08005817// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005818void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5819 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005820 // TODO Set this based on Config properties.
5821 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005822
5823 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5824 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005825 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005826
jiabin81772902018-04-02 17:52:27 -07005827 // If MANUAL, keep the supported surround sound formats as current enabled ones.
5828 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
5829 formats.clear();
5830 for (auto it = mSurroundFormats.begin(); it != mSurroundFormats.end(); it++) {
5831 formats.add(*it);
Phil Burk09bc4612016-02-24 15:58:15 -08005832 }
jiabin81772902018-04-02 17:52:27 -07005833 // Always enable IEC61937 when in MANUAL mode.
5834 formats.add(AUDIO_FORMAT_IEC61937);
5835 } else { // NEVER, AUTO or ALWAYS
5836 // Analyze original support for various formats.
5837 bool supportsAC3 = false;
5838 bool supportsOtherSurround = false;
5839 bool supportsIEC61937 = false;
5840 mSurroundFormats.clear();
5841 for (ssize_t formatIndex = 0; formatIndex < (ssize_t)formats.size(); formatIndex++) {
5842 audio_format_t format = formats[formatIndex];
5843 switch (format) {
5844 case AUDIO_FORMAT_AC3:
5845 supportsAC3 = true;
5846 break;
5847 case AUDIO_FORMAT_E_AC3:
5848 case AUDIO_FORMAT_DTS:
5849 case AUDIO_FORMAT_DTS_HD:
5850 // If ALWAYS, remove all other surround formats here
5851 // since we will add them later.
5852 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5853 formats.removeAt(formatIndex);
5854 formatIndex--;
5855 }
5856 supportsOtherSurround = true;
5857 break;
5858 case AUDIO_FORMAT_IEC61937:
5859 supportsIEC61937 = true;
5860 break;
5861 default:
5862 break;
5863 }
5864 }
Phil Burk09bc4612016-02-24 15:58:15 -08005865
jiabin81772902018-04-02 17:52:27 -07005866 // Modify formats based on surround preferences.
5867 // If NEVER, remove support for surround formats.
5868 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5869 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5870 // Remove surround sound related formats.
5871 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5872 audio_format_t format = formats[formatIndex];
5873 switch(format) {
5874 case AUDIO_FORMAT_AC3:
5875 case AUDIO_FORMAT_E_AC3:
5876 case AUDIO_FORMAT_DTS:
5877 case AUDIO_FORMAT_DTS_HD:
5878 case AUDIO_FORMAT_IEC61937:
5879 formats.removeAt(formatIndex);
5880 break;
5881 default:
5882 formatIndex++; // keep it
5883 break;
5884 }
5885 }
5886 supportsAC3 = false;
5887 supportsOtherSurround = false;
5888 supportsIEC61937 = false;
5889 }
5890 } else { // AUTO or ALWAYS
5891 // Most TVs support AC3 even if they do not report it in the EDID.
5892 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
5893 && !supportsAC3) {
5894 formats.add(AUDIO_FORMAT_AC3);
5895 supportsAC3 = true;
5896 }
5897
5898 // If ALWAYS, add support for raw surround formats if all are missing.
5899 // This assumes that if any of these formats are reported by the HAL
5900 // then the report is valid and should not be modified.
5901 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5902 formats.add(AUDIO_FORMAT_E_AC3);
5903 formats.add(AUDIO_FORMAT_DTS);
5904 formats.add(AUDIO_FORMAT_DTS_HD);
5905 supportsOtherSurround = true;
5906 }
5907
5908 // Add support for IEC61937 if any raw surround supported.
5909 // The HAL could do this but add it here, just in case.
5910 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
5911 formats.add(AUDIO_FORMAT_IEC61937);
5912 supportsIEC61937 = true;
5913 }
5914
5915 // Add reported surround sound formats to enabled surround formats.
5916 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
Phil Burk07ac1142016-03-25 13:39:29 -07005917 audio_format_t format = formats[formatIndex];
Mikhail Naganov02743e22018-11-28 15:56:55 -08005918 if (mConfig.getSurroundFormats().count(format) != 0) {
5919 mSurroundFormats.insert(format);
Phil Burk07ac1142016-03-25 13:39:29 -07005920 }
Phil Burk09bc4612016-02-24 15:58:15 -08005921 }
Phil Burk07ac1142016-03-25 13:39:29 -07005922 }
Phil Burk09bc4612016-02-24 15:58:15 -08005923 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005924}
5925
5926// Modify the list of channel masks supported.
5927void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
5928 ChannelsVector &channelMasks = *channelMasksPtr;
5929 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5930 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5931
5932 // If NEVER, then remove support for channelMasks > stereo.
5933 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5934 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5935 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5936 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5937 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5938 channelMasks.removeAt(maskIndex);
5939 } else {
5940 maskIndex++;
5941 }
5942 }
jiabin81772902018-04-02 17:52:27 -07005943 // If ALWAYS or MANUAL, then make sure we at least support 5.1
5944 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
5945 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005946 bool supports5dot1 = false;
5947 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005948 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005949 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5950 supports5dot1 = true;
5951 break;
5952 }
5953 }
5954 // If not then add 5.1 support.
5955 if (!supports5dot1) {
5956 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
5957 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
5958 }
Phil Burk09bc4612016-02-24 15:58:15 -08005959 }
5960}
5961
Phil Burk00eeb322016-03-31 12:41:00 -07005962void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
5963 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005964 AudioProfileVector &profiles)
5965{
5966 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07005967
François Gaffie112b0af2015-11-19 16:13:25 +01005968 // Format MUST be checked first to update the list of AudioProfile
5969 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005970 reply = mpClientInterface->getParameters(
5971 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07005972 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005973 AudioParameter repliedParameters(reply);
5974 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005975 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005976 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5977 return;
5978 }
Phil Burk09bc4612016-02-24 15:58:15 -08005979 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07005980 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005981 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005982 }
Phil Burk09bc4612016-02-24 15:58:15 -08005983 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005984 }
François Gaffie112b0af2015-11-19 16:13:25 +01005985
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005986 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08005987 ChannelsVector channelMasks;
5988 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005989 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07005990 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01005991
5992 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005993 reply = mpClientInterface->getParameters(
5994 ioHandle,
5995 requestedParameters.toString() + ";" +
5996 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01005997 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005998 AudioParameter repliedParameters(reply);
5999 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006000 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006001 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01006002 }
6003 }
6004 if (profiles.hasDynamicChannelsFor(format)) {
6005 reply = mpClientInterface->getParameters(ioHandle,
6006 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07006007 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01006008 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006009 AudioParameter repliedParameters(reply);
6010 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006011 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006012 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07006013 if (device == AUDIO_DEVICE_OUT_HDMI) {
6014 filterSurroundChannelMasks(&channelMasks);
6015 }
François Gaffie112b0af2015-11-19 16:13:25 +01006016 }
6017 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08006018 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006019 }
6020}
Eric Laurentd60560a2015-04-10 11:31:20 -07006021
Mikhail Naganovdc769682018-05-04 15:34:08 -07006022status_t AudioPolicyManager::installPatch(const char *caller,
6023 audio_patch_handle_t *patchHandle,
6024 AudioIODescriptorInterface *ioDescriptor,
6025 const struct audio_patch *patch,
6026 int delayMs)
6027{
6028 ssize_t index = mAudioPatches.indexOfKey(
6029 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6030 *patchHandle : ioDescriptor->getPatchHandle());
6031 sp<AudioPatch> patchDesc;
6032 status_t status = installPatch(
6033 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6034 if (status == NO_ERROR) {
6035 ioDescriptor->setPatchHandle(patchDesc->mHandle);
6036 }
6037 return status;
6038}
6039
6040status_t AudioPolicyManager::installPatch(const char *caller,
6041 ssize_t index,
6042 audio_patch_handle_t *patchHandle,
6043 const struct audio_patch *patch,
6044 int delayMs,
6045 uid_t uid,
6046 sp<AudioPatch> *patchDescPtr)
6047{
6048 sp<AudioPatch> patchDesc;
6049 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6050 if (index >= 0) {
6051 patchDesc = mAudioPatches.valueAt(index);
6052 afPatchHandle = patchDesc->mAfPatchHandle;
6053 }
6054
6055 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6056 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6057 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6058 if (status == NO_ERROR) {
6059 if (index < 0) {
6060 patchDesc = new AudioPatch(patch, uid);
6061 addAudioPatch(patchDesc->mHandle, patchDesc);
6062 } else {
6063 patchDesc->mPatch = *patch;
6064 }
6065 patchDesc->mAfPatchHandle = afPatchHandle;
6066 if (patchHandle) {
6067 *patchHandle = patchDesc->mHandle;
6068 }
6069 nextAudioPortGeneration();
6070 mpClientInterface->onAudioPatchListUpdate();
6071 }
6072 if (patchDescPtr) *patchDescPtr = patchDesc;
6073 return status;
6074}
6075
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006076} // namespace android