blob: 4c339bcb926ae05573d13c4d62b17a630b2982ad [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);
jiabin40573322018-11-08 12:08:02 -0800485 audio_io_handle_t output = selectOutput(outputs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800486 // 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
695// Find a direct output profile compatible with the parameters passed, even if the input flags do
696// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800697sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700698 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{
Eric Laurent861a6282015-05-18 15:40:16 -0700704 // only retain flags that will drive the direct output profile selection
705 // if explicitly requested
706 static const uint32_t kRelevantFlags =
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700707 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
708 AUDIO_OUTPUT_FLAG_VOIP_RX);
Eric Laurent861a6282015-05-18 15:40:16 -0700709 flags =
710 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
711
712 sp<IOProfile> profile;
713
Mikhail Naganovd4120142017-12-06 15:49:22 -0800714 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800715 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent861a6282015-05-18 15:40:16 -0700716 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700717 samplingRate, NULL /*updatedSamplingRate*/,
718 format, NULL /*updatedFormat*/,
719 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700720 flags)) {
721 continue;
722 }
723 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100724 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700725 continue;
726 }
727 // if several profiles are compatible, give priority to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100728 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700729 continue;
730 }
731 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100732 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700733 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700734 }
Eric Laurente552edb2014-03-10 17:42:56 -0700735 }
736 }
Eric Laurent861a6282015-05-18 15:40:16 -0700737 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700738}
739
Eric Laurentf4e63452017-11-06 19:31:46 +0000740audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700741{
Eric Laurent3b73df72014-03-11 09:06:29 -0700742 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700743 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800744
745 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
746 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
747 // format, flags, etc. This may result in some discrepancy for functions that utilize
748 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
749 // and AudioSystem::getOutputSamplingRate().
750
Eric Laurentf4e63452017-11-06 19:31:46 +0000751 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
jiabin40573322018-11-08 12:08:02 -0800752 audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -0700753
Eric Laurentf4e63452017-11-06 19:31:46 +0000754 ALOGV("getOutput() stream %d selected device %08x, output %d", stream, device, output);
755 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700756}
757
Eric Laurente83b55d2014-11-14 10:06:21 -0800758status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
759 audio_io_handle_t *output,
760 audio_session_t session,
761 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700762 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800763 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200764 audio_output_flags_t *flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700765 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800766 audio_port_handle_t *portId)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700767{
Eric Laurente83b55d2014-11-14 10:06:21 -0800768 audio_attributes_t attributes;
Eric Laurent8fc147b2018-07-22 19:13:55 -0700769 DeviceVector outputDevices;
770 routing_strategy strategy;
771 audio_devices_t device;
Eric Laurent97ac8712018-07-27 18:59:02 -0700772 const audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100773 audio_devices_t msdDevice = getMsdAudioOutDeviceTypes();
Eric Laurent8fc147b2018-07-22 19:13:55 -0700774
Eric Laurent8f42ea12018-08-08 09:08:25 -0700775 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
776 if (*portId != AUDIO_PORT_HANDLE_NONE) {
777 return INVALID_OPERATION;
778 }
779
Eric Laurente83b55d2014-11-14 10:06:21 -0800780 if (attr != NULL) {
781 if (!isValidAttributes(attr)) {
782 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
783 attr->usage, attr->content_type, attr->flags,
784 attr->tags);
785 return BAD_VALUE;
786 }
787 attributes = *attr;
788 } else {
789 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
790 ALOGE("getOutputForAttr(): invalid stream type");
791 return BAD_VALUE;
792 }
793 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700794 }
Eric Laurent20b9ef02016-12-05 11:03:16 -0800795
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700796 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
Eric Laurent97ac8712018-07-27 18:59:02 -0700797 " session %d selectedDeviceId %d",
798 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
799 session, requestedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700800
Eric Laurent97ac8712018-07-27 18:59:02 -0700801 *stream = streamTypefromAttributesInt(&attributes);
802
803 strategy = getStrategyForAttr(&attributes);
804
Scott Randolph7b1fd232018-06-18 15:33:03 -0700805 // First check for explicit routing (eg. setPreferredDevice)
Eric Laurent97ac8712018-07-27 18:59:02 -0700806 if (requestedDeviceId != AUDIO_PORT_HANDLE_NONE) {
807 sp<DeviceDescriptor> deviceDesc =
808 mAvailableOutputDevices.getDeviceFromId(requestedDeviceId);
809 device = deviceDesc->type();
Scott Randolph7b1fd232018-06-18 15:33:03 -0700810 } else {
811 // If no explict route, is there a matching dynamic policy that applies?
812 sp<SwAudioOutputDescriptor> desc;
813 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
814 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
815 if (!audio_has_proportional_frames(config->format)) {
816 return BAD_VALUE;
817 }
818 *stream = streamTypefromAttributesInt(&attributes);
819 *output = desc->mIoHandle;
Eric Laurent97ac8712018-07-27 18:59:02 -0700820 AudioMix *mix = desc->mPolicyMix;
821 sp<DeviceDescriptor> deviceDesc =
822 mAvailableOutputDevices.getDevice(mix->mDeviceType, mix->mDeviceAddress);
823 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Scott Randolph7b1fd232018-06-18 15:33:03 -0700824 ALOGV("getOutputForAttr() returns output %d", *output);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700825 goto exit;
Scott Randolph7b1fd232018-06-18 15:33:03 -0700826 }
827
828 // Virtual sources must always be dynamicaly or explicitly routed
829 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
830 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
831 return BAD_VALUE;
832 }
Eric Laurent97ac8712018-07-27 18:59:02 -0700833 device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700834 }
Scott Randolph7b1fd232018-06-18 15:33:03 -0700835
Eric Laurente83b55d2014-11-14 10:06:21 -0800836 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200837 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -0700838 }
839
Nadav Barb2f18162018-07-18 13:01:53 +0300840 // Set incall music only if device was explicitly set, and fallback to the device which is
841 // chosen by the engine if not.
842 // FIXME: provide a more generic approach which is not device specific and move this back
843 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +0200844 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
Nadav Barb2f18162018-07-18 13:01:53 +0300845 if (device == AUDIO_DEVICE_OUT_TELEPHONY_TX &&
Nadav Bar20919492018-11-20 10:20:51 +0200846 (*stream == AUDIO_STREAM_MUSIC || attributes.usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +0300847 audio_is_linear_pcm(config->format) &&
848 isInCall()) {
Eric Laurent97ac8712018-07-27 18:59:02 -0700849 if (requestedDeviceId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +0300850 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
851 } else {
Eric Laurent97ac8712018-07-27 18:59:02 -0700852 // Get the devce type directly from the engine to bypass preferred route logic
Nadav Barb2f18162018-07-18 13:01:53 +0300853 device = mEngine->getDeviceForStrategy(strategy);
854 }
855 }
856
Glenn Kasten49f36ba2017-12-06 13:02:02 -0800857 ALOGV("getOutputForAttr() device 0x%x, sampling rate %d, format %#x, channel mask %#x, "
858 "flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +0200859 device, config->sample_rate, config->format, config->channel_mask, *flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700860
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100861 *output = AUDIO_IO_HANDLE_NONE;
862 if (msdDevice != AUDIO_DEVICE_NONE) {
863 *output = getOutputForDevice(msdDevice, session, *stream, config, flags);
864 if (*output != AUDIO_IO_HANDLE_NONE && setMsdPatch(device) == NO_ERROR) {
865 ALOGV("%s() Using MSD device 0x%x instead of device 0x%x",
866 __func__, msdDevice, device);
867 device = msdDevice;
868 } else {
869 *output = AUDIO_IO_HANDLE_NONE;
870 }
871 }
872 if (*output == AUDIO_IO_HANDLE_NONE) {
873 *output = getOutputForDevice(device, session, *stream, config, flags);
874 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800875 if (*output == AUDIO_IO_HANDLE_NONE) {
876 return INVALID_OPERATION;
877 }
Paul McLeanaa981192015-03-21 09:55:15 -0700878
Eric Laurent8fc147b2018-07-22 19:13:55 -0700879 outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -0700880 *selectedDeviceId = outputDevices.size() > 0 ? outputDevices.itemAt(0)->getId()
881 : AUDIO_PORT_HANDLE_NONE;
882
Eric Laurent8fc147b2018-07-22 19:13:55 -0700883exit:
884 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
885 .format = config->format,
886 .channel_mask = config->channel_mask };
Eric Laurent8f42ea12018-08-08 09:08:25 -0700887 *portId = AudioPort::getNextUniqueId();
888
Eric Laurent8fc147b2018-07-22 19:13:55 -0700889 sp<TrackClientDescriptor> clientDesc =
Eric Laurent97ac8712018-07-27 18:59:02 -0700890 new TrackClientDescriptor(*portId, uid, session, attributes, clientConfig,
891 requestedDeviceId, *stream,
892 getStrategyForAttr(&attributes),
893 *flags);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700894 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Andy Hung39efb7a2018-09-26 15:39:28 -0700895 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700896
897 ALOGV(" getOutputForAttr() returns output %d selectedDeviceId %d for port ID %d",
898 *output, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -0700899
Eric Laurente83b55d2014-11-14 10:06:21 -0800900 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700901}
902
903audio_io_handle_t AudioPolicyManager::getOutputForDevice(
904 audio_devices_t device,
Kevin Rocard169753c2017-03-06 14:18:23 -0800905 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700906 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -0800907 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200908 audio_output_flags_t *flags)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700909{
Andy Hungc88b0642018-04-27 15:42:35 -0700910 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700911 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700912
Eric Laurente552edb2014-03-10 17:42:56 -0700913 // open a direct output if required by specified parameters
914 //force direct flag if offload flag is set: offloading implies a direct output stream
915 // and all common behaviors are driven by checking only the direct flag
916 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +0200917 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
918 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700919 }
Nadav Bar766fb022018-01-07 12:18:03 +0200920 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
921 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -0700922 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800923 // only allow deep buffering for music stream type
924 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +0200925 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700926 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +0200927 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700928 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
929 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +0200930 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800931 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700932 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +0200933 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700934 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +0200935 audio_is_linear_pcm(config->format) &&
936 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200937 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700938 AUDIO_OUTPUT_FLAG_DIRECT);
939 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700940 }
Eric Laurente552edb2014-03-10 17:42:56 -0700941
Nadav Bar766fb022018-01-07 12:18:03 +0200942
Eric Laurentb732cf52014-09-24 19:08:21 -0700943 sp<IOProfile> profile;
944
945 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700946 // and not explicitly requested
Nadav Bar766fb022018-01-07 12:18:03 +0200947 if (((*flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Eric Laurentfe231122017-11-17 17:48:06 -0800948 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
949 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
Eric Laurentb732cf52014-09-24 19:08:21 -0700950 goto non_direct_output;
951 }
952
Andy Hung2ddee192015-12-18 17:34:44 -0800953 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
954 // This prevents creating an offloaded track and tearing it down immediately after start
955 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700956 // FIXME: We should check the audio session here but we do not have it in this context.
957 // This may prevent offloading in rare situations where effects are left active by apps
958 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700959
Nadav Bar766fb022018-01-07 12:18:03 +0200960 if (((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800961 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700962 profile = getProfileForDirectOutput(device,
Eric Laurentfe231122017-11-17 17:48:06 -0800963 config->sample_rate,
964 config->format,
965 config->channel_mask,
Nadav Bar766fb022018-01-07 12:18:03 +0200966 (audio_output_flags_t)*flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700967 }
968
Eric Laurent1c333e22014-05-20 10:48:17 -0700969 if (profile != 0) {
Andy Hungc88b0642018-04-27 15:42:35 -0700970 // exclusive outputs for MMAP and Offload are enforced by different session ids.
971 for (size_t i = 0; i < mOutputs.size(); i++) {
972 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
973 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
974 // reuse direct output if currently open by the same client
975 // and configured with same parameters
976 if ((config->sample_rate == desc->mSamplingRate) &&
Andy Hung5659ed52018-04-30 10:31:26 -0700977 (config->format == desc->mFormat) &&
Andy Hungc88b0642018-04-27 15:42:35 -0700978 (config->channel_mask == desc->mChannelMask) &&
979 (session == desc->mDirectClientSession)) {
980 desc->mDirectOpenCount++;
981 ALOGI("getOutputForDevice() reusing direct output %d for session %d",
982 mOutputs.keyAt(i), session);
983 return mOutputs.keyAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700984 }
985 }
986 }
Eric Laurent3974e3b2017-12-07 17:58:43 -0800987
988 if (!profile->canOpenNewIo()) {
989 goto non_direct_output;
Eric Laurente552edb2014-03-10 17:42:56 -0700990 }
Eric Laurent861a6282015-05-18 15:40:16 -0700991
Eric Laurent3974e3b2017-12-07 17:58:43 -0800992 sp<SwAudioOutputDescriptor> outputDesc =
993 new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurent53b810e2017-12-10 17:25:10 -0800994
Mikhail Naganov708e0382018-05-30 09:53:04 -0700995 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -0800996 String8 address = outputDevices.size() > 0 ? outputDevices.itemAt(0)->mAddress
997 : String8("");
998
Dean Wheatley3023b382018-08-09 07:42:40 +1000999 // MSD patch may be using the only output stream that can service this request. Release
1000 // MSD patch to prioritize this request over any active output on MSD.
1001 AudioPatchCollection msdPatches = getMsdPatches();
1002 for (size_t i = 0; i < msdPatches.size(); i++) {
1003 const auto& patch = msdPatches[i];
1004 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1005 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1006 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
1007 (sink->ext.device.type & device) != AUDIO_DEVICE_NONE &&
1008 (address.isEmpty() || strncmp(sink->ext.device.address, address.string(),
1009 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
1010 releaseAudioPatch(patch->mHandle, mUidCached);
1011 break;
1012 }
1013 }
1014 }
1015
Nadav Bar766fb022018-01-07 12:18:03 +02001016 status = outputDesc->open(config, device, address, stream, *flags, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07001017
1018 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001019 if (status != NO_ERROR ||
Eric Laurentfe231122017-11-17 17:48:06 -08001020 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
Andy Hung5659ed52018-04-30 10:31:26 -07001021 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->mFormat) ||
Eric Laurentfe231122017-11-17 17:48:06 -08001022 (config->channel_mask != 0 && config->channel_mask != outputDesc->mChannelMask)) {
1023 ALOGV("getOutputForDevice() failed opening direct output: output %d sample rate %d %d,"
1024 "format %d %d, channel mask %04x %04x", output, config->sample_rate,
1025 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
1026 config->channel_mask, outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001027 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001028 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07001029 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001030 // fall back to mixer output if possible when the direct output could not be open
Eric Laurentfe231122017-11-17 17:48:06 -08001031 if (audio_is_linear_pcm(config->format) &&
1032 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -08001033 goto non_direct_output;
1034 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001035 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001036 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001037 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -08001038 outputDesc->mDirectClientSession = session;
1039
Eric Laurente552edb2014-03-10 17:42:56 -07001040 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001041 mPreviousOutputs = mOutputs;
Eric Laurentf4e63452017-11-06 19:31:46 +00001042 ALOGV("getOutputForDevice() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001043 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001044 return output;
1045 }
1046
Eric Laurentb732cf52014-09-24 19:08:21 -07001047non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001048
1049 // A request for HW A/V sync cannot fallback to a mixed output because time
1050 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001051 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001052 return AUDIO_IO_HANDLE_NONE;
1053 }
1054
Eric Laurente552edb2014-03-10 17:42:56 -07001055 // ignoring channel mask due to downmix capability in mixer
1056
1057 // open a non direct output
1058
1059 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001060 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001061 // get which output is suitable for the specified stream. The actual
1062 // routing change will happen when startOutput() will be called
1063 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1064
Eric Laurent8838a382014-09-08 16:44:28 -07001065 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001066 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabin40573322018-11-08 12:08:02 -08001067 output = selectOutput(outputs, *flags, config->format,
1068 config->channel_mask, config->sample_rate);
Eric Laurente552edb2014-03-10 17:42:56 -07001069 }
Eric Laurentf4e63452017-11-06 19:31:46 +00001070 ALOGW_IF((output == 0), "getOutputForDevice() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001071 "sampling rate %d, format %#x, channels %#x, flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +02001072 stream, config->sample_rate, config->format, config->channel_mask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001073
Eric Laurente552edb2014-03-10 17:42:56 -07001074 return output;
1075}
1076
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001077sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001078 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001079 if (msdModule != 0) {
1080 DeviceVector msdInputDevices = mAvailableInputDevices.getDevicesFromHwModule(
1081 msdModule->getHandle());
1082 if (!msdInputDevices.isEmpty()) return msdInputDevices.itemAt(0);
1083 }
1084 return 0;
1085}
1086
1087audio_devices_t AudioPolicyManager::getMsdAudioOutDeviceTypes() const {
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001088 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001089 if (msdModule != 0) {
1090 return mAvailableOutputDevices.getDeviceTypesFromHwModule(msdModule->getHandle());
1091 }
1092 return AUDIO_DEVICE_NONE;
1093}
1094
1095const AudioPatchCollection AudioPolicyManager::getMsdPatches() const {
1096 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001097 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1098 if (msdModule != 0) {
1099 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1100 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1101 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1102 const struct audio_port_config *source = &patch->mPatch.sources[j];
1103 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1104 source->ext.device.hw_module == msdModule->getHandle()) {
1105 msdPatches.addAudioPatch(patch->mHandle, patch);
1106 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001107 }
1108 }
1109 }
1110 return msdPatches;
1111}
1112
1113status_t AudioPolicyManager::getBestMsdAudioProfileFor(audio_devices_t outputDevice,
1114 bool hwAvSync, audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1115{
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001116 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001117 if (msdModule == nullptr) {
1118 ALOGE("%s() unable to get MSD module", __func__);
1119 return NO_INIT;
1120 }
1121 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(outputDevice);
1122 if (deviceModule == nullptr) {
1123 ALOGE("%s() unable to get module for %#x", __func__, outputDevice);
1124 return NO_INIT;
1125 }
1126 const InputProfileCollection &inputProfiles = msdModule->getInputProfiles();
1127 if (inputProfiles.isEmpty()) {
1128 ALOGE("%s() no input profiles for MSD module", __func__);
1129 return NO_INIT;
1130 }
1131 const OutputProfileCollection &outputProfiles = deviceModule->getOutputProfiles();
1132 if (outputProfiles.isEmpty()) {
1133 ALOGE("%s() no output profiles for device %#x", __func__, outputDevice);
1134 return NO_INIT;
1135 }
1136 AudioProfileVector msdProfiles;
1137 // Each IOProfile represents a MixPort from audio_policy_configuration.xml
1138 for (const auto &inProfile : inputProfiles) {
1139 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0)) {
1140 msdProfiles.appendVector(inProfile->getAudioProfiles());
1141 }
1142 }
1143 AudioProfileVector deviceProfiles;
1144 for (const auto &outProfile : outputProfiles) {
1145 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0)) {
1146 deviceProfiles.appendVector(outProfile->getAudioProfiles());
1147 }
1148 }
1149 struct audio_config_base bestSinkConfig;
1150 status_t result = msdProfiles.findBestMatchingOutputConfig(deviceProfiles,
1151 compressedFormatsOrder, surroundChannelMasksOrder, true /*preferHigherSamplingRates*/,
1152 &bestSinkConfig);
1153 if (result != NO_ERROR) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001154 ALOGD("%s() no matching profiles found for device: %#x, hwAvSync: %d",
1155 __func__, outputDevice, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001156 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001157 }
1158 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1159 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1160 sinkConfig->format = bestSinkConfig.format;
1161 // For encoded streams force direct flag to prevent downstream mixing.
1162 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1163 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
1164 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1165 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1166 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1167 sourceConfig->format = bestSinkConfig.format;
1168 // Copy input stream directly without any processing (e.g. resampling).
1169 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1170 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1171 if (hwAvSync) {
1172 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1173 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1174 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1175 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1176 }
1177 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1178 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1179 sinkConfig->config_mask |= config_mask;
1180 sourceConfig->config_mask |= config_mask;
1181 return NO_ERROR;
1182}
1183
1184PatchBuilder AudioPolicyManager::buildMsdPatch(audio_devices_t outputDevice) const
1185{
1186 PatchBuilder patchBuilder;
1187 patchBuilder.addSource(getMsdAudioInDevice()).
1188 addSink(findDevice(mAvailableOutputDevices, outputDevice));
1189 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1190 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
1191 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1192 // For now, we just forcefully try with HwAvSync first.
1193 status_t res = getBestMsdAudioProfileFor(outputDevice, true /*hwAvSync*/,
1194 &sourceConfig, &sinkConfig) == NO_ERROR ? NO_ERROR :
1195 getBestMsdAudioProfileFor(
1196 outputDevice, false /*hwAvSync*/, &sourceConfig, &sinkConfig);
1197 if (res == NO_ERROR) {
1198 // Found a matching profile for encoded audio. Re-create PatchBuilder with this config.
1199 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1200 }
1201 ALOGV("%s() no matching profile found. Fall through to default PCM patch"
1202 " supporting PCM format conversion.", __func__);
1203 return patchBuilder;
1204}
1205
1206status_t AudioPolicyManager::setMsdPatch(audio_devices_t outputDevice) {
1207 ALOGV("%s() for outputDevice %#x", __func__, outputDevice);
1208 if (outputDevice == AUDIO_DEVICE_NONE) {
1209 // Use media strategy for unspecified output device. This should only
1210 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1211 // therefore invalidate explicit routing requests.
1212 outputDevice = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
1213 }
1214 PatchBuilder patchBuilder = buildMsdPatch(outputDevice);
1215 const struct audio_patch* patch = patchBuilder.patch();
1216 const AudioPatchCollection msdPatches = getMsdPatches();
1217 if (!msdPatches.isEmpty()) {
1218 LOG_ALWAYS_FATAL_IF(msdPatches.size() > 1,
1219 "The current MSD prototype only supports one output patch");
1220 sp<AudioPatch> currentPatch = msdPatches.valueAt(0);
1221 if (audio_patches_are_equal(&currentPatch->mPatch, patch)) {
1222 return NO_ERROR;
1223 }
1224 releaseAudioPatch(currentPatch->mHandle, mUidCached);
1225 }
1226 status_t status = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1227 patch, 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1228 ALOGE_IF(status != NO_ERROR, "%s() error %d creating MSD audio patch", __func__, status);
1229 ALOGI_IF(status == NO_ERROR, "%s() Patch created from MSD_IN to "
1230 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__, outputDevice,
1231 patch->sources[0].format, patch->sources[0].channel_mask, patch->sources[0].sample_rate);
1232 return status;
1233}
1234
Eric Laurente0720872014-03-11 09:30:41 -07001235audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001236 audio_output_flags_t flags,
jiabin40573322018-11-08 12:08:02 -08001237 audio_format_t format,
1238 audio_channel_mask_t channelMask,
1239 uint32_t samplingRate)
Eric Laurente552edb2014-03-10 17:42:56 -07001240{
1241 // select one output among several that provide a path to a particular device or set of
1242 // devices (the list was previously build by getOutputsForDevice()).
1243 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001244 // 1: the output supporting haptic playback when requesting haptic playback
1245 // 2: the output with the highest number of requested policy flags
1246 // 3: the output with the bit depth the closest to the requested one
1247 // 4: the primary output
1248 // 5: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001249
1250 if (outputs.size() == 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001251 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001252 }
1253 if (outputs.size() == 1) {
1254 return outputs[0];
1255 }
1256
1257 int maxCommonFlags = 0;
jiabin40573322018-11-08 12:08:02 -08001258 const size_t hapticChannelCount = audio_channel_count_from_out_mask(
1259 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
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 }
jiabin40573322018-11-08 12:08:02 -08001272 // If haptic channel is specified, use the haptic output if present.
1273 // When using haptic output, same audio format and sample rate are required.
1274 if (hapticChannelCount > 0) {
1275 // If haptic channel is specified, use the first output that
1276 // support haptic playback.
1277 if (audio_channel_count_from_out_mask(
1278 outputDesc->mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL) >= hapticChannelCount
1279 && format == outputDesc->mFormat
1280 && samplingRate == outputDesc->mSamplingRate) {
1281 return output;
1282 }
1283 } else {
1284 // When haptic channel is not specified, skip haptic output.
1285 if (outputDesc->mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL) {
1286 continue;
1287 }
1288 }
1289
Eric Laurent8838a382014-09-08 16:44:28 -07001290 // if a valid format is specified, skip output if not compatible
1291 if (format != AUDIO_FORMAT_INVALID) {
chenhg1794d712018-10-09 15:20:37 -07001292 if (!audio_is_linear_pcm(format)) {
Eric Laurent8838a382014-09-08 16:44:28 -07001293 continue;
1294 }
Eric Laurente6930022016-02-11 10:20:40 -08001295 if (AudioPort::isBetterFormatMatch(
1296 outputDesc->mFormat, bestFormat, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001297 outputForFormat = output;
Eric Laurente6930022016-02-11 10:20:40 -08001298 bestFormat = outputDesc->mFormat;
1299 }
Eric Laurent8838a382014-09-08 16:44:28 -07001300 }
1301
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001302 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001303 if (commonFlags >= maxCommonFlags) {
1304 if (commonFlags == maxCommonFlags) {
Andy Hungc9901522017-11-10 20:07:54 -08001305 if (format != AUDIO_FORMAT_INVALID
1306 && AudioPort::isBetterFormatMatch(
1307 outputDesc->mFormat, bestFormatForFlags, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001308 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001309 bestFormatForFlags = outputDesc->mFormat;
1310 }
1311 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001312 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001313 maxCommonFlags = commonFlags;
1314 bestFormatForFlags = outputDesc->mFormat;
1315 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001316 ALOGV("selectOutput() commonFlags for output %d, %04x", output, commonFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001317 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001318 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001319 outputForPrimary = output;
Eric Laurente552edb2014-03-10 17:42:56 -07001320 }
1321 }
1322 }
1323
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001324 if (outputForFlags != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001325 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001326 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001327 if (outputForFormat != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001328 return outputForFormat;
1329 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001330 if (outputForPrimary != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001331 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001332 }
1333
1334 return outputs[0];
1335}
1336
Eric Laurent8fc147b2018-07-22 19:13:55 -07001337status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001338{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001339 ALOGV("%s portId %d", __FUNCTION__, portId);
1340
1341 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1342 if (outputDesc == 0) {
1343 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001344 return BAD_VALUE;
1345 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001346 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001347
Eric Laurent8fc147b2018-07-22 19:13:55 -07001348 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001349 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001350
Eric Laurent733ce942017-12-07 12:18:25 -08001351 status_t status = outputDesc->start();
1352 if (status != NO_ERROR) {
1353 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001354 }
1355
Eric Laurent97ac8712018-07-27 18:59:02 -07001356 uint32_t delayMs;
1357 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001358
1359 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001360 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001361 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001362 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001363 if (delayMs != 0) {
1364 usleep(delayMs * 1000);
1365 }
1366
1367 return status;
1368}
1369
Eric Laurent97ac8712018-07-27 18:59:02 -07001370status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1371 const sp<TrackClientDescriptor>& client,
1372 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001373{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001374 // cannot start playback of STREAM_TTS if any other output is being used
1375 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001376
1377 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001378 audio_stream_type_t stream = client->stream();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001379 if (stream == AUDIO_STREAM_TTS) {
1380 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001381 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001382 return INVALID_OPERATION;
1383 } else {
1384 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1385 }
1386 } else {
1387 // some playback other than beacon starts
1388 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1389 }
1390
Eric Laurent77305a62016-07-25 16:39:22 -07001391 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001392 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001393 bool force = !outputDesc->isActive() &&
1394 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001395
Eric Laurent97ac8712018-07-27 18:59:02 -07001396 audio_devices_t device = AUDIO_DEVICE_NONE;
1397 AudioMix *policyMix = NULL;
1398 const char *address = NULL;
1399 if (outputDesc->mPolicyMix != NULL) {
1400 policyMix = outputDesc->mPolicyMix;
1401 address = policyMix->mDeviceAddress.string();
1402 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1403 device = policyMix->mDeviceType;
1404 } else {
1405 device = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1406 }
1407 }
1408
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001409 // requiresMuteCheck is false when we can bypass mute strategy.
1410 // It covers a common case when there is no materially active audio
1411 // and muting would result in unnecessary delay and dropped audio.
1412 const uint32_t outputLatencyMs = outputDesc->latency();
1413 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1414
Eric Laurente552edb2014-03-10 17:42:56 -07001415 // increment usage count for this stream on the requested output:
1416 // NOTE that the usage count is the same for duplicated output and hardware output which is
1417 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001418 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001419
1420 if (client->hasPreferredDevice(true)) {
1421 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
1422 if (device != outputDesc->device()) {
1423 checkStrategyRoute(getStrategy(stream), outputDesc->mIoHandle);
1424 }
1425 }
Eric Laurente552edb2014-03-10 17:42:56 -07001426
Eric Laurent36829f92017-04-07 19:04:42 -07001427 if (stream == AUDIO_STREAM_MUSIC) {
1428 selectOutputForMusicEffects();
1429 }
1430
Eric Laurent592dd7b2018-08-05 18:58:48 -07001431 if (outputDesc->streamActiveCount(stream) == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001432 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001433 if (device == AUDIO_DEVICE_NONE) {
1434 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001435 }
Eric Laurent36829f92017-04-07 19:04:42 -07001436
Eric Laurente552edb2014-03-10 17:42:56 -07001437 routing_strategy strategy = getStrategy(stream);
1438 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001439 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1440 (beaconMuteLatency > 0);
1441 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001442 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001443 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001444 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001445 // An output has a shared device if
1446 // - managed by the same hw module
1447 // - supports the currently selected device
1448 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
1449 && (desc->supportedDevices() & device) != AUDIO_DEVICE_NONE;
1450
Eric Laurent77305a62016-07-25 16:39:22 -07001451 // force a device change if any other output is:
1452 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001453 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001454 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001455 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001456 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001457 // change the device currently selected by the other output.
1458 if (sharedDevice &&
Eric Laurent77305a62016-07-25 16:39:22 -07001459 desc->device() != device &&
Eric Laurent77305a62016-07-25 16:39:22 -07001460 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001461 force = true;
1462 }
1463 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001464 // a notification so that audio focus effect can propagate, or that a mute/unmute
1465 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001466 const uint32_t latencyMs = desc->latency();
1467 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1468
1469 if (shouldWait && isActive && (waitMs < latencyMs)) {
1470 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001471 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001472
1473 // Require mute check if another output is on a shared device
1474 // and currently active to have proper drain and avoid pops.
1475 // Note restoring AudioTracks onto this output needs to invoke
1476 // a volume ramp if there is no mute.
1477 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001478 }
1479 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001480
1481 const uint32_t muteWaitMs =
1482 setOutputDevice(outputDesc, device, force, 0, NULL, address, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001483
Eric Laurente552edb2014-03-10 17:42:56 -07001484 // apply volume rules for current stream and device if necessary
1485 checkAndSetVolume(stream,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001486 mVolumeCurves->getVolumeIndex(stream, outputDesc->device()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001487 outputDesc,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001488 outputDesc->device());
Eric Laurente552edb2014-03-10 17:42:56 -07001489
1490 // update the outputs if starting an output with a stream that can affect notification
1491 // routing
1492 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001493
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001494 // force reevaluating accessibility routing when ringtone or alarm starts
1495 if (strategy == STRATEGY_SONIFICATION) {
1496 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1497 }
Eric Laurentdc462862016-07-19 12:29:53 -07001498
1499 if (waitMs > muteWaitMs) {
1500 *delayMs = waitMs - muteWaitMs;
1501 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001502
1503 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1504 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1505 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1506 // change occurs after the MixerThread starts and causes a stream volume
1507 // glitch.
1508 //
1509 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001510 }
Eric Laurentdc462862016-07-19 12:29:53 -07001511
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001512 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1513 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1514 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1515 }
1516
Eric Laurent97ac8712018-07-27 18:59:02 -07001517 // Automatically enable the remote submix input when output is started on a re routing mix
1518 // of type MIX_TYPE_RECORDERS
1519 if (audio_is_remote_submix_device(device) && policyMix != NULL &&
1520 policyMix->mMixType == MIX_TYPE_RECORDERS) {
1521 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1522 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1523 address,
1524 "remote-submix");
1525 }
1526
Eric Laurente552edb2014-03-10 17:42:56 -07001527 return NO_ERROR;
1528}
1529
Eric Laurent8fc147b2018-07-22 19:13:55 -07001530status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001531{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001532 ALOGV("%s portId %d", __FUNCTION__, portId);
1533
1534 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1535 if (outputDesc == 0) {
1536 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001537 return BAD_VALUE;
1538 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001539 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001540
Eric Laurent97ac8712018-07-27 18:59:02 -07001541 ALOGV("stopOutput() output %d, stream %d, session %d",
1542 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07001543
Eric Laurent97ac8712018-07-27 18:59:02 -07001544 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08001545
Eric Laurent733ce942017-12-07 12:18:25 -08001546 if (status == NO_ERROR ) {
1547 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001548 }
1549 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001550}
1551
Eric Laurent97ac8712018-07-27 18:59:02 -07001552status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1553 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07001554{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001555 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07001556 audio_stream_type_t stream = client->stream();
1557
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001558 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1559
Eric Laurent592dd7b2018-08-05 18:58:48 -07001560 if (outputDesc->streamActiveCount(stream) > 0) {
1561 if (outputDesc->streamActiveCount(stream) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001562 // Automatically disable the remote submix input when output is stopped on a
1563 // re routing mix of type MIX_TYPE_RECORDERS
1564 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1565 outputDesc->mPolicyMix != NULL &&
1566 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1567 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1568 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1569 outputDesc->mPolicyMix->mDeviceAddress,
1570 "remote-submix");
1571 }
1572 }
1573 bool forceDeviceUpdate = false;
1574 if (client->hasPreferredDevice(true)) {
1575 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1576 forceDeviceUpdate = true;
1577 }
1578
Eric Laurente552edb2014-03-10 17:42:56 -07001579 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07001580 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07001581
Eric Laurente552edb2014-03-10 17:42:56 -07001582 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001583 if (outputDesc->streamActiveCount(stream) == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001584 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001585 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001586 // delay the device switch by twice the latency because stopOutput() is executed when
1587 // the track stop() command is received and at that time the audio track buffer can
1588 // still contain data that needs to be drained. The latency only covers the audio HAL
1589 // and kernel buffers. Also the latency does not always include additional delay in the
1590 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001591 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001592
1593 // force restoring the device selection on other active outputs if it differs from the
1594 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001595 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001596 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001597 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001598 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001599 desc->isActive() &&
1600 outputDesc->sharesHwModuleWith(desc) &&
1601 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001602 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1603 bool force = desc->device() != newDevice2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001604
Eric Laurentc75307b2015-03-17 15:29:32 -07001605 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001606 newDevice2,
1607 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001608 delayMs);
1609 // re-apply device specific volume if not done by setOutputDevice()
1610 if (!force) {
1611 applyStreamVolumes(desc, newDevice2, delayMs);
1612 }
Eric Laurente552edb2014-03-10 17:42:56 -07001613 }
1614 }
1615 // update the outputs if stopping one with a stream that can affect notification routing
1616 handleNotificationRoutingForStream(stream);
1617 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001618
1619 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1620 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1621 setStrategyMute(STRATEGY_SONIFICATION, false, outputDesc);
1622 }
1623
Eric Laurent36829f92017-04-07 19:04:42 -07001624 if (stream == AUDIO_STREAM_MUSIC) {
1625 selectOutputForMusicEffects();
1626 }
Eric Laurente552edb2014-03-10 17:42:56 -07001627 return NO_ERROR;
1628 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001629 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001630 return INVALID_OPERATION;
1631 }
1632}
1633
Eric Laurent8fc147b2018-07-22 19:13:55 -07001634void AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001635{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001636 ALOGV("%s portId %d", __FUNCTION__, portId);
1637
1638 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1639 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07001640 // If an output descriptor is closed due to a device routing change,
1641 // then there are race conditions with releaseOutput from tracks
1642 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
1643 // destroyed shortly thereafter.
1644 //
1645 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07001646 ALOGW("releaseOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001647 return;
1648 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001649
1650 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001651
Eric Laurent8fc147b2018-07-22 19:13:55 -07001652 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1653 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001654 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07001655 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001656 return;
1657 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001658 if (--outputDesc->mDirectOpenCount == 0) {
1659 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07001660 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001661 }
1662 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001663 // stopOutput() needs to be successfully called before releaseOutput()
1664 // otherwise there may be inaccurate stream reference counts.
1665 // This is checked in outputDesc->removeClient below.
1666 outputDesc->removeClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001667}
1668
Eric Laurentcaf7f482014-11-25 17:50:47 -08001669status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1670 audio_io_handle_t *input,
1671 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001672 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001673 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001674 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001675 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001676 input_type_t *inputType,
1677 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001678{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001679 ALOGV("getInputForAttr() source %d, sampling rate %d, format %#x, channel mask %#x,"
Eric Laurentcaf7f482014-11-25 17:50:47 -08001680 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001681 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001682
Eric Laurentad2e7b92017-09-14 20:06:42 -07001683 status_t status = NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -08001684 // handle legacy remote submix case where the address was not always specified
1685 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001686 audio_source_t halInputSource;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001687 audio_source_t inputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001688 AudioMix *policyMix = NULL;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001689 DeviceVector inputDevices;
Eric Laurent8fc147b2018-07-22 19:13:55 -07001690 sp<AudioInputDescriptor> inputDesc;
1691 sp<RecordClientDescriptor> clientDesc;
1692 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001693 bool isSoundTrigger;
1694 audio_devices_t device;
1695
1696 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1697 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1698 return INVALID_OPERATION;
1699 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001700
Eric Laurentfe231122017-11-17 17:48:06 -08001701 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1702 inputSource = AUDIO_SOURCE_MIC;
1703 }
1704
Paul McLean466dc8e2015-04-17 13:15:36 -06001705 // Explicit routing?
1706 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -07001707 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
jiabinc0c831a2018-01-29 17:55:15 -08001708 deviceDesc = mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001709 }
Paul McLean466dc8e2015-04-17 13:15:36 -06001710
Eric Laurentad2e7b92017-09-14 20:06:42 -07001711 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1712 // possible
1713 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1714 *input != AUDIO_IO_HANDLE_NONE) {
1715 ssize_t index = mInputs.indexOfKey(*input);
1716 if (index < 0) {
1717 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1718 status = BAD_VALUE;
1719 goto error;
1720 }
1721 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001722 RecordClientVector clients = inputDesc->getClientsForSession(session);
1723 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001724 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1725 status = BAD_VALUE;
1726 goto error;
1727 }
1728 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1729 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001730 // corresponds to a new client and is only permitted from the same UID.
1731 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07001732 if (clients.size() > 1) {
1733 for (const auto& client : clients) {
1734 // The client map is ordered by key values (portId) and portIds are allocated
1735 // incrementaly. So the first client in this list is the one opened by audio flinger
1736 // when the mmap stream is created and should be ignored as it does not correspond
1737 // to an actual client
1738 if (client == *clients.cbegin()) {
1739 continue;
1740 }
1741 if (uid != client->uid() && !client->isSilenced()) {
1742 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
1743 uid, client->portId(), client->uid());
1744 status = INVALID_OPERATION;
1745 goto error;
1746 }
Eric Laurent331679c2018-04-16 17:03:16 -07001747 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001748 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001749 *inputType = API_INPUT_LEGACY;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001750 device = inputDesc->mDevice;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001751
Eric Laurent8f42ea12018-08-08 09:08:25 -07001752 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001753 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001754 }
1755
1756 *input = AUDIO_IO_HANDLE_NONE;
1757 *inputType = API_INPUT_INVALID;
1758
Eric Laurentad2e7b92017-09-14 20:06:42 -07001759 halInputSource = inputSource;
1760
Eric Laurentc447ded2015-01-06 08:47:05 -08001761 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001762 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001763 status = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
1764 if (status != NO_ERROR) {
1765 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001766 }
1767 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001768 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1769 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001770 } else {
Eric Laurent97ac8712018-07-27 18:59:02 -07001771 if (deviceDesc != 0) {
1772 device = deviceDesc->type();
1773 } else {
1774 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
1775 }
Eric Laurent275e8e92014-11-30 15:14:47 -08001776 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001777 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001778 status = BAD_VALUE;
1779 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001780 }
Eric Laurentc722f302014-12-10 11:21:49 -08001781 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001782 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001783 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1784 // there is an external policy, but this input is attached to a mix of recorders,
1785 // meaning it receives audio injected into the framework, so the recorder doesn't
1786 // know about it and is therefore considered "legacy"
1787 *inputType = API_INPUT_LEGACY;
1788 } else {
1789 // recording a mix of players defined by an external policy, we're rerouting for
1790 // an external policy
1791 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1792 }
Eric Laurentc722f302014-12-10 11:21:49 -08001793 } else if (audio_is_remote_submix_device(device)) {
1794 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001795 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001796 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1797 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001798 } else {
1799 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001800 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001801
Eric Laurent599c7582015-12-07 18:05:55 -08001802 }
1803
Eric Laurent8f42ea12018-08-08 09:08:25 -07001804 *input = getInputForDevice(device, address, session, inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001805 config, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001806 policyMix);
1807 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001808 status = INVALID_OPERATION;
1809 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001810 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001811
Eric Laurent8f42ea12018-08-08 09:08:25 -07001812exit:
1813
Mikhail Naganov708e0382018-05-30 09:53:04 -07001814 inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -07001815 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
Eric Laurent8f42ea12018-08-08 09:08:25 -07001816 : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07001817
Eric Laurent8f42ea12018-08-08 09:08:25 -07001818 isSoundTrigger = inputSource == AUDIO_SOURCE_HOTWORD &&
1819 mSoundTriggerSessions.indexOfKey(session) > 0;
1820 *portId = AudioPort::getNextUniqueId();
1821
Eric Laurent8fc147b2018-07-22 19:13:55 -07001822 clientDesc = new RecordClientDescriptor(*portId, uid, session,
Eric Laurent8f42ea12018-08-08 09:08:25 -07001823 *attr, *config, requestedDeviceId,
1824 inputSource,flags, isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001825 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07001826 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001827
1828 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
1829 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001830
Eric Laurent599c7582015-12-07 18:05:55 -08001831 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001832
1833error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07001834 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001835}
1836
1837
1838audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1839 String8 address,
1840 audio_session_t session,
Eric Laurent599c7582015-12-07 18:05:55 -08001841 audio_source_t inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001842 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08001843 audio_input_flags_t flags,
1844 AudioMix *policyMix)
1845{
1846 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1847 audio_source_t halInputSource = inputSource;
1848 bool isSoundTrigger = false;
1849
1850 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1851 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1852 if (index >= 0) {
1853 input = mSoundTriggerSessions.valueFor(session);
1854 isSoundTrigger = true;
1855 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1856 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1857 } else {
1858 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001859 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001860 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08001861 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001862 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001863 }
1864
Andy Hungf129b032015-04-07 13:45:50 -07001865 // find a compatible input profile (not necessarily identical in parameters)
1866 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08001867 // sampling rate and flags may be updated by getInputProfile
1868 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
1869 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07001870 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08001871 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07001872 audio_input_flags_t profileFlags = flags;
1873 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07001874 profileFormat = config->format; // reset each time through loop, in case it is updated
Eric Laurent275e8e92014-11-30 15:14:47 -08001875 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001876 profileSamplingRate, profileFormat, profileChannelMask,
1877 profileFlags);
1878 if (profile != 0) {
1879 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001880 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1881 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001882 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1883 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1884 } else { // fail
Glenn Kastenfaa10a62017-05-25 15:52:05 -07001885 ALOGW("getInputForDevice() could not find profile for device 0x%X, "
Eric Laurentfe231122017-11-17 17:48:06 -08001886 "sampling rate %u, format %#x, channel mask 0x%X, flags %#x",
1887 device, config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001888 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001889 }
Eric Laurente552edb2014-03-10 17:42:56 -07001890 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001891 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08001892 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08001893 if (samplingRate == 0) {
1894 samplingRate = profileSamplingRate;
1895 }
Eric Laurente552edb2014-03-10 17:42:56 -07001896
Eric Laurent322b4d22015-04-03 15:57:54 -07001897 if (profile->getModuleHandle() == 0) {
1898 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001899 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001900 }
1901
Eric Laurent3974e3b2017-12-07 17:58:43 -08001902 if (!profile->canOpenNewIo()) {
1903 return AUDIO_IO_HANDLE_NONE;
1904 }
1905
Eric Laurentfe231122017-11-17 17:48:06 -08001906 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001907
Eric Laurentfe231122017-11-17 17:48:06 -08001908 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
1909 lConfig.sample_rate = profileSamplingRate;
1910 lConfig.channel_mask = profileChannelMask;
1911 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07001912
Eric Laurent53b810e2017-12-10 17:25:10 -08001913 if (address == "") {
Mikhail Naganov708e0382018-05-30 09:53:04 -07001914 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -08001915 // the inputs vector must be of size >= 1, but we don't want to crash here
1916 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress : String8("");
1917 }
1918
Eric Laurentfe231122017-11-17 17:48:06 -08001919 status_t status = inputDesc->open(&lConfig, device, address,
1920 halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001921
1922 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001923 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08001924 (profileSamplingRate != lConfig.sample_rate) ||
1925 !audio_formats_match(profileFormat, lConfig.format) ||
1926 (profileChannelMask != lConfig.channel_mask)) {
1927 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001928 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08001929 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001930 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001931 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07001932 }
Eric Laurent599c7582015-12-07 18:05:55 -08001933 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001934 }
1935
Eric Laurentc722f302014-12-10 11:21:49 -08001936 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001937
Eric Laurent599c7582015-12-07 18:05:55 -08001938 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001939 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001940
Eric Laurent599c7582015-12-07 18:05:55 -08001941 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001942}
1943
Eric Laurentbb948092017-01-23 18:33:30 -08001944//static
1945bool AudioPolicyManager::isConcurrentSource(audio_source_t source)
1946{
1947 return (source == AUDIO_SOURCE_HOTWORD) ||
1948 (source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
1949 (source == AUDIO_SOURCE_FM_TUNER);
1950}
1951
Chris Thornton2b864642017-06-27 21:26:07 -07001952// FIXME: remove when concurrent capture is ready. This is a hack to work around bug b/63083537.
1953bool AudioPolicyManager::soundTriggerSupportsConcurrentCapture() {
1954 if (!mHasComputedSoundTriggerSupportsConcurrentCapture) {
1955 bool soundTriggerSupportsConcurrentCapture = false;
1956 unsigned int numModules = 0;
1957 struct sound_trigger_module_descriptor* nModules = NULL;
1958
1959 status_t status = SoundTrigger::listModules(nModules, &numModules);
1960 if (status == NO_ERROR && numModules != 0) {
1961 nModules = (struct sound_trigger_module_descriptor*) calloc(
1962 numModules, sizeof(struct sound_trigger_module_descriptor));
1963 if (nModules == NULL) {
1964 // We failed to malloc the buffer, so just say no for now, and hope that we have more
1965 // ram the next time this function is called.
1966 ALOGE("Failed to allocate buffer for module descriptors");
1967 return false;
1968 }
1969
1970 status = SoundTrigger::listModules(nModules, &numModules);
1971 if (status == NO_ERROR) {
1972 soundTriggerSupportsConcurrentCapture = true;
1973 for (size_t i = 0; i < numModules; ++i) {
1974 soundTriggerSupportsConcurrentCapture &=
1975 nModules[i].properties.concurrent_capture;
1976 }
1977 }
1978 free(nModules);
1979 }
1980 mSoundTriggerSupportsConcurrentCapture = soundTriggerSupportsConcurrentCapture;
1981 mHasComputedSoundTriggerSupportsConcurrentCapture = true;
1982 }
1983 return mSoundTriggerSupportsConcurrentCapture;
1984}
1985
Eric Laurentfb66dd92016-01-28 18:32:03 -08001986
Eric Laurent8fc147b2018-07-22 19:13:55 -07001987status_t AudioPolicyManager::startInput(audio_port_handle_t portId,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001988 bool silenced,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001989 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07001990{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001991 *concurrency = API_INPUT_CONCURRENCY_NONE;
1992
1993 ALOGV("%s portId %d", __FUNCTION__, portId);
1994
1995 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
1996 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07001997 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001998 return BAD_VALUE;
1999 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002000 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002001 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002002 if (client->active()) {
2003 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2004 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002005 }
2006
Eric Laurent8f42ea12018-08-08 09:08:25 -07002007 audio_session_t session = client->session();
2008
2009 ALOGV("%s input:%d, session:%d, silenced:%d, concurrency:%d)",
2010 __FUNCTION__, input, session, silenced, *concurrency);
2011
Eric Laurent74708e72017-04-07 17:13:42 -07002012 if (!is_virtual_input_device(inputDesc->mDevice)) {
2013 if (mCallTxPatch != 0 &&
2014 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
2015 ALOGW("startInput(%d) failed: call in progress", input);
Ray Essick84e84a52018-05-03 18:45:07 -07002016 *concurrency |= API_INPUT_CONCURRENCY_CALL;
Eric Laurent74708e72017-04-07 17:13:42 -07002017 return INVALID_OPERATION;
2018 }
2019
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002020 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002021
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002022 // If a UID is idle and records silence and another not silenced recording starts
2023 // from another UID (idle or active) we stop the current idle UID recording in
2024 // favor of the new one - "There can be only one" TM
2025 if (!silenced) {
2026 for (const auto& activeDesc : activeInputs) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002027 if ((activeDesc->getAudioPort()->getFlags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002028 activeDesc->getId() == inputDesc->getId()) {
2029 continue;
2030 }
2031
Eric Laurent8f42ea12018-08-08 09:08:25 -07002032 RecordClientVector activeClients = activeDesc->clientsList(true /*activeOnly*/);
2033 for (const auto& activeClient : activeClients) {
2034 if (activeClient->isSilenced()) {
2035 closeClient(activeClient->portId());
2036 ALOGV("%s client %d stopping silenced client %d", __FUNCTION__,
2037 portId, activeClient->portId());
2038 activeInputs = mInputs.getActiveInputs();
2039 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002040 }
2041 }
2042 }
2043
2044 for (const auto& activeDesc : activeInputs) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002045 if ((client->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
Eric Laurentcb4dae22017-07-01 19:39:32 -07002046 activeDesc->getId() == inputDesc->getId()) {
2047 continue;
2048 }
2049
Eric Laurent74708e72017-04-07 17:13:42 -07002050 audio_source_t activeSource = activeDesc->inputSource(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002051 if (client->source() == AUDIO_SOURCE_HOTWORD) {
Eric Laurent74708e72017-04-07 17:13:42 -07002052 if (activeSource == AUDIO_SOURCE_HOTWORD) {
2053 if (activeDesc->hasPreemptedSession(session)) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002054 ALOGW("%s input %d failed for HOTWORD: "
2055 "other input %d already started for HOTWORD", __FUNCTION__,
Eric Laurent74708e72017-04-07 17:13:42 -07002056 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07002057 *concurrency |= API_INPUT_CONCURRENCY_HOTWORD;
Eric Laurent74708e72017-04-07 17:13:42 -07002058 return INVALID_OPERATION;
2059 }
2060 } else {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002061 ALOGV("%s input %d failed for HOTWORD: other input %d already started",
2062 __FUNCTION__, input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07002063 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07002064 return INVALID_OPERATION;
2065 }
2066 } else {
2067 if (activeSource != AUDIO_SOURCE_HOTWORD) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002068 ALOGW("%s input %d failed: other input %d already started", __FUNCTION__,
Eric Laurent74708e72017-04-07 17:13:42 -07002069 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07002070 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07002071 return INVALID_OPERATION;
2072 }
2073 }
2074 }
2075
Chris Thornton2b864642017-06-27 21:26:07 -07002076 // We only need to check if the sound trigger session supports concurrent capture if the
2077 // input is also a sound trigger input. Otherwise, we should preempt any hotword stream
2078 // that's running.
2079 const bool allowConcurrentWithSoundTrigger =
2080 inputDesc->isSoundTrigger() ? soundTriggerSupportsConcurrentCapture() : false;
2081
Eric Laurent74708e72017-04-07 17:13:42 -07002082 // if capture is allowed, preempt currently active HOTWORD captures
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002083 for (const auto& activeDesc : activeInputs) {
Chris Thornton2b864642017-06-27 21:26:07 -07002084 if (allowConcurrentWithSoundTrigger && activeDesc->isSoundTrigger()) {
2085 continue;
2086 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002087 RecordClientVector activeHotwordClients =
2088 activeDesc->clientsList(true, AUDIO_SOURCE_HOTWORD);
2089 if (activeHotwordClients.size() > 0) {
Eric Laurent74708e72017-04-07 17:13:42 -07002090 SortedVector<audio_session_t> sessions = activeDesc->getPreemptedSessions();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002091
2092 for (const auto& activeClient : activeHotwordClients) {
2093 *concurrency |= API_INPUT_CONCURRENCY_PREEMPT;
2094 sessions.add(activeClient->session());
2095 closeClient(activeClient->portId());
2096 ALOGV("%s input %d for HOTWORD preempting HOTWORD input %d", __FUNCTION__,
2097 input, activeDesc->mIoHandle);
2098 }
2099
Eric Laurent74708e72017-04-07 17:13:42 -07002100 inputDesc->setPreemptedSessions(sessions);
Eric Laurent74708e72017-04-07 17:13:42 -07002101 }
2102 }
2103 }
Eric Laurente552edb2014-03-10 17:42:56 -07002104
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002105 // Make sure we start with the correct silence state
Eric Laurent8f42ea12018-08-08 09:08:25 -07002106 client->setSilenced(silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002107
Eric Laurent313d1e72016-01-29 09:56:57 -08002108 // increment activity count before calling getNewInputDevice() below as only active sessions
2109 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002110 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002111
Eric Laurent8f42ea12018-08-08 09:08:25 -07002112 // indicate active capture to sound trigger service if starting capture from a mic on
2113 // primary HW module
2114 audio_devices_t device = getNewInputDevice(inputDesc);
2115 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002116
Eric Laurent8f42ea12018-08-08 09:08:25 -07002117 status_t status = inputDesc->start();
2118 if (status != NO_ERROR) {
2119 inputDesc->setClientActive(client, false);
2120 return status;
2121 }
2122
2123 if (inputDesc->activeCount() == 1) {
2124 // if input maps to a dynamic policy with an activity listener, notify of state change
2125 if ((inputDesc->mPolicyMix != NULL)
2126 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2127 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2128 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002129 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002130
Eric Laurent8f42ea12018-08-08 09:08:25 -07002131 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2132 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2133 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
2134 SoundTrigger::setCaptureState(true);
2135 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002136
Eric Laurent8f42ea12018-08-08 09:08:25 -07002137 // automatically enable the remote submix output when input is started if not
2138 // used by a policy mix of type MIX_TYPE_RECORDERS
2139 // For remote submix (a virtual device), we open only one input per capture request.
2140 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2141 String8 address = String8("");
2142 if (inputDesc->mPolicyMix == NULL) {
2143 address = String8("0");
2144 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2145 address = inputDesc->mPolicyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002146 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002147 if (address != "") {
2148 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2149 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2150 address, "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08002151 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002152 }
Eric Laurente552edb2014-03-10 17:42:56 -07002153 }
2154
Eric Laurent8f42ea12018-08-08 09:08:25 -07002155 ALOGV("%s input %d source = %d exit", __FUNCTION__, input, client->source());
Eric Laurente552edb2014-03-10 17:42:56 -07002156
Eric Laurente552edb2014-03-10 17:42:56 -07002157 return NO_ERROR;
2158}
2159
Eric Laurent8fc147b2018-07-22 19:13:55 -07002160status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002161{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002162 ALOGV("%s portId %d", __FUNCTION__, portId);
2163
2164 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2165 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002166 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002167 return BAD_VALUE;
2168 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002169 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002170 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002171 if (!client->active()) {
2172 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002173 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002174 }
2175
Eric Laurent8f42ea12018-08-08 09:08:25 -07002176 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002177
Eric Laurent8f42ea12018-08-08 09:08:25 -07002178 inputDesc->stop();
2179 if (inputDesc->isActive()) {
2180 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2181 } else {
2182 // if input maps to a dynamic policy with an activity listener, notify of state change
2183 if ((inputDesc->mPolicyMix != NULL)
2184 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2185 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2186 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002187 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002188
2189 // automatically disable the remote submix output when input is stopped if not
2190 // used by a policy mix of type MIX_TYPE_RECORDERS
2191 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2192 String8 address = String8("");
2193 if (inputDesc->mPolicyMix == NULL) {
2194 address = String8("0");
2195 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2196 address = inputDesc->mPolicyMix->mDeviceAddress;
2197 }
2198 if (address != "") {
2199 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2200 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2201 address, "remote-submix");
2202 }
2203 }
2204
2205 audio_devices_t device = inputDesc->mDevice;
2206 resetInputDevice(input);
2207
2208 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2209 // primary HW module
2210 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2211 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2212 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
2213 SoundTrigger::setCaptureState(false);
2214 }
2215 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002216 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002217 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002218}
2219
Eric Laurent8fc147b2018-07-22 19:13:55 -07002220void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002221{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002222 ALOGV("%s portId %d", __FUNCTION__, portId);
2223
2224 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2225 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002226 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002227 return;
2228 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002229 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002230 audio_io_handle_t input = inputDesc->mIoHandle;
2231
Eric Laurent8f42ea12018-08-08 09:08:25 -07002232 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002233
Andy Hung39efb7a2018-09-26 15:39:28 -07002234 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002235
Andy Hung39efb7a2018-09-26 15:39:28 -07002236 if (inputDesc->getClientCount() > 0) {
2237 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002238 return;
2239 }
2240
Eric Laurent05b90f82014-08-27 15:32:29 -07002241 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002242 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002243 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002244}
2245
Eric Laurent8f42ea12018-08-08 09:08:25 -07002246void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002247{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002248 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002249
2250 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002251 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002252 }
2253}
2254
Eric Laurent8f42ea12018-08-08 09:08:25 -07002255void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2256{
2257 stopInput(portId);
2258 releaseInput(portId);
2259}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002260
Eric Laurentd4692962014-05-05 18:13:44 -07002261void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002262 bool patchRemoved = false;
2263
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002264 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002265 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002266 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002267 if (patch_index >= 0) {
2268 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002269 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002270 mAudioPatches.removeItemsAt(patch_index);
2271 patchRemoved = true;
2272 }
Eric Laurentfe231122017-11-17 17:48:06 -08002273 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002274 }
2275 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002276 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002277 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002278
2279 if (patchRemoved) {
2280 mpClientInterface->onAudioPatchListUpdate();
2281 }
Eric Laurentd4692962014-05-05 18:13:44 -07002282}
2283
Eric Laurente0720872014-03-11 09:30:41 -07002284void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002285 int indexMin,
2286 int indexMax)
2287{
2288 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002289 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002290
2291 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002292 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2293 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002294 continue;
2295 }
2296 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002297 }
Eric Laurente552edb2014-03-10 17:42:56 -07002298}
2299
Eric Laurente0720872014-03-11 09:30:41 -07002300status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002301 int index,
2302 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002303{
2304
Nadav Bar7c605f62017-12-25 00:01:52 +02002305 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2306 // app that has MODIFY_PHONE_STATE permission.
2307 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
2308 !(stream == AUDIO_STREAM_VOICE_CALL && index == 0)) ||
François Gaffied1ab2bd2015-12-02 18:20:06 +01002309 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002310 return BAD_VALUE;
2311 }
2312 if (!audio_is_output_device(device)) {
2313 return BAD_VALUE;
2314 }
2315
2316 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002317 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002318
Eric Laurent1fd372e2016-04-06 14:23:53 -07002319 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002320 stream, device, index);
2321
Eric Laurent28d09f02016-03-08 10:43:05 -08002322 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002323 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2324 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002325 continue;
2326 }
2327 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2328 }
Eric Laurente552edb2014-03-10 17:42:56 -07002329
Eric Laurent1fd372e2016-04-06 14:23:53 -07002330 // update volume on all outputs and streams matching the following:
2331 // - The requested stream (or a stream matching for volume control) is active on the output
2332 // - The device (or devices) selected by the strategy corresponding to this stream includes
2333 // the requested device
2334 // - For non default requested device, currently selected device on the output is either the
2335 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002336 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2337 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002338 status_t status = NO_ERROR;
2339 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002340 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2341 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08002342 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
Eric Laurent3839bc02018-07-10 18:33:34 -07002343 if (!(streamsMatchForvolume(stream, (audio_stream_type_t)curStream))) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002344 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002345 }
Eric Laurentdcd4ab12018-06-29 17:45:13 -07002346 if (!(desc->isStreamActive((audio_stream_type_t)curStream) || isInCall())) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002347 continue;
2348 }
Eric Laurent794fde22016-03-11 09:50:45 -08002349 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002350 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2351 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002352 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2353 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002354 continue;
2355 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002356 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002357 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002358 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07002359 applyVolume = (curDevice & curStreamDevice) != 0;
2360 } else {
2361 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002362 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002363 }
Eric Laurent3839bc02018-07-10 18:33:34 -07002364 // rescale index before applying to curStream as ranges may be different for
2365 // stream and curStream
2366 int idx = rescaleVolumeIndex(index, stream, (audio_stream_type_t)curStream);
Eric Laurente76f29c2016-09-14 17:17:53 -07002367 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002368 //FIXME: workaround for truncated touch sounds
2369 // delayed volume change for system stream to be removed when the problem is
2370 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002371 status_t volStatus =
Eric Laurent3839bc02018-07-10 18:33:34 -07002372 checkAndSetVolume((audio_stream_type_t)curStream, idx, desc, curDevice,
Eric Laurentdc462862016-07-19 12:29:53 -07002373 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002374 if (volStatus != NO_ERROR) {
2375 status = volStatus;
2376 }
2377 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002378 }
Eric Laurente552edb2014-03-10 17:42:56 -07002379 }
2380 return status;
2381}
2382
Eric Laurente0720872014-03-11 09:30:41 -07002383status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002384 int *index,
2385 audio_devices_t device)
2386{
2387 if (index == NULL) {
2388 return BAD_VALUE;
2389 }
2390 if (!audio_is_output_device(device)) {
2391 return BAD_VALUE;
2392 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002393 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002394 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002395 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002396 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2397 }
François Gaffiedfd74092015-03-19 12:10:59 +01002398 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002399
François Gaffied1ab2bd2015-12-02 18:20:06 +01002400 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002401 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2402 return NO_ERROR;
2403}
2404
Eric Laurent36829f92017-04-07 19:04:42 -07002405audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002406{
2407 // select one output among several suitable for global effects.
2408 // The priority is as follows:
2409 // 1: An offloaded output. If the effect ends up not being offloadable,
2410 // AudioFlinger will invalidate the track and the offloaded output
2411 // will be closed causing the effect to be moved to a PCM output.
2412 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002413 // 3: The primary output
2414 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002415
Eric Laurent3b73df72014-03-11 09:06:29 -07002416 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002417 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent36829f92017-04-07 19:04:42 -07002418 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002419
Eric Laurent36829f92017-04-07 19:04:42 -07002420 if (outputs.size() == 0) {
2421 return AUDIO_IO_HANDLE_NONE;
2422 }
Eric Laurente552edb2014-03-10 17:42:56 -07002423
Eric Laurent36829f92017-04-07 19:04:42 -07002424 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2425 bool activeOnly = true;
2426
2427 while (output == AUDIO_IO_HANDLE_NONE) {
2428 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2429 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2430 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2431
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002432 for (audio_io_handle_t output : outputs) {
2433 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002434 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2435 continue;
2436 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002437 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2438 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002439 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002440 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002441 }
2442 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002443 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002444 }
2445 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002446 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002447 }
2448 }
2449 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2450 output = outputOffloaded;
2451 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2452 output = outputDeepBuffer;
2453 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2454 output = outputPrimary;
2455 } else {
2456 output = outputs[0];
2457 }
2458 activeOnly = false;
2459 }
2460
2461 if (output != mMusicEffectOutput) {
2462 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2463 mMusicEffectOutput = output;
2464 }
2465
2466 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002467 return output;
2468}
2469
Eric Laurent36829f92017-04-07 19:04:42 -07002470audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2471{
2472 return selectOutputForMusicEffects();
2473}
2474
Eric Laurente0720872014-03-11 09:30:41 -07002475status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002476 audio_io_handle_t io,
2477 uint32_t strategy,
2478 int session,
2479 int id)
2480{
2481 ssize_t index = mOutputs.indexOfKey(io);
2482 if (index < 0) {
2483 index = mInputs.indexOfKey(io);
2484 if (index < 0) {
2485 ALOGW("registerEffect() unknown io %d", io);
2486 return INVALID_OPERATION;
2487 }
2488 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002489 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002490}
2491
Eric Laurentc75307b2015-03-17 15:29:32 -07002492bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2493{
Eric Laurent28d09f02016-03-08 10:43:05 -08002494 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002495 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2496 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002497 continue;
2498 }
2499 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2500 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002501 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002502}
2503
2504bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2505{
2506 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2507}
2508
Eric Laurente0720872014-03-11 09:30:41 -07002509bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002510{
2511 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002512 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002513 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002514 return true;
2515 }
2516 }
2517 return false;
2518}
2519
Eric Laurent275e8e92014-11-30 15:14:47 -08002520// Register a list of custom mixes with their attributes and format.
2521// When a mix is registered, corresponding input and output profiles are
2522// added to the remote submix hw module. The profile contains only the
2523// parameters (sampling rate, format...) specified by the mix.
2524// The corresponding input remote submix device is also connected.
2525//
2526// When a remote submix device is connected, the address is checked to select the
2527// appropriate profile and the corresponding input or output stream is opened.
2528//
2529// When capture starts, getInputForAttr() will:
2530// - 1 look for a mix matching the address passed in attribtutes tags if any
2531// - 2 if none found, getDeviceForInputSource() will:
2532// - 2.1 look for a mix matching the attributes source
2533// - 2.2 if none found, default to device selection by policy rules
2534// At this time, the corresponding output remote submix device is also connected
2535// and active playback use cases can be transferred to this mix if needed when reconnecting
2536// after AudioTracks are invalidated
2537//
2538// When playback starts, getOutputForAttr() will:
2539// - 1 look for a mix matching the address passed in attribtutes tags if any
2540// - 2 if none found, look for a mix matching the attributes usage
2541// - 3 if none found, default to device and output selection by policy rules.
2542
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002543status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002544{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002545 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2546 status_t res = NO_ERROR;
2547
2548 sp<HwModule> rSubmixModule;
2549 // examine each mix's route type
2550 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002551 AudioMix mix = mixes[i];
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002552 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
Eric Laurent97ac8712018-07-27 18:59:02 -07002553 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002554 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002555 break;
2556 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002557 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002558 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002559 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002560 rSubmixModule = mHwModules.getModuleFromName(
2561 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2562 if (rSubmixModule == 0) {
2563 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2564 i);
2565 res = INVALID_OPERATION;
2566 break;
2567 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002568 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002569
Eric Laurent97ac8712018-07-27 18:59:02 -07002570 String8 address = mix.mDeviceAddress;
2571 if (mix.mMixType == MIX_TYPE_PLAYERS) {
2572 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2573 } else {
2574 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
2575 }
François Gaffie036e1e92015-03-19 10:16:24 +01002576
Eric Laurent97ac8712018-07-27 18:59:02 -07002577 if (mPolicyMixes.registerMix(address, mix, 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002578 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002579 res = INVALID_OPERATION;
2580 break;
2581 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002582 audio_config_t outputConfig = mix.mFormat;
2583 audio_config_t inputConfig = mix.mFormat;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002584 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2585 // stereo and let audio flinger do the channel conversion if needed.
2586 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2587 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2588 rSubmixModule->addOutputProfile(address, &outputConfig,
2589 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2590 rSubmixModule->addInputProfile(address, &inputConfig,
2591 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002592
Eric Laurent97ac8712018-07-27 18:59:02 -07002593 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002594 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2595 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2596 address.string(), "remote-submix");
2597 } else {
2598 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2599 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2600 address.string(), "remote-submix");
2601 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002602 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2603 String8 address = mix.mDeviceAddress;
2604 audio_devices_t device = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002605 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2606 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002607
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002608 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002609 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2610 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2611 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2612 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2613 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2614 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002615 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2616 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002617 if (mPolicyMixes.registerMix(address, mix, desc) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002618 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002619 } else {
2620 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002621 }
2622 break;
2623 }
2624 }
2625
2626 if (res != NO_ERROR) {
2627 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002628 i, device, address.string());
2629 res = INVALID_OPERATION;
2630 break;
2631 } else if (!foundOutput) {
2632 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2633 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002634 res = INVALID_OPERATION;
2635 break;
2636 }
Eric Laurentc722f302014-12-10 11:21:49 -08002637 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002638 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002639 if (res != NO_ERROR) {
2640 unregisterPolicyMixes(mixes);
2641 }
2642 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002643}
2644
2645status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2646{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002647 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002648 status_t res = NO_ERROR;
2649 sp<HwModule> rSubmixModule;
2650 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002651 for (const auto& mix : mixes) {
2652 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002653
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002654 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002655 rSubmixModule = mHwModules.getModuleFromName(
2656 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2657 if (rSubmixModule == 0) {
2658 res = INVALID_OPERATION;
2659 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002660 }
2661 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002662
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002663 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002664
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002665 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2666 res = INVALID_OPERATION;
2667 continue;
2668 }
2669
2670 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2671 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2672 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2673 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2674 address.string(), "remote-submix");
2675 }
2676 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2677 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2678 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2679 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2680 address.string(), "remote-submix");
2681 }
2682 rSubmixModule->removeOutputProfile(address);
2683 rSubmixModule->removeInputProfile(address);
2684
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002685 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2686 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002687 res = INVALID_OPERATION;
2688 continue;
2689 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002690 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002691 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002692 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002693}
2694
Andy Hungc29d82b2018-10-05 12:23:17 -07002695void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07002696{
Andy Hungc29d82b2018-10-05 12:23:17 -07002697 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
2698 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07002699 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002700 std::string stateLiteral;
2701 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07002702 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002703 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
2704 "communications", "media", "record", "dock", "system",
2705 "HDMI system audio", "encoded surround output", "vibrate ringing" };
2706 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
2707 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Andy Hungc29d82b2018-10-05 12:23:17 -07002708 dst->appendFormat(" Force use for %s: %d\n",
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002709 forceUses[i], mEngine->getForceUse(i));
2710 }
Andy Hungc29d82b2018-10-05 12:23:17 -07002711 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
2712 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
2713 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
2714 mAvailableOutputDevices.dump(dst, String8("Available output"));
2715 mAvailableInputDevices.dump(dst, String8("Available input"));
2716 mHwModulesAll.dump(dst);
2717 mOutputs.dump(dst);
2718 mInputs.dump(dst);
2719 mVolumeCurves->dump(dst);
2720 mEffects.dump(dst);
2721 mAudioPatches.dump(dst);
2722 mPolicyMixes.dump(dst);
2723 mAudioSources.dump(dst);
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002724 if (!mSurroundFormats.empty()) {
Andy Hungc29d82b2018-10-05 12:23:17 -07002725 dst->append("\nEnabled Surround Formats:\n");
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002726 size_t i = 0;
2727 for (const auto& fmt : mSurroundFormats) {
Andy Hungc29d82b2018-10-05 12:23:17 -07002728 dst->append(i++ == 0 ? " " : ", ");
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002729 std::string sfmt;
2730 FormatConverter::toString(fmt, sfmt);
Andy Hungc29d82b2018-10-05 12:23:17 -07002731 dst->append(sfmt.c_str());
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002732 }
Andy Hungc29d82b2018-10-05 12:23:17 -07002733 dst->append("\n");
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002734 }
Andy Hungc29d82b2018-10-05 12:23:17 -07002735}
2736
2737status_t AudioPolicyManager::dump(int fd)
2738{
2739 String8 result;
2740 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07002741 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002742 return NO_ERROR;
2743}
2744
2745// This function checks for the parameters which can be offloaded.
2746// This can be enhanced depending on the capability of the DSP and policy
2747// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002748bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002749{
2750 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002751 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002752 offloadInfo.sample_rate, offloadInfo.channel_mask,
2753 offloadInfo.format,
2754 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2755 offloadInfo.has_video);
2756
Andy Hung2ddee192015-12-18 17:34:44 -08002757 if (mMasterMono) {
2758 return false; // no offloading if mono is set.
2759 }
2760
Eric Laurente552edb2014-03-10 17:42:56 -07002761 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07002762 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
2763 ALOGV("offload disabled by audio.offload.disable");
2764 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002765 }
2766
2767 // Check if stream type is music, then only allow offload as of now.
2768 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2769 {
2770 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2771 return false;
2772 }
2773
2774 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002775 const bool allowOffloadWithVideo =
2776 property_get_bool("audio.offload.video", false /* default_value */);
2777 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002778 ALOGV("isOffloadSupported: has_video == true, returning false");
2779 return false;
2780 }
2781
2782 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07002783 const int min_duration_secs = property_get_int32(
2784 "audio.offload.min.duration.secs", -1 /* default_value */);
2785 if (min_duration_secs >= 0) {
2786 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
2787 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%d)",
2788 min_duration_secs);
Eric Laurente552edb2014-03-10 17:42:56 -07002789 return false;
2790 }
2791 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2792 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2793 return false;
2794 }
2795
2796 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2797 // creating an offloaded track and tearing it down immediately after start when audioflinger
2798 // detects there is an active non offloadable effect.
2799 // FIXME: We should check the audio session here but we do not have it in this context.
2800 // This may prevent offloading in rare situations where effects are left active by apps
2801 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002802 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002803 return false;
2804 }
2805
2806 // See if there is a profile to support this.
2807 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002808 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002809 offloadInfo.sample_rate,
2810 offloadInfo.format,
2811 offloadInfo.channel_mask,
2812 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002813 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2814 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002815}
2816
Eric Laurent6a94d692014-05-20 11:18:06 -07002817status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2818 audio_port_type_t type,
2819 unsigned int *num_ports,
2820 struct audio_port *ports,
2821 unsigned int *generation)
2822{
2823 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2824 generation == NULL) {
2825 return BAD_VALUE;
2826 }
2827 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2828 if (ports == NULL) {
2829 *num_ports = 0;
2830 }
2831
2832 size_t portsWritten = 0;
2833 size_t portsMax = *num_ports;
2834 *num_ports = 0;
2835 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002836 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2837 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002838 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002839 for (const auto& dev : mAvailableOutputDevices) {
2840 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002841 continue;
2842 }
2843 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002844 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002845 }
2846 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002847 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002848 }
2849 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002850 for (const auto& dev : mAvailableInputDevices) {
2851 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002852 continue;
2853 }
2854 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002855 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002856 }
2857 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002858 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002859 }
2860 }
2861 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2862 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2863 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2864 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2865 }
2866 *num_ports += mInputs.size();
2867 }
2868 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002869 size_t numOutputs = 0;
2870 for (size_t i = 0; i < mOutputs.size(); i++) {
2871 if (!mOutputs[i]->isDuplicated()) {
2872 numOutputs++;
2873 if (portsWritten < portsMax) {
2874 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2875 }
2876 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002877 }
Eric Laurent84c70242014-06-23 08:46:27 -07002878 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002879 }
2880 }
2881 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002882 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002883 return NO_ERROR;
2884}
2885
Eric Laurent99fcae42018-05-17 16:59:18 -07002886status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07002887{
Eric Laurent99fcae42018-05-17 16:59:18 -07002888 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
2889 return BAD_VALUE;
2890 }
2891 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
2892 if (dev != 0) {
2893 dev->toAudioPort(port);
2894 return NO_ERROR;
2895 }
2896 dev = mAvailableInputDevices.getDeviceFromId(port->id);
2897 if (dev != 0) {
2898 dev->toAudioPort(port);
2899 return NO_ERROR;
2900 }
2901 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
2902 if (out != 0) {
2903 out->toAudioPort(port);
2904 return NO_ERROR;
2905 }
2906 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
2907 if (in != 0) {
2908 in->toAudioPort(port);
2909 return NO_ERROR;
2910 }
2911 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002912}
2913
Eric Laurent6a94d692014-05-20 11:18:06 -07002914status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2915 audio_patch_handle_t *handle,
2916 uid_t uid)
2917{
2918 ALOGV("createAudioPatch()");
2919
2920 if (handle == NULL || patch == NULL) {
2921 return BAD_VALUE;
2922 }
2923 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2924
Mikhail Naganovac9858b2018-06-15 13:12:37 -07002925 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07002926 return BAD_VALUE;
2927 }
2928 // only one source per audio patch supported for now
2929 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002930 return INVALID_OPERATION;
2931 }
Eric Laurent874c42872014-08-08 15:13:39 -07002932
2933 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002934 return INVALID_OPERATION;
2935 }
Eric Laurent874c42872014-08-08 15:13:39 -07002936 for (size_t i = 0; i < patch->num_sinks; i++) {
2937 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2938 return INVALID_OPERATION;
2939 }
2940 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002941
2942 sp<AudioPatch> patchDesc;
2943 ssize_t index = mAudioPatches.indexOfKey(*handle);
2944
Eric Laurent6a94d692014-05-20 11:18:06 -07002945 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2946 patch->sources[0].role,
2947 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002948#if LOG_NDEBUG == 0
2949 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002950 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002951 patch->sinks[i].role,
2952 patch->sinks[i].type);
2953 }
2954#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002955
2956 if (index >= 0) {
2957 patchDesc = mAudioPatches.valueAt(index);
2958 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2959 mUidCached, patchDesc->mUid, uid);
2960 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2961 return INVALID_OPERATION;
2962 }
2963 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002964 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002965 }
2966
2967 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002968 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002969 if (outputDesc == NULL) {
2970 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2971 return BAD_VALUE;
2972 }
Eric Laurent84c70242014-06-23 08:46:27 -07002973 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2974 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002975 if (patchDesc != 0) {
2976 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2977 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2978 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2979 return BAD_VALUE;
2980 }
2981 }
Eric Laurent874c42872014-08-08 15:13:39 -07002982 DeviceVector devices;
2983 for (size_t i = 0; i < patch->num_sinks; i++) {
2984 // Only support mix to devices connection
2985 // TODO add support for mix to mix connection
2986 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2987 ALOGV("createAudioPatch() source mix but sink is not a device");
2988 return INVALID_OPERATION;
2989 }
2990 sp<DeviceDescriptor> devDesc =
2991 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2992 if (devDesc == 0) {
2993 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2994 return BAD_VALUE;
2995 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002996
François Gaffie53615e22015-03-19 09:24:12 +01002997 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002998 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002999 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01003000 NULL, // updatedSamplingRate
3001 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003002 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01003003 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003004 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01003005 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07003006 ALOGV("createAudioPatch() profile not supported for device %08x",
3007 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07003008 return INVALID_OPERATION;
3009 }
3010 devices.add(devDesc);
3011 }
3012 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003013 return INVALID_OPERATION;
3014 }
Eric Laurent874c42872014-08-08 15:13:39 -07003015
Eric Laurent6a94d692014-05-20 11:18:06 -07003016 // TODO: reconfigure output format and channels here
3017 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07003018 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07003019 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003020 index = mAudioPatches.indexOfKey(*handle);
3021 if (index >= 0) {
3022 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3023 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
3024 }
3025 patchDesc = mAudioPatches.valueAt(index);
3026 patchDesc->mUid = uid;
3027 ALOGV("createAudioPatch() success");
3028 } else {
3029 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
3030 return INVALID_OPERATION;
3031 }
3032 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3033 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3034 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003035 // only one sink supported when connecting an input device to a mix
3036 if (patch->num_sinks > 1) {
3037 return INVALID_OPERATION;
3038 }
François Gaffie53615e22015-03-19 09:24:12 +01003039 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003040 if (inputDesc == NULL) {
3041 return BAD_VALUE;
3042 }
3043 if (patchDesc != 0) {
3044 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3045 return BAD_VALUE;
3046 }
3047 }
3048 sp<DeviceDescriptor> devDesc =
3049 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
3050 if (devDesc == 0) {
3051 return BAD_VALUE;
3052 }
3053
François Gaffie53615e22015-03-19 09:24:12 +01003054 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08003055 devDesc->mAddress,
3056 patch->sinks[0].sample_rate,
3057 NULL, /*updatedSampleRate*/
3058 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003059 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003060 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003061 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003062 // FIXME for the parameter type,
3063 // and the NONE
3064 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003065 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003066 return INVALID_OPERATION;
3067 }
3068 // TODO: reconfigure output format and channels here
3069 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01003070 devDesc->type(), inputDesc->mIoHandle);
3071 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003072 index = mAudioPatches.indexOfKey(*handle);
3073 if (index >= 0) {
3074 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3075 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
3076 }
3077 patchDesc = mAudioPatches.valueAt(index);
3078 patchDesc->mUid = uid;
3079 ALOGV("createAudioPatch() success");
3080 } else {
3081 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
3082 return INVALID_OPERATION;
3083 }
3084 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3085 // device to device connection
3086 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003087 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003088 return BAD_VALUE;
3089 }
3090 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003091 sp<DeviceDescriptor> srcDeviceDesc =
3092 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07003093 if (srcDeviceDesc == 0) {
3094 return BAD_VALUE;
3095 }
Eric Laurent874c42872014-08-08 15:13:39 -07003096
Eric Laurent6a94d692014-05-20 11:18:06 -07003097 //update source and sink with our own data as the data passed in the patch may
3098 // be incomplete.
3099 struct audio_patch newPatch = *patch;
3100 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003101
Eric Laurent874c42872014-08-08 15:13:39 -07003102 for (size_t i = 0; i < patch->num_sinks; i++) {
3103 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3104 ALOGV("createAudioPatch() source device but one sink is not a device");
3105 return INVALID_OPERATION;
3106 }
3107
3108 sp<DeviceDescriptor> sinkDeviceDesc =
3109 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3110 if (sinkDeviceDesc == 0) {
3111 return BAD_VALUE;
3112 }
3113 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
3114
Eric Laurent3bcf8592015-04-03 12:13:24 -07003115 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003116 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003117 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08003118 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003119 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003120 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003121 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003122 return INVALID_OPERATION;
3123 }
Eric Laurent874c42872014-08-08 15:13:39 -07003124 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01003125 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003126 // if the sink device is reachable via an opened output stream, request to go via
3127 // this output stream by adding a second source to the patch description
jiabin40573322018-11-08 12:08:02 -08003128 audio_io_handle_t output = selectOutput(outputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003129 if (output != AUDIO_IO_HANDLE_NONE) {
3130 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3131 if (outputDesc->isDuplicated()) {
3132 return INVALID_OPERATION;
3133 }
3134 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003135 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003136 newPatch.num_sources = 2;
3137 }
Eric Laurent83b88082014-06-20 18:31:16 -07003138 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003139 }
3140 // TODO: check from routing capabilities in config file and other conflicting patches
3141
Mikhail Naganovdc769682018-05-04 15:34:08 -07003142 status_t status = installPatch(__func__, index, handle, &newPatch, 0, uid, &patchDesc);
3143 if (status != NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003144 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3145 status);
3146 return INVALID_OPERATION;
3147 }
3148 } else {
3149 return BAD_VALUE;
3150 }
3151 } else {
3152 return BAD_VALUE;
3153 }
3154 return NO_ERROR;
3155}
3156
3157status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3158 uid_t uid)
3159{
3160 ALOGV("releaseAudioPatch() patch %d", handle);
3161
3162 ssize_t index = mAudioPatches.indexOfKey(handle);
3163
3164 if (index < 0) {
3165 return BAD_VALUE;
3166 }
3167 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3168 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3169 mUidCached, patchDesc->mUid, uid);
3170 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3171 return INVALID_OPERATION;
3172 }
3173
3174 struct audio_patch *patch = &patchDesc->mPatch;
3175 patchDesc->mUid = mUidCached;
3176 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003177 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003178 if (outputDesc == NULL) {
3179 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3180 return BAD_VALUE;
3181 }
3182
Eric Laurentc75307b2015-03-17 15:29:32 -07003183 setOutputDevice(outputDesc,
3184 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07003185 true,
3186 0,
3187 NULL);
3188 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3189 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003190 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003191 if (inputDesc == NULL) {
3192 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3193 return BAD_VALUE;
3194 }
3195 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003196 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003197 true,
3198 NULL);
3199 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003200 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3201 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3202 status, patchDesc->mAfPatchHandle);
3203 removeAudioPatch(patchDesc->mHandle);
3204 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003205 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003206 } else {
3207 return BAD_VALUE;
3208 }
3209 } else {
3210 return BAD_VALUE;
3211 }
3212 return NO_ERROR;
3213}
3214
3215status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3216 struct audio_patch *patches,
3217 unsigned int *generation)
3218{
François Gaffie53615e22015-03-19 09:24:12 +01003219 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003220 return BAD_VALUE;
3221 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003222 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003223 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003224}
3225
Eric Laurente1715a42014-05-20 11:30:42 -07003226status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003227{
Eric Laurente1715a42014-05-20 11:30:42 -07003228 ALOGV("setAudioPortConfig()");
3229
3230 if (config == NULL) {
3231 return BAD_VALUE;
3232 }
3233 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3234 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003235 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3236 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003237 }
3238
Eric Laurenta121f902014-06-03 13:32:54 -07003239 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003240 if (config->type == AUDIO_PORT_TYPE_MIX) {
3241 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003242 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003243 if (outputDesc == NULL) {
3244 return BAD_VALUE;
3245 }
Eric Laurent84c70242014-06-23 08:46:27 -07003246 ALOG_ASSERT(!outputDesc->isDuplicated(),
3247 "setAudioPortConfig() called on duplicated output %d",
3248 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003249 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003250 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003251 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003252 if (inputDesc == NULL) {
3253 return BAD_VALUE;
3254 }
Eric Laurenta121f902014-06-03 13:32:54 -07003255 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003256 } else {
3257 return BAD_VALUE;
3258 }
3259 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3260 sp<DeviceDescriptor> deviceDesc;
3261 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3262 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3263 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3264 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3265 } else {
3266 return BAD_VALUE;
3267 }
3268 if (deviceDesc == NULL) {
3269 return BAD_VALUE;
3270 }
Eric Laurenta121f902014-06-03 13:32:54 -07003271 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003272 } else {
3273 return BAD_VALUE;
3274 }
3275
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003276 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003277 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3278 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003279 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003280 audioPortConfig->toAudioPortConfig(&newConfig, config);
3281 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003282 }
Eric Laurenta121f902014-06-03 13:32:54 -07003283 if (status != NO_ERROR) {
3284 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003285 }
Eric Laurente1715a42014-05-20 11:30:42 -07003286
3287 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003288}
3289
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003290void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3291{
Eric Laurentd60560a2015-04-10 11:31:20 -07003292 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003293 clearAudioPatches(uid);
3294 clearSessionRoutes(uid);
3295}
3296
Eric Laurent6a94d692014-05-20 11:18:06 -07003297void AudioPolicyManager::clearAudioPatches(uid_t uid)
3298{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003299 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003300 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3301 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003302 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003303 }
3304 }
3305}
3306
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003307void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3308 audio_io_handle_t ouptutToSkip)
3309{
3310 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3311 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3312 for (size_t j = 0; j < mOutputs.size(); j++) {
3313 if (mOutputs.keyAt(j) == ouptutToSkip) {
3314 continue;
3315 }
3316 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3317 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3318 continue;
3319 }
3320 // If the default device for this strategy is on another output mix,
3321 // invalidate all tracks in this strategy to force re connection.
3322 // Otherwise select new device on the output mix.
3323 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003324 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003325 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3326 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3327 }
3328 }
3329 } else {
3330 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3331 setOutputDevice(outputDesc, newDevice, false);
3332 }
3333 }
3334}
3335
3336void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3337{
3338 // remove output routes associated with this uid
3339 SortedVector<routing_strategy> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07003340 for (size_t i = 0; i < mOutputs.size(); i++) {
3341 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003342 for (const auto& client : outputDesc->getClientIterable()) {
3343 if (client->hasPreferredDevice() && client->uid() == uid) {
3344 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3345 affectedStrategies.add(getStrategy(client->stream()));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003346 }
3347 }
3348 }
3349 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003350 for (const auto& strategy : affectedStrategies) {
3351 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003352 }
3353
3354 // remove input routes associated with this uid
3355 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07003356 for (size_t i = 0; i < mInputs.size(); i++) {
3357 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003358 for (const auto& client : inputDesc->getClientIterable()) {
3359 if (client->hasPreferredDevice() && client->uid() == uid) {
3360 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3361 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003362 }
3363 }
3364 }
3365 // reroute inputs if necessary
3366 SortedVector<audio_io_handle_t> inputsToClose;
3367 for (size_t i = 0; i < mInputs.size(); i++) {
3368 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003369 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003370 inputsToClose.add(inputDesc->mIoHandle);
3371 }
3372 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003373 for (const auto& input : inputsToClose) {
3374 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003375 }
3376}
3377
Eric Laurentd60560a2015-04-10 11:31:20 -07003378void AudioPolicyManager::clearAudioSources(uid_t uid)
3379{
3380 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003381 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3382 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07003383 stopAudioSource(mAudioSources.keyAt(i));
3384 }
3385 }
3386}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003387
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003388status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3389 audio_io_handle_t *ioHandle,
3390 audio_devices_t *device)
3391{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003392 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3393 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003394 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003395
François Gaffiedf372692015-03-19 10:43:27 +01003396 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003397}
3398
Eric Laurentd60560a2015-04-10 11:31:20 -07003399status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003400 const audio_attributes_t *attributes,
3401 audio_port_handle_t *portId,
3402 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003403{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003404 ALOGV("%s", __FUNCTION__);
3405 *portId = AUDIO_PORT_HANDLE_NONE;
3406
3407 if (source == NULL || attributes == NULL || portId == NULL) {
3408 ALOGW("%s invalid argument: source %p attributes %p handle %p",
3409 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003410 return BAD_VALUE;
3411 }
3412
Eric Laurentd60560a2015-04-10 11:31:20 -07003413 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3414 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003415 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
3416 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003417 return INVALID_OPERATION;
3418 }
3419
3420 sp<DeviceDescriptor> srcDeviceDesc =
3421 mAvailableInputDevices.getDevice(source->ext.device.type,
3422 String8(source->ext.device.address));
3423 if (srcDeviceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003424 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003425 return BAD_VALUE;
3426 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003427
3428 *portId = AudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07003429
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003430 struct audio_patch dummyPatch = {};
Eric Laurentd60560a2015-04-10 11:31:20 -07003431 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003432
3433 sp<SourceClientDescriptor> sourceDesc =
3434 new SourceClientDescriptor(*portId, uid, *attributes, patchDesc, srcDeviceDesc,
Eric Laurent97ac8712018-07-27 18:59:02 -07003435 streamTypefromAttributesInt(attributes),
3436 getStrategyForAttr(attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07003437
3438 status_t status = connectAudioSource(sourceDesc);
3439 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003440 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003441 }
3442 return status;
3443}
3444
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003445status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003446{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003447 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003448
3449 // make sure we only have one patch per source.
3450 disconnectAudioSource(sourceDesc);
3451
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003452 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003453 routing_strategy strategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003454 audio_stream_type_t stream = sourceDesc->stream();
3455 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->srcDevice();
Eric Laurentd60560a2015-04-10 11:31:20 -07003456
3457 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3458 sp<DeviceDescriptor> sinkDeviceDesc =
3459 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3460
3461 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003462
3463 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3464 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003465 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003466 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3467 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3468 // create patch between src device and output device
3469 // create Hwoutput and add to mHwOutputs
3470 } else {
3471 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
jiabin40573322018-11-08 12:08:02 -08003472 audio_io_handle_t output = selectOutput(outputs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003473 if (output == AUDIO_IO_HANDLE_NONE) {
3474 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3475 return INVALID_OPERATION;
3476 }
3477 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3478 if (outputDesc->isDuplicated()) {
3479 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3480 return INVALID_OPERATION;
3481 }
Eric Laurent733ce942017-12-07 12:18:25 -08003482 status_t status = outputDesc->start();
3483 if (status != NO_ERROR) {
3484 return status;
3485 }
3486
Eric Laurentd60560a2015-04-10 11:31:20 -07003487 // create a special patch with no sink and two sources:
3488 // - the second source indicates to PatchPanel through which output mix this patch should
3489 // be connected as well as the stream type for volume control
3490 // - the sink is defined by whatever output device is currently selected for the output
3491 // though which this patch is routed.
Mikhail Naganovdc769682018-05-04 15:34:08 -07003492 PatchBuilder patchBuilder;
3493 patchBuilder.addSource(srcDeviceDesc).addSource(outputDesc, { .stream = stream });
3494 status = mpClientInterface->createAudioPatch(patchBuilder.patch(),
Eric Laurentd60560a2015-04-10 11:31:20 -07003495 &afPatchHandle,
3496 0);
3497 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3498 status, afPatchHandle);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003499 sourceDesc->patchDesc()->mPatch = *patchBuilder.patch();
Eric Laurentd60560a2015-04-10 11:31:20 -07003500 if (status != NO_ERROR) {
3501 ALOGW("%s patch panel could not connect device patch, error %d",
3502 __FUNCTION__, status);
3503 return INVALID_OPERATION;
3504 }
3505 uint32_t delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07003506 status = startSource(outputDesc, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003507
3508 if (status != NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003509 mpClientInterface->releaseAudioPatch(sourceDesc->patchDesc()->mAfPatchHandle, 0);
Eric Laurentd60560a2015-04-10 11:31:20 -07003510 return status;
3511 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003512 sourceDesc->setSwOutput(outputDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003513 if (delayMs != 0) {
3514 usleep(delayMs * 1000);
3515 }
3516 }
3517
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003518 sourceDesc->patchDesc()->mAfPatchHandle = afPatchHandle;
3519 addAudioPatch(sourceDesc->patchDesc()->mHandle, sourceDesc->patchDesc());
Eric Laurentd60560a2015-04-10 11:31:20 -07003520
3521 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003522}
3523
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003524status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07003525{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003526 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
3527 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003528 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003529 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003530 return BAD_VALUE;
3531 }
3532 status_t status = disconnectAudioSource(sourceDesc);
3533
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003534 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003535 return status;
3536}
3537
Andy Hung2ddee192015-12-18 17:34:44 -08003538status_t AudioPolicyManager::setMasterMono(bool mono)
3539{
3540 if (mMasterMono == mono) {
3541 return NO_ERROR;
3542 }
3543 mMasterMono = mono;
3544 // if enabling mono we close all offloaded devices, which will invalidate the
3545 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3546 // for recreating the new AudioTrack as non-offloaded PCM.
3547 //
3548 // If disabling mono, we leave all tracks as is: we don't know which clients
3549 // and tracks are able to be recreated as offloaded. The next "song" should
3550 // play back offloaded.
3551 if (mMasterMono) {
3552 Vector<audio_io_handle_t> offloaded;
3553 for (size_t i = 0; i < mOutputs.size(); ++i) {
3554 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3555 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3556 offloaded.push(desc->mIoHandle);
3557 }
3558 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003559 for (const auto& handle : offloaded) {
3560 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003561 }
3562 }
3563 // update master mono for all remaining outputs
3564 for (size_t i = 0; i < mOutputs.size(); ++i) {
3565 updateMono(mOutputs.keyAt(i));
3566 }
3567 return NO_ERROR;
3568}
3569
3570status_t AudioPolicyManager::getMasterMono(bool *mono)
3571{
3572 *mono = mMasterMono;
3573 return NO_ERROR;
3574}
3575
Eric Laurentac9cef52017-06-09 15:46:26 -07003576float AudioPolicyManager::getStreamVolumeDB(
3577 audio_stream_type_t stream, int index, audio_devices_t device)
3578{
3579 return computeVolume(stream, index, device);
3580}
3581
jiabin81772902018-04-02 17:52:27 -07003582status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3583 audio_format_t *surroundFormats,
3584 bool *surroundFormatsEnabled,
3585 bool reported)
3586{
3587 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3588 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3589 return BAD_VALUE;
3590 }
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003591 ALOGV("getSurroundFormats() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p"
3592 " reported %d", *numSurroundFormats, surroundFormats, surroundFormatsEnabled, reported);
jiabin81772902018-04-02 17:52:27 -07003593
3594 // Only return value if there is HDMI output.
3595 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3596 return INVALID_OPERATION;
3597 }
3598
3599 size_t formatsWritten = 0;
3600 size_t formatsMax = *numSurroundFormats;
3601 *numSurroundFormats = 0;
Mikhail Naganov2563f232018-09-27 14:48:01 -07003602 std::unordered_set<audio_format_t> formats;
jiabin81772902018-04-02 17:52:27 -07003603 if (reported) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003604 // Return formats from HDMI profiles, that have already been resolved by
3605 // checkOutputsForDevice().
3606 DeviceVector hdmiOutputDevs = mAvailableOutputDevices.getDevicesFromTypeMask(
3607 AUDIO_DEVICE_OUT_HDMI);
3608 for (size_t i = 0; i < hdmiOutputDevs.size(); i++) {
3609 FormatVector supportedFormats =
3610 hdmiOutputDevs[i]->getAudioPort()->getAudioProfiles().getSupportedFormats();
3611 for (size_t j = 0; j < supportedFormats.size(); j++) {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003612 if (mConfig.getSurroundFormats().count(supportedFormats[j]) != 0) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003613 formats.insert(supportedFormats[j]);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003614 } else {
3615 for (const auto& pair : mConfig.getSurroundFormats()) {
3616 if (pair.second.count(supportedFormats[j]) != 0) {
3617 formats.insert(pair.first);
3618 break;
3619 }
3620 }
Mikhail Naganov2563f232018-09-27 14:48:01 -07003621 }
3622 }
jiabin81772902018-04-02 17:52:27 -07003623 }
3624 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003625 for (const auto& pair : mConfig.getSurroundFormats()) {
3626 formats.insert(pair.first);
jiabin81772902018-04-02 17:52:27 -07003627 }
3628 }
Mikhail Naganov2563f232018-09-27 14:48:01 -07003629 for (const auto& format: formats) {
jiabin81772902018-04-02 17:52:27 -07003630 if (formatsWritten < formatsMax) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003631 surroundFormats[formatsWritten] = format;
jiabin81772902018-04-02 17:52:27 -07003632 bool formatEnabled = false;
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003633 if (mConfig.getSurroundFormats().count(format) == 0) {
3634 // Check sub-formats
3635 for (const auto& pair : mConfig.getSurroundFormats()) {
3636 for (const auto& subformat : pair.second) {
3637 formatEnabled = mSurroundFormats.count(subformat) != 0;
3638 if (formatEnabled) break;
3639 }
3640 if (formatEnabled) break;
jiabin81772902018-04-02 17:52:27 -07003641 }
3642 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003643 formatEnabled = mSurroundFormats.count(format) != 0;
jiabin81772902018-04-02 17:52:27 -07003644 }
3645 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3646 }
3647 (*numSurroundFormats)++;
3648 }
3649 return NO_ERROR;
3650}
3651
3652status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3653{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003654 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
jiabin81772902018-04-02 17:52:27 -07003655 // Check if audio format is a surround formats.
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003656 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
3657 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003658 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07003659 return BAD_VALUE;
3660 }
3661
3662 // Should only be called when MANUAL.
3663 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3664 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
3665 if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003666 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07003667 return INVALID_OPERATION;
3668 }
3669
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003670 if ((mSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07003671 return NO_ERROR;
3672 }
3673
3674 // The operation is valid only when there is HDMI output available.
3675 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003676 ALOGW("%s() no HDMI out devices found", __func__);
jiabin81772902018-04-02 17:52:27 -07003677 return INVALID_OPERATION;
3678 }
3679
Mikhail Naganov2563f232018-09-27 14:48:01 -07003680 std::unordered_set<audio_format_t> surroundFormatsBackup(mSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07003681 if (enabled) {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003682 mSurroundFormats.insert(audioFormat);
3683 for (const auto& subFormat : formatIter->second) {
3684 mSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07003685 }
3686 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003687 mSurroundFormats.erase(audioFormat);
3688 for (const auto& subFormat : formatIter->second) {
3689 mSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07003690 }
3691 }
3692
3693 sp<SwAudioOutputDescriptor> outputDesc;
3694 bool profileUpdated = false;
Mikhail Naganov708e0382018-05-30 09:53:04 -07003695 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003696 AUDIO_DEVICE_OUT_HDMI);
3697 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3698 // Simulate reconnection to update enabled surround sound formats.
3699 String8 address = hdmiOutputDevices[i]->mAddress;
3700 String8 name = hdmiOutputDevices[i]->getName();
3701 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3702 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3703 address.c_str(),
3704 name.c_str());
3705 if (status != NO_ERROR) {
3706 continue;
3707 }
3708 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3709 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3710 address.c_str(),
3711 name.c_str());
3712 profileUpdated |= (status == NO_ERROR);
3713 }
Mikhail Naganov708e0382018-05-30 09:53:04 -07003714 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003715 AUDIO_DEVICE_IN_HDMI);
3716 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3717 // Simulate reconnection to update enabled surround sound formats.
3718 String8 address = hdmiInputDevices[i]->mAddress;
3719 String8 name = hdmiInputDevices[i]->getName();
3720 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3721 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3722 address.c_str(),
3723 name.c_str());
3724 if (status != NO_ERROR) {
3725 continue;
3726 }
3727 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3728 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3729 address.c_str(),
3730 name.c_str());
3731 profileUpdated |= (status == NO_ERROR);
3732 }
3733
jiabin81772902018-04-02 17:52:27 -07003734 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003735 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov2563f232018-09-27 14:48:01 -07003736 mSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07003737 }
3738
3739 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3740}
3741
Eric Laurentf32108e2018-10-04 17:22:04 -07003742void AudioPolicyManager::setAppState(uid_t uid, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003743{
Eric Laurentf32108e2018-10-04 17:22:04 -07003744 Vector<sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
3745 bool silenced = state == APP_STATE_IDLE;
3746
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003747 ALOGV("AudioPolicyManager:setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
3748
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003749 for (size_t i = 0; i < activeInputs.size(); i++) {
3750 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
Eric Laurent8f42ea12018-08-08 09:08:25 -07003751 RecordClientVector clients = activeDesc->clientsList(true /*activeOnly*/);
3752 for (const auto& client : clients) {
3753 if (uid == client->uid()) {
3754 client->setSilenced(silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003755 }
3756 }
3757 }
3758}
3759
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003760status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003761{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003762 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003763
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003764 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003765 if (patchDesc == 0) {
3766 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003767 sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003768 return BAD_VALUE;
3769 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003770 removeAudioPatch(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003771
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003772 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003773 if (swOutputDesc != 0) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003774 status_t status = stopSource(swOutputDesc, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08003775 if (status == NO_ERROR) {
3776 swOutputDesc->stop();
3777 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003778 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3779 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003780 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003781 if (hwOutputDesc != 0) {
3782 // release patch between src device and output device
3783 // close Hwoutput and remove from mHwOutputs
3784 } else {
3785 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3786 }
3787 }
3788 return NO_ERROR;
3789}
3790
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003791sp<SourceClientDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
Eric Laurentd60560a2015-04-10 11:31:20 -07003792 audio_io_handle_t output, routing_strategy strategy)
3793{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003794 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07003795 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003796 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3797 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003798 routing_strategy sourceStrategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003799 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003800 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3801 source = sourceDesc;
3802 break;
3803 }
3804 }
3805 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003806}
3807
Eric Laurente552edb2014-03-10 17:42:56 -07003808// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003809// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003810// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003811uint32_t AudioPolicyManager::nextAudioPortGeneration()
3812{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003813 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003814}
3815
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003816// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3817static const char *kConfigLocationList[] =
3818 {"/odm/etc", "/vendor/etc", "/system/etc"};
3819static const int kConfigLocationListSize =
3820 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3821
3822static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3823 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07003824 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003825 status_t ret;
3826
Petri Gyntherf497f292018-04-17 18:46:10 -07003827 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
3828 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
3829 // A2DP offload supported but disabled: try to use special XML file
3830 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
3831 }
3832 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3833
3834 for (const char* fileName : fileNames) {
3835 for (int i = 0; i < kConfigLocationListSize; i++) {
Petri Gyntherf497f292018-04-17 18:46:10 -07003836 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
3837 "%s/%s", kConfigLocationList[i], fileName);
Mikhail Naganova289aea2018-09-17 15:26:23 -07003838 ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile, &config);
Petri Gyntherf497f292018-04-17 18:46:10 -07003839 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003840 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07003841 return ret;
3842 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003843 }
3844 }
3845 return ret;
3846}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003847
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003848AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
3849 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07003850 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07003851 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003852 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07003853 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003854 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003855 mVolumeCurves(new VolumeCurvesCollection()),
3856 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08003857 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003858 mAudioPortGeneration(1),
3859 mBeaconMuteRefCount(0),
3860 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003861 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003862 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003863 mMasterMono(false),
Chris Thornton2b864642017-06-27 21:26:07 -07003864 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE),
3865 mHasComputedSoundTriggerSupportsConcurrentCapture(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003866{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003867}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003868
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003869AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
3870 : AudioPolicyManager(clientInterface, false /*forTesting*/)
3871{
3872 loadConfig();
3873 initialize();
3874}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003875
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07003876// This check is to catch any legacy platform updating to Q without having
3877// switched to XML since its deprecation on O.
3878// TODO: after Q release, remove this check and flag as XML is now the only
3879// option and all legacy platform should have transitioned to XML.
3880#ifndef USE_XML_AUDIO_POLICY_CONF
3881#error Audio policy no longer supports legacy .conf configuration format
François Gaffied1ab2bd2015-12-02 18:20:06 +01003882#endif
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07003883
3884void AudioPolicyManager::loadConfig() {
3885 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003886 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003887 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01003888 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003889}
3890
3891status_t AudioPolicyManager::initialize() {
3892 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01003893
3894 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003895 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3896 if (!engineInstance) {
3897 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003898 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003899 }
3900 // Retrieve the Policy Manager Interface
3901 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3902 if (mEngine == NULL) {
3903 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003904 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003905 }
3906 mEngine->setObserver(this);
3907 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003908 if (status != NO_ERROR) {
3909 LOG_FATAL("Policy engine not initialized(err=%d)", status);
3910 return status;
3911 }
François Gaffie2110e042015-03-24 08:41:51 +01003912
Eric Laurent3a4311c2014-03-17 12:00:47 -07003913 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003914 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003915 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3916 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Mikhail Naganovd4120142017-12-06 15:49:22 -08003917 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003918 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08003919 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
3920 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003921 continue;
3922 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08003923 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07003924 // open all output streams needed to access attached devices
3925 // except for direct output streams that are only opened when they are actually
3926 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003927 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003928 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003929 if (!outProfile->canOpenNewIo()) {
3930 ALOGE("Invalid Output profile max open count %u for profile %s",
3931 outProfile->maxOpenCount, outProfile->getTagName().c_str());
3932 continue;
3933 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003934 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003935 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003936 continue;
3937 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003938 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003939 mTtsOutputAvailable = true;
3940 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003941
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003942 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003943 continue;
3944 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003945 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003946 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3947 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003948 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003949 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003950 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003951 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003952 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003953 if ((profileType & outputDeviceTypes) == 0) {
3954 continue;
3955 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003956 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3957 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003958 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov708e0382018-05-30 09:53:04 -07003959 const DeviceVector &devicesForType = supportedDevices.getDevicesFromTypeMask(
3960 profileType);
Eric Laurentc40d9692016-04-13 19:14:13 -07003961 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3962 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003963 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08003964 status_t status = outputDesc->open(nullptr, profileType, address,
3965 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07003966
3967 if (status != NO_ERROR) {
3968 ALOGW("Cannot open output stream for device %08x on hw module %s",
3969 outputDesc->mDevice,
Mikhail Naganovd4120142017-12-06 15:49:22 -08003970 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003971 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003972 for (const auto& dev : supportedDevices) {
3973 ssize_t index = mAvailableOutputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07003974 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003975 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003976 mAvailableOutputDevices[index]->attach(hwModule);
Eric Laurentd78f1532014-09-16 16:38:20 -07003977 }
3978 }
3979 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003980 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003981 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003982 }
3983 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003984 setOutputDevice(outputDesc,
Eric Laurentfe231122017-11-17 17:48:06 -08003985 profileType,
Eric Laurentc40d9692016-04-13 19:14:13 -07003986 true,
3987 0,
3988 NULL,
Eric Laurentfe231122017-11-17 17:48:06 -08003989 address);
Eric Laurentd78f1532014-09-16 16:38:20 -07003990 }
Eric Laurente552edb2014-03-10 17:42:56 -07003991 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003992 // open input streams needed to access attached devices to validate
3993 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003994 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003995 if (!inProfile->canOpenNewIo()) {
3996 ALOGE("Invalid Input profile max open count %u for profile %s",
3997 inProfile->maxOpenCount, inProfile->getTagName().c_str());
3998 continue;
3999 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004000 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004001 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004002 continue;
4003 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004004 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07004005 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004006 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
4007
Eric Laurentd78f1532014-09-16 16:38:20 -07004008 if ((profileType & inputDeviceTypes) == 0) {
4009 continue;
4010 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08004011 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08004012 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004013
Mikhail Naganov708e0382018-05-30 09:53:04 -07004014 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(profileType);
Eric Laurent53b810e2017-12-10 17:25:10 -08004015 // the inputs vector must be of size >= 1, but we don't want to crash here
4016 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
4017 : String8("");
4018 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
4019 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
4020
Eric Laurentd78f1532014-09-16 16:38:20 -07004021 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004022 status_t status = inputDesc->open(nullptr,
4023 profileType,
Eric Laurent53b810e2017-12-10 17:25:10 -08004024 address,
Eric Laurentfe231122017-11-17 17:48:06 -08004025 AUDIO_SOURCE_MIC,
4026 AUDIO_INPUT_FLAG_NONE,
4027 &input);
Eric Laurentd78f1532014-09-16 16:38:20 -07004028
4029 if (status == NO_ERROR) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004030 for (const auto& dev : inProfile->getSupportedDevices()) {
4031 ssize_t index = mAvailableInputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07004032 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07004033 if (index >= 0) {
4034 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
4035 if (!devDesc->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004036 devDesc->attach(hwModule);
Eric Laurent83efe1c2017-07-09 16:51:08 -07004037 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07004038 }
Eric Laurentd78f1532014-09-16 16:38:20 -07004039 }
4040 }
Eric Laurentfe231122017-11-17 17:48:06 -08004041 inputDesc->close();
Eric Laurentd78f1532014-09-16 16:38:20 -07004042 } else {
4043 ALOGW("Cannot open input stream for device %08x on hw module %s",
Eric Laurentfe231122017-11-17 17:48:06 -08004044 profileType,
Mikhail Naganovd4120142017-12-06 15:49:22 -08004045 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07004046 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004047 }
4048 }
4049 // make sure all attached devices have been allocated a unique ID
4050 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004051 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004052 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004053 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
4054 continue;
4055 }
François Gaffie2110e042015-03-24 08:41:51 +01004056 // The device is now validated and can be appended to the available devices of the engine
4057 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
4058 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004059 i++;
4060 }
4061 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004062 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01004063 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004064 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
4065 continue;
4066 }
François Gaffie2110e042015-03-24 08:41:51 +01004067 // The device is now validated and can be appended to the available devices of the engine
4068 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
4069 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004070 i++;
4071 }
4072 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004073 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01004074 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004075 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004076 }
jiabin9ff780e2018-03-19 18:19:52 -07004077 // If microphones address is empty, set it according to device type
4078 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
4079 if (mAvailableInputDevices[i]->mAddress.isEmpty()) {
4080 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
4081 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
4082 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
4083 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BACK_MICROPHONE_ADDRESS);
4084 }
4085 }
4086 }
Eric Laurente552edb2014-03-10 17:42:56 -07004087
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004088 if (mPrimaryOutput == 0) {
4089 ALOGE("Failed to open primary output");
4090 status = NO_INIT;
4091 }
Eric Laurente552edb2014-03-10 17:42:56 -07004092
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09004093 // Silence ALOGV statements
4094 property_set("log.tag." LOG_TAG, "D");
4095
Eric Laurente552edb2014-03-10 17:42:56 -07004096 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004097 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004098}
4099
Eric Laurente0720872014-03-11 09:30:41 -07004100AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004101{
Eric Laurente552edb2014-03-10 17:42:56 -07004102 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004103 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004104 }
4105 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004106 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004107 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004108 mAvailableOutputDevices.clear();
4109 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004110 mOutputs.clear();
4111 mInputs.clear();
4112 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004113 mHwModulesAll.clear();
jiabin81772902018-04-02 17:52:27 -07004114 mSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004115}
4116
Eric Laurente0720872014-03-11 09:30:41 -07004117status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004118{
Eric Laurent87ffa392015-05-22 10:32:38 -07004119 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004120}
4121
Eric Laurente552edb2014-03-10 17:42:56 -07004122// ---
4123
Eric Laurent98e38192018-02-15 18:31:53 -08004124void AudioPolicyManager::addOutput(audio_io_handle_t output,
4125 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004126{
Eric Laurent1c333e22014-05-20 10:48:17 -07004127 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08004128 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004129 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004130 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004131 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004132}
4133
François Gaffie53615e22015-03-19 09:24:12 +01004134void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4135{
4136 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004137 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004138}
4139
Eric Laurent98e38192018-02-15 18:31:53 -08004140void AudioPolicyManager::addInput(audio_io_handle_t input,
4141 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004142{
Eric Laurent1c333e22014-05-20 10:48:17 -07004143 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004144 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004145}
Eric Laurente552edb2014-03-10 17:42:56 -07004146
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004147void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08004148 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004149 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004150 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08004151 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004152 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08004153 if (devDesc != 0) {
4154 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
4155 desc->mIoHandle, address.string());
4156 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004157 }
4158}
4159
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004160status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004161 audio_policy_dev_state_t state,
4162 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004163 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07004164{
François Gaffie53615e22015-03-19 09:24:12 +01004165 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07004166 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004167
4168 if (audio_device_is_digital(device)) {
4169 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004170 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004171 }
Eric Laurente552edb2014-03-10 17:42:56 -07004172
Eric Laurent3b73df72014-03-11 09:06:29 -07004173 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004174 // first list already open outputs that can be routed to this device
4175 for (size_t i = 0; i < mOutputs.size(); i++) {
4176 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07004177 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004178 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004179 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
4180 outputs.add(mOutputs.keyAt(i));
4181 } else {
4182 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08004183 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004184 }
Eric Laurente552edb2014-03-10 17:42:56 -07004185 }
4186 }
4187 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004188 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004189 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004190 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4191 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004192 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004193 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004194 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004195 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004196 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4197 j, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004198 }
Eric Laurente552edb2014-03-10 17:42:56 -07004199 }
4200 }
4201 }
4202
Eric Laurent7b279bb2015-12-14 10:18:23 -08004203 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004204
Eric Laurente552edb2014-03-10 17:42:56 -07004205 if (profiles.isEmpty() && outputs.isEmpty()) {
4206 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4207 return BAD_VALUE;
4208 }
4209
4210 // open outputs for matching profiles if needed. Direct outputs are also opened to
4211 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4212 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004213 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004214
4215 // nothing to do if one output is already opened for this profile
4216 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004217 for (j = 0; j < outputs.size(); j++) {
4218 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004219 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004220 // matching profile: save the sample rates, format and channel masks supported
4221 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07004222 if (audio_device_is_digital(device)) {
4223 devDesc->importAudioPort(profile);
4224 }
Eric Laurente552edb2014-03-10 17:42:56 -07004225 break;
4226 }
4227 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004228 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004229 continue;
4230 }
4231
Eric Laurent3974e3b2017-12-07 17:58:43 -08004232 if (!profile->canOpenNewIo()) {
4233 ALOGW("Max Output number %u already opened for this profile %s",
4234 profile->maxOpenCount, profile->getTagName().c_str());
4235 continue;
4236 }
4237
Eric Laurent83efe1c2017-07-09 16:51:08 -07004238 ALOGV("opening output for device %08x with params %s profile %p name %s",
4239 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004240 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004241 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004242 status_t status = desc->open(nullptr, device, address,
4243 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004244
Eric Laurentfe231122017-11-17 17:48:06 -08004245 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004246 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004247 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004248 char *param = audio_device_address_to_parameter(device, address);
4249 mpClientInterface->setParameters(output, String8(param));
4250 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004251 }
Phil Burk00eeb322016-03-31 12:41:00 -07004252 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004253 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004254 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004255 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004256 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004257 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004258 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004259 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004260 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4261 profile->pickAudioProfile(
4262 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004263 config.offload_info.sample_rate = config.sample_rate;
4264 config.offload_info.channel_mask = config.channel_mask;
4265 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004266
4267 status_t status = desc->open(&config, device, address, AUDIO_STREAM_DEFAULT,
4268 AUDIO_OUTPUT_FLAG_NONE, &output);
4269 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004270 output = AUDIO_IO_HANDLE_NONE;
4271 }
Eric Laurentd4692962014-05-05 18:13:44 -07004272 }
4273
Eric Laurentcf2c0212014-07-25 16:20:43 -07004274 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004275 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01004276 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004277 sp<AudioPolicyMix> policyMix;
4278 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004279 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
4280 address.string());
4281 }
François Gaffie036e1e92015-03-19 10:16:24 +01004282 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07004283 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01004284
Eric Laurent87ffa392015-05-22 10:32:38 -07004285 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4286 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004287 // no duplicated output for direct outputs and
4288 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004289 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004290
Eric Laurentd4692962014-05-05 18:13:44 -07004291 //TODO: configure audio effect output stage here
4292
4293 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004294 sp<SwAudioOutputDescriptor> dupOutputDesc =
4295 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4296 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4297 &duplicatedOutput);
4298 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004299 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004300 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004301 } else {
4302 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004303 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004304 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004305 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004306 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004307 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004308 }
Eric Laurente552edb2014-03-10 17:42:56 -07004309 }
4310 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004311 } else {
4312 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004313 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004314 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004315 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004316 profiles.removeAt(profile_index);
4317 profile_index--;
4318 } else {
4319 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004320 // Load digital format info only for digital devices
4321 if (audio_device_is_digital(device)) {
4322 devDesc->importAudioPort(profile);
4323 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004324
François Gaffie53615e22015-03-19 09:24:12 +01004325 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004326 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4327 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004328 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004329 NULL/*patch handle*/, address.string());
4330 }
Eric Laurente552edb2014-03-10 17:42:56 -07004331 ALOGV("checkOutputsForDevice(): adding output %d", output);
4332 }
4333 }
4334
4335 if (profiles.isEmpty()) {
4336 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4337 return BAD_VALUE;
4338 }
Eric Laurentd4692962014-05-05 18:13:44 -07004339 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004340 // check if one opened output is not needed any more after disconnecting one device
4341 for (size_t i = 0; i < mOutputs.size(); i++) {
4342 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004343 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004344 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004345 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004346 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004347 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004348 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004349 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4350 mOutputs.keyAt(i));
4351 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004352 }
Eric Laurente552edb2014-03-10 17:42:56 -07004353 }
4354 }
Eric Laurentd4692962014-05-05 18:13:44 -07004355 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004356 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004357 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4358 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004359 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004360 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004361 "clearing direct output profile %zu on module %s",
4362 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004363 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004364 }
4365 }
4366 }
4367 }
4368 return NO_ERROR;
4369}
4370
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004371status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004372 audio_policy_dev_state_t state,
4373 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004374 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004375{
Paul McLean9080a4c2015-06-18 08:24:02 -07004376 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004377 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004378
4379 if (audio_device_is_digital(device)) {
4380 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004381 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004382 }
4383
Eric Laurentd4692962014-05-05 18:13:44 -07004384 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4385 // first list already open inputs that can be routed to this device
4386 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4387 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004388 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004389 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4390 inputs.add(mInputs.keyAt(input_index));
4391 }
4392 }
4393
4394 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004395 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004396 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004397 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004398 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004399 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004400 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004401
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004402 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004403 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004404 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004405 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004406 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4407 profile_index, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004408 }
Eric Laurentd4692962014-05-05 18:13:44 -07004409 }
4410 }
4411 }
4412
4413 if (profiles.isEmpty() && inputs.isEmpty()) {
4414 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4415 return BAD_VALUE;
4416 }
4417
4418 // open inputs for matching profiles if needed. Direct inputs are also opened to
4419 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4420 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4421
Eric Laurent1c333e22014-05-20 10:48:17 -07004422 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004423
Eric Laurentd4692962014-05-05 18:13:44 -07004424 // nothing to do if one input is already opened for this profile
4425 size_t input_index;
4426 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4427 desc = mInputs.valueAt(input_index);
4428 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004429 if (audio_device_is_digital(device)) {
4430 devDesc->importAudioPort(profile);
4431 }
Eric Laurentd4692962014-05-05 18:13:44 -07004432 break;
4433 }
4434 }
4435 if (input_index != mInputs.size()) {
4436 continue;
4437 }
4438
Eric Laurent3974e3b2017-12-07 17:58:43 -08004439 if (!profile->canOpenNewIo()) {
4440 ALOGW("Max Input number %u already opened for this profile %s",
4441 profile->maxOpenCount, profile->getTagName().c_str());
4442 continue;
4443 }
4444
Eric Laurentfe231122017-11-17 17:48:06 -08004445 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004446 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004447 status_t status = desc->open(nullptr,
4448 device,
4449 address,
4450 AUDIO_SOURCE_MIC,
4451 AUDIO_INPUT_FLAG_NONE,
4452 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004453
Eric Laurentcf2c0212014-07-25 16:20:43 -07004454 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004455 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004456 char *param = audio_device_address_to_parameter(device, address);
4457 mpClientInterface->setParameters(input, String8(param));
4458 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004459 }
Phil Burk00eeb322016-03-31 12:41:00 -07004460 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004461 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004462 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004463 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004464 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004465 }
4466
4467 if (input != 0) {
4468 addInput(input, desc);
4469 }
4470 } // endif input != 0
4471
Eric Laurentcf2c0212014-07-25 16:20:43 -07004472 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004473 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004474 profiles.removeAt(profile_index);
4475 profile_index--;
4476 } else {
4477 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004478 if (audio_device_is_digital(device)) {
4479 devDesc->importAudioPort(profile);
4480 }
Eric Laurentd4692962014-05-05 18:13:44 -07004481 ALOGV("checkInputsForDevice(): adding input %d", input);
4482 }
4483 } // end scan profiles
4484
4485 if (profiles.isEmpty()) {
4486 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4487 return BAD_VALUE;
4488 }
4489 } else {
4490 // Disconnect
4491 // check if one opened input is not needed any more after disconnecting one device
4492 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4493 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004494 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004495 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4496 mInputs.keyAt(input_index));
4497 inputs.add(mInputs.keyAt(input_index));
4498 }
4499 }
4500 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004501 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004502 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004503 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004504 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004505 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004506 if (profile->supportDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004507 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4508 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004509 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004510 }
4511 }
4512 }
4513 } // end disconnect
4514
4515 return NO_ERROR;
4516}
4517
4518
Eric Laurente0720872014-03-11 09:30:41 -07004519void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004520{
4521 ALOGV("closeOutput(%d)", output);
4522
Eric Laurentc75307b2015-03-17 15:29:32 -07004523 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004524 if (outputDesc == NULL) {
4525 ALOGW("closeOutput() unknown output %d", output);
4526 return;
4527 }
François Gaffie036e1e92015-03-19 10:16:24 +01004528 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004529
Eric Laurente552edb2014-03-10 17:42:56 -07004530 // look for duplicated outputs connected to the output being removed.
4531 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004532 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004533 if (dupOutputDesc->isDuplicated() &&
4534 (dupOutputDesc->mOutput1 == outputDesc ||
4535 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004536 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004537 if (dupOutputDesc->mOutput1 == outputDesc) {
4538 outputDesc2 = dupOutputDesc->mOutput2;
4539 } else {
4540 outputDesc2 = dupOutputDesc->mOutput1;
4541 }
4542 // As all active tracks on duplicated output will be deleted,
4543 // and as they were also referenced on the other output, the reference
4544 // count for their stream type must be adjusted accordingly on
4545 // the other output.
Andy Hungaf036da2018-09-21 10:46:21 -07004546 const bool wasActive = outputDesc2->isActive();
4547 for (const auto &clientPair : dupOutputDesc->getActiveClients()) {
4548 outputDesc2->changeStreamActiveCount(clientPair.first, -clientPair.second);
Eric Laurente552edb2014-03-10 17:42:56 -07004549 }
Eric Laurent733ce942017-12-07 12:18:25 -08004550 // stop() will be a no op if the output is still active but is needed in case all
4551 // active streams refcounts where cleared above
4552 if (wasActive) {
4553 outputDesc2->stop();
4554 }
Eric Laurente552edb2014-03-10 17:42:56 -07004555 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4556 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4557
4558 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004559 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004560 }
4561 }
4562
Eric Laurent05b90f82014-08-27 15:32:29 -07004563 nextAudioPortGeneration();
4564
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004565 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004566 if (index >= 0) {
4567 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004568 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004569 mAudioPatches.removeItemsAt(index);
4570 mpClientInterface->onAudioPatchListUpdate();
4571 }
4572
Eric Laurentfe231122017-11-17 17:48:06 -08004573 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004574
François Gaffie53615e22015-03-19 09:24:12 +01004575 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004576 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10004577
4578 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
4579 // no direct outputs are open.
4580 if (getMsdAudioOutDeviceTypes() != AUDIO_DEVICE_NONE) {
4581 bool directOutputOpen = false;
4582 for (size_t i = 0; i < mOutputs.size(); i++) {
4583 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
4584 directOutputOpen = true;
4585 break;
4586 }
4587 }
4588 if (!directOutputOpen) {
4589 ALOGV("no direct outputs open, reset MSD patch");
4590 setMsdPatch();
4591 }
4592 }
Eric Laurent05b90f82014-08-27 15:32:29 -07004593}
4594
4595void AudioPolicyManager::closeInput(audio_io_handle_t input)
4596{
4597 ALOGV("closeInput(%d)", input);
4598
4599 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4600 if (inputDesc == NULL) {
4601 ALOGW("closeInput() unknown input %d", input);
4602 return;
4603 }
4604
Eric Laurent6a94d692014-05-20 11:18:06 -07004605 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004606
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004607 audio_devices_t device = inputDesc->mDevice;
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004608 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004609 if (index >= 0) {
4610 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004611 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004612 mAudioPatches.removeItemsAt(index);
4613 mpClientInterface->onAudioPatchListUpdate();
4614 }
4615
Eric Laurentfe231122017-11-17 17:48:06 -08004616 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004617 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004618
4619 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
4620 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
4621 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
4622 SoundTrigger::setCaptureState(false);
4623 }
Eric Laurente552edb2014-03-10 17:42:56 -07004624}
4625
Eric Laurentc75307b2015-03-17 15:29:32 -07004626SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4627 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004628 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004629{
4630 SortedVector<audio_io_handle_t> outputs;
4631
4632 ALOGVV("getOutputsForDevice() device %04x", device);
4633 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004634 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004635 i, openOutputs.valueAt(i)->isDuplicated(),
4636 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004637 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4638 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4639 outputs.add(openOutputs.keyAt(i));
4640 }
4641 }
4642 return outputs;
4643}
4644
Mikhail Naganov37977152018-07-11 15:54:44 -07004645void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
4646{
4647 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
4648 // output is suspended before any tracks are moved to it
4649 checkA2dpSuspend();
4650 checkOutputForAllStrategies();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004651 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07004652 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00004653 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004654 setMsdPatch();
4655 }
Mikhail Naganov37977152018-07-11 15:54:44 -07004656}
4657
Eric Laurente0720872014-03-11 09:30:41 -07004658void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004659{
4660 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4661 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4662 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4663 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4664
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004665 // also take into account external policy-related changes: add all outputs which are
4666 // associated with policies in the "before" and "after" output vectors
4667 ALOGVV("checkOutputForStrategy(): policy related outputs");
4668 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004669 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004670 if (desc != 0 && desc->mPolicyMix != NULL) {
4671 srcOutputs.add(desc->mIoHandle);
4672 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4673 }
4674 }
4675 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004676 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004677 if (desc != 0 && desc->mPolicyMix != NULL) {
4678 dstOutputs.add(desc->mIoHandle);
4679 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4680 }
4681 }
4682
Mikhail Naganov9de8bd12018-07-23 16:41:31 -07004683 if (srcOutputs != dstOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004684 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4685 // audio from invalidated tracks will be rendered when unmuting
4686 uint32_t maxLatency = 0;
4687 for (audio_io_handle_t srcOut : srcOutputs) {
4688 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4689 if (desc != 0 && maxLatency < desc->latency()) {
4690 maxLatency = desc->latency();
4691 }
4692 }
Eric Laurente552edb2014-03-10 17:42:56 -07004693 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4694 strategy, srcOutputs[0], dstOutputs[0]);
4695 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004696 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004697 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4698 if (desc != 0 && isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004699 setStrategyMute(strategy, true, desc);
Eric Laurentac3a6902018-05-11 16:39:10 -07004700 setStrategyMute(strategy, false, desc, maxLatency * LATENCY_MUTE_FACTOR, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004701 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004702 sp<SourceClientDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004703 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004704 if (source != 0){
4705 connectAudioSource(source);
4706 }
Eric Laurente552edb2014-03-10 17:42:56 -07004707 }
4708
4709 // Move effects associated to this strategy from previous output to new output
4710 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004711 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004712 }
4713 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004714 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004715 if (getStrategy((audio_stream_type_t)i) == strategy) {
4716 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004717 }
4718 }
4719 }
4720}
4721
Eric Laurente0720872014-03-11 09:30:41 -07004722void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004723{
François Gaffie2110e042015-03-24 08:41:51 +01004724 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004725 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004726 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004727 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004728 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004729 checkOutputForStrategy(STRATEGY_SONIFICATION);
4730 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004731 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004732 checkOutputForStrategy(STRATEGY_MEDIA);
4733 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004734 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004735}
4736
Eric Laurente0720872014-03-11 09:30:41 -07004737void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004738{
François Gaffie53615e22015-03-19 09:24:12 +01004739 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004740 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004741 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004742 return;
4743 }
4744
Eric Laurent3a4311c2014-03-17 12:00:47 -07004745 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004746 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4747 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4748 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004749
4750 // if suspended, restore A2DP output if:
4751 // ((SCO device is NOT connected) ||
4752 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4753 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004754 //
Eric Laurentf732e072016-08-03 19:30:28 -07004755 // if not suspended, suspend A2DP output if:
4756 // (SCO device is connected) &&
4757 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4758 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004759 //
4760 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004761 if (!isScoConnected ||
4762 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4763 AUDIO_POLICY_FORCE_BT_SCO) &&
4764 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4765 AUDIO_POLICY_FORCE_BT_SCO) &&
4766 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004767 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004768
4769 mpClientInterface->restoreOutput(a2dpOutput);
4770 mA2dpSuspended = false;
4771 }
4772 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004773 if (isScoConnected &&
4774 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4775 AUDIO_POLICY_FORCE_BT_SCO) ||
4776 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4777 AUDIO_POLICY_FORCE_BT_SCO) ||
4778 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004779 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004780
4781 mpClientInterface->suspendOutput(a2dpOutput);
4782 mA2dpSuspended = true;
4783 }
4784 }
4785}
4786
Eric Laurent97ac8712018-07-27 18:59:02 -07004787template <class IoDescriptor, class Filter>
4788sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4789 IoDescriptor& desc, Filter filter, bool& active, const DeviceVector& devices)
4790{
4791 auto activeClients = desc->clientsList(true /*activeOnly*/);
4792 auto activeClientsWithRoute =
4793 desc->clientsList(true /*activeOnly*/, filter, true /*preferredDevice*/);
4794 active = activeClients.size() > 0;
4795 if (active && activeClients.size() == activeClientsWithRoute.size()) {
4796 return devices.getDeviceFromId(activeClientsWithRoute[0]->preferredDeviceId());
4797 }
4798 return nullptr;
4799}
4800
4801template <class IoCollection, class Filter>
4802sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4803 IoCollection& ioCollection, Filter filter, const DeviceVector& devices)
4804{
4805 sp<DeviceDescriptor> device;
4806 for (size_t i = 0; i < ioCollection.size(); i++) {
4807 auto desc = ioCollection.valueAt(i);
4808 bool active;
4809 sp<DeviceDescriptor> curDevice = findPreferredDevice(desc, filter, active, devices);
4810 if (active && curDevice == nullptr) {
4811 return nullptr;
4812 } else if (curDevice != nullptr) {
4813 device = curDevice;
4814 }
4815 }
4816 return device;
4817}
4818
Eric Laurentc75307b2015-03-17 15:29:32 -07004819audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4820 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004821{
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004822 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004823 if (index >= 0) {
4824 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4825 if (patchDesc->mUid != mUidCached) {
4826 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004827 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004828 return outputDesc->device();
4829 }
4830 }
4831
Eric Laurent97ac8712018-07-27 18:59:02 -07004832 // Honor explicit routing requests only if no client using default routing is active on this
4833 // input: a specific app can not force routing for other apps by setting a preferred device.
4834 bool active; // unused
4835 sp<DeviceDescriptor> deviceDesc =
4836 findPreferredDevice(outputDesc, STRATEGY_NONE, active, mAvailableOutputDevices);
4837 if (deviceDesc != nullptr) {
4838 return deviceDesc->type();
Eric Laurentf3a5a602018-05-22 18:42:55 -07004839 }
4840
Eric Laurente552edb2014-03-10 17:42:56 -07004841 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004842 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004843 // use device for strategy enforced audible
4844 // 2: we are in call or the strategy phone is active on the output:
4845 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004846 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004847 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004848 // 4: the strategy for enforced audible is active but not enforced on the output:
4849 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004850 // 5: the strategy accessibility is active on the output:
4851 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004852 // 6: the strategy "respectful" sonification is active on the output:
4853 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004854 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004855 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004856 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004857 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004858 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004859 // use device for strategy t-t-s
Eric Laurent484e9272018-06-07 17:29:23 -07004860
4861 // FIXME: extend use of isStrategyActiveOnSameModule() to all strategies
4862 // with a refined rule considering mutually exclusive devices (using same backend)
4863 // as opposed to all streams on the same audio HAL module.
Eric Laurent97ac8712018-07-27 18:59:02 -07004864 audio_devices_t device = AUDIO_DEVICE_NONE;
François Gaffiead3183e2015-03-18 16:55:35 +01004865 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004866 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004867 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4868 } else if (isInCall() ||
Eric Laurent484e9272018-06-07 17:29:23 -07004869 isStrategyActiveOnSameModule(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004870 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
Yung Ti Su3e7eb5e2018-06-13 11:48:42 +08004871 } else if (isStrategyActiveOnSameModule(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004872 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004873 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
4874 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004875 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4876 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004877 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004878 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004879 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004880 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004881 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004882 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004883 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004884 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004885 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004886 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004887 }
4888
Eric Laurent1c333e22014-05-20 10:48:17 -07004889 ALOGV("getNewOutputDevice() selected device %x", device);
4890 return device;
4891}
4892
Eric Laurentfb66dd92016-01-28 18:32:03 -08004893audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004894{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004895 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004896
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004897 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004898 if (index >= 0) {
4899 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4900 if (patchDesc->mUid != mUidCached) {
4901 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004902 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004903 return inputDesc->mDevice;
4904 }
4905 }
4906
Eric Laurent97ac8712018-07-27 18:59:02 -07004907 // Honor explicit routing requests only if no client using default routing is active on this
4908 // input: a specific app can not force routing for other apps by setting a preferred device.
4909 bool active;
4910 sp<DeviceDescriptor> deviceDesc =
4911 findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
4912 if (deviceDesc != nullptr) {
4913 return deviceDesc->type();
4914 }
4915
Eric Laurentdc95a252018-04-12 12:46:56 -07004916 // If we are not in call and no client is active on this input, this methods returns
4917 // AUDIO_DEVICE_NONE, causing the patch on the input stream to be released.
Eric Laurentfb66dd92016-01-28 18:32:03 -08004918 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
Eric Laurentdc95a252018-04-12 12:46:56 -07004919 if (source == AUDIO_SOURCE_DEFAULT && isInCall()) {
4920 source = AUDIO_SOURCE_VOICE_COMMUNICATION;
4921 }
4922 if (source != AUDIO_SOURCE_DEFAULT) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08004923 device = getDeviceAndMixForInputSource(source);
4924 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004925
Eric Laurente552edb2014-03-10 17:42:56 -07004926 return device;
4927}
4928
Eric Laurent794fde22016-03-11 09:50:45 -08004929bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4930 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004931 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004932}
4933
Eric Laurente0720872014-03-11 09:30:41 -07004934uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004935 return (uint32_t)getStrategy(stream);
4936}
4937
Eric Laurente0720872014-03-11 09:30:41 -07004938audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004939 // By checking the range of stream before calling getStrategy, we avoid
4940 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4941 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004942 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004943 return AUDIO_DEVICE_NONE;
4944 }
Eric Laurentb0688d62018-08-14 15:49:18 -07004945 audio_devices_t activeDevices = AUDIO_DEVICE_NONE;
Eric Laurent28d09f02016-03-08 10:43:05 -08004946 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004947 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4948 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004949 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004950 }
Eric Laurent794fde22016-03-11 09:50:45 -08004951 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004952 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004953 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Eric Laurentb0688d62018-08-14 15:49:18 -07004954 devices |= curDevices;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004955 for (audio_io_handle_t output : getOutputsForDevice(curDevices, mOutputs)) {
4956 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08004957 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurentb0688d62018-08-14 15:49:18 -07004958 activeDevices |= outputDesc->device();
Eric Laurent28d09f02016-03-08 10:43:05 -08004959 }
4960 }
Eric Laurente552edb2014-03-10 17:42:56 -07004961 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004962
Eric Laurentb0688d62018-08-14 15:49:18 -07004963 // Favor devices selected on active streams if any to report correct device in case of
4964 // explicit device selection
4965 if (activeDevices != AUDIO_DEVICE_NONE) {
4966 devices = activeDevices;
4967 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004968 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4969 and doesn't really need to.*/
4970 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4971 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4972 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4973 }
Eric Laurente552edb2014-03-10 17:42:56 -07004974 return devices;
4975}
4976
François Gaffie2110e042015-03-24 08:41:51 +01004977routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4978{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004979 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004980 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004981}
4982
Eric Laurent97ac8712018-07-27 18:59:02 -07004983routing_strategy AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004984 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004985 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004986 return STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004987 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004988 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004989 return STRATEGY_ENFORCED_AUDIBLE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004990 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004991 // usage to strategy mapping
Eric Laurent97ac8712018-07-27 18:59:02 -07004992 return mEngine->getStrategyForUsage(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004993}
4994
Eric Laurente0720872014-03-11 09:30:41 -07004995void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004996 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004997 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004998 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4999 updateDevicesAndOutputs();
5000 break;
5001 default:
5002 break;
5003 }
5004}
5005
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005006uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07005007
5008 // skip beacon mute management if a dedicated TTS output is available
5009 if (mTtsOutputAvailable) {
5010 return 0;
5011 }
5012
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005013 switch(event) {
5014 case STARTING_OUTPUT:
5015 mBeaconMuteRefCount++;
5016 break;
5017 case STOPPING_OUTPUT:
5018 if (mBeaconMuteRefCount > 0) {
5019 mBeaconMuteRefCount--;
5020 }
5021 break;
5022 case STARTING_BEACON:
5023 mBeaconPlayingRefCount++;
5024 break;
5025 case STOPPING_BEACON:
5026 if (mBeaconPlayingRefCount > 0) {
5027 mBeaconPlayingRefCount--;
5028 }
5029 break;
5030 }
5031
5032 if (mBeaconMuteRefCount > 0) {
5033 // any playback causes beacon to be muted
5034 return setBeaconMute(true);
5035 } else {
5036 // no other playback: unmute when beacon starts playing, mute when it stops
5037 return setBeaconMute(mBeaconPlayingRefCount == 0);
5038 }
5039}
5040
5041uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5042 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5043 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5044 // keep track of muted state to avoid repeating mute/unmute operations
5045 if (mBeaconMuted != mute) {
5046 // mute/unmute AUDIO_STREAM_TTS on all outputs
5047 ALOGV("\t muting %d", mute);
5048 uint32_t maxLatency = 0;
5049 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005050 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005051 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07005052 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005053 0 /*delay*/, AUDIO_DEVICE_NONE);
5054 const uint32_t latency = desc->latency() * 2;
5055 if (latency > maxLatency) {
5056 maxLatency = latency;
5057 }
5058 }
5059 mBeaconMuted = mute;
5060 return maxLatency;
5061 }
5062 return 0;
5063}
5064
Eric Laurente0720872014-03-11 09:30:41 -07005065audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01005066 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005067{
Eric Laurent97ac8712018-07-27 18:59:02 -07005068 // Honor explicit routing requests only if all active clients have a preferred route in which
5069 // case the last active client route is used
5070 sp<DeviceDescriptor> deviceDesc = findPreferredDevice(mOutputs, strategy, mAvailableOutputDevices);
5071 if (deviceDesc != nullptr) {
5072 return deviceDesc->type();
Paul McLeanaa981192015-03-21 09:55:15 -07005073 }
5074
Eric Laurente552edb2014-03-10 17:42:56 -07005075 if (fromCache) {
5076 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
5077 strategy, mDeviceForStrategy[strategy]);
5078 return mDeviceForStrategy[strategy];
5079 }
François Gaffie2110e042015-03-24 08:41:51 +01005080 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07005081}
5082
Eric Laurente0720872014-03-11 09:30:41 -07005083void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005084{
5085 for (int i = 0; i < NUM_STRATEGIES; i++) {
5086 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
5087 }
5088 mPreviousOutputs = mOutputs;
5089}
5090
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005091uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005092 audio_devices_t prevDevice,
5093 uint32_t delayMs)
5094{
5095 // mute/unmute strategies using an incompatible device combination
5096 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5097 // if unmuting, unmute only after the specified delay
5098 if (outputDesc->isDuplicated()) {
5099 return 0;
5100 }
5101
5102 uint32_t muteWaitMs = 0;
5103 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07005104 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005105
5106 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
5107 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07005108 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07005109 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
5110 bool doMute = false;
5111
5112 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
5113 doMute = true;
5114 outputDesc->mStrategyMutedByDevice[i] = true;
5115 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
5116 doMute = true;
5117 outputDesc->mStrategyMutedByDevice[i] = false;
5118 }
Eric Laurent99401132014-05-07 19:48:15 -07005119 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005120 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005121 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005122 // skip output if it does not share any device with current output
5123 if ((desc->supportedDevices() & outputDesc->supportedDevices())
5124 == AUDIO_DEVICE_NONE) {
5125 continue;
5126 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005127 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07005128 mute ? "muting" : "unmuting", i, curDevice);
5129 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005130 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005131 if (mute) {
5132 // FIXME: should not need to double latency if volume could be applied
5133 // immediately by the audioflinger mixer. We must account for the delay
5134 // between now and the next time the audioflinger thread for this output
5135 // will process a buffer (which corresponds to one buffer size,
5136 // usually 1/2 or 1/4 of the latency).
5137 if (muteWaitMs < desc->latency() * 2) {
5138 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005139 }
5140 }
5141 }
5142 }
5143 }
5144 }
5145
Eric Laurent99401132014-05-07 19:48:15 -07005146 // temporary mute output if device selection changes to avoid volume bursts due to
5147 // different per device volumes
5148 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005149 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5150 // temporary mute duration is conservatively set to 4 times the reported latency
5151 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5152 if (muteWaitMs < tempMuteWaitMs) {
5153 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005154 }
Eric Laurentdc462862016-07-19 12:29:53 -07005155
Eric Laurent99401132014-05-07 19:48:15 -07005156 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005157 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005158 // make sure that we do not start the temporary mute period too early in case of
5159 // delayed device change
5160 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005161 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07005162 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07005163 }
5164 }
5165 }
5166
Eric Laurente552edb2014-03-10 17:42:56 -07005167 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5168 if (muteWaitMs > delayMs) {
5169 muteWaitMs -= delayMs;
5170 usleep(muteWaitMs * 1000);
5171 return muteWaitMs;
5172 }
5173 return 0;
5174}
5175
Eric Laurentc75307b2015-03-17 15:29:32 -07005176uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005177 audio_devices_t device,
5178 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07005179 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005180 audio_patch_handle_t *patchHandle,
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005181 const char *address,
5182 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005183{
Eric Laurentc75307b2015-03-17 15:29:32 -07005184 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005185 AudioParameter param;
5186 uint32_t muteWaitMs;
5187
5188 if (outputDesc->isDuplicated()) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005189 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs,
5190 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
5191 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs,
5192 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005193 return muteWaitMs;
5194 }
5195 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5196 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07005197 if ((device != AUDIO_DEVICE_NONE) &&
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005198 ((device & outputDesc->supportedDevices()) == AUDIO_DEVICE_NONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005199 return 0;
5200 }
5201
5202 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07005203 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07005204
5205 audio_devices_t prevDevice = outputDesc->mDevice;
5206
Paul McLeanaa981192015-03-21 09:55:15 -07005207 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005208
5209 if (device != AUDIO_DEVICE_NONE) {
5210 outputDesc->mDevice = device;
5211 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005212
5213 // if the outputs are not materially active, there is no need to mute.
5214 if (requiresMuteCheck) {
5215 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
5216 } else {
5217 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5218 muteWaitMs = 0;
5219 }
Eric Laurente552edb2014-03-10 17:42:56 -07005220
5221 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005222 // the requested device is AUDIO_DEVICE_NONE
5223 // OR the requested device is the same as current device
5224 // AND force is not specified
5225 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07005226 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07005227 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
5228 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005229 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005230 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005231 return muteWaitMs;
5232 }
5233
5234 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07005235
Eric Laurente552edb2014-03-10 17:42:56 -07005236 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07005237 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005238 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005239 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07005240 DeviceVector deviceList;
5241 if ((address == NULL) || (strlen(address) == 0)) {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005242 deviceList = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurentc40d9692016-04-13 19:14:13 -07005243 } else {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005244 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
5245 device, String8(address));
5246 if (deviceDesc) deviceList.add(deviceDesc);
Eric Laurentc40d9692016-04-13 19:14:13 -07005247 }
5248
Eric Laurent1c333e22014-05-20 10:48:17 -07005249 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005250 PatchBuilder patchBuilder;
5251 patchBuilder.addSource(outputDesc);
Eric Laurent1c333e22014-05-20 10:48:17 -07005252 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005253 patchBuilder.addSink(deviceList.itemAt(i));
Eric Laurent1c333e22014-05-20 10:48:17 -07005254 }
Mikhail Naganovdc769682018-05-04 15:34:08 -07005255 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005256 }
bryant_liuf5e7e792014-08-19 20:07:05 +08005257
5258 // inform all input as well
5259 for (size_t i = 0; i < mInputs.size(); i++) {
5260 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01005261 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08005262 AudioParameter inputCmd = AudioParameter();
5263 ALOGV("%s: inform input %d of device:%d", __func__,
5264 inputDescriptor->mIoHandle, device);
5265 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
5266 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
5267 inputCmd.toString(),
5268 delayMs);
5269 }
5270 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005271 }
Eric Laurente552edb2014-03-10 17:42:56 -07005272
5273 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07005274 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005275
5276 return muteWaitMs;
5277}
5278
Eric Laurentc75307b2015-03-17 15:29:32 -07005279status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005280 int delayMs,
5281 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005282{
Eric Laurent6a94d692014-05-20 11:18:06 -07005283 ssize_t index;
5284 if (patchHandle) {
5285 index = mAudioPatches.indexOfKey(*patchHandle);
5286 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005287 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005288 }
5289 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005290 return INVALID_OPERATION;
5291 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005292 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5293 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005294 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005295 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005296 removeAudioPatch(patchDesc->mHandle);
5297 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005298 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005299 return status;
5300}
5301
5302status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5303 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005304 bool force,
5305 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005306{
5307 status_t status = NO_ERROR;
5308
Eric Laurent1f2f2232014-06-02 12:01:23 -07005309 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005310 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5311 inputDesc->mDevice = device;
5312
Mikhail Naganov708e0382018-05-30 09:53:04 -07005313 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005314 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005315 PatchBuilder patchBuilder;
5316 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005317 // AUDIO_SOURCE_HOTWORD is for internal use only:
5318 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07005319 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5320 auto result = usecase;
5321 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5322 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5323 }
5324 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07005325 //only one input device for now
Mikhail Naganovdc769682018-05-04 15:34:08 -07005326 addSource(deviceList.itemAt(0));
5327 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005328 }
5329 }
5330 return status;
5331}
5332
Eric Laurent6a94d692014-05-20 11:18:06 -07005333status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5334 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005335{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005336 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005337 ssize_t index;
5338 if (patchHandle) {
5339 index = mAudioPatches.indexOfKey(*patchHandle);
5340 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005341 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005342 }
5343 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005344 return INVALID_OPERATION;
5345 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005346 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5347 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005348 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005349 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005350 removeAudioPatch(patchDesc->mHandle);
5351 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005352 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005353 return status;
5354}
5355
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005356sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005357 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005358 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005359 audio_format_t& format,
5360 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005361 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005362{
5363 // Choose an input profile based on the requested capture parameters: select the first available
5364 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005365 //
5366 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5367 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005368
Glenn Kasten730b9262018-03-29 15:01:26 -07005369 sp<IOProfile> firstInexact;
5370 uint32_t updatedSamplingRate = 0;
5371 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5372 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005373 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005374 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005375 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005376 //updatedFormat = format;
Eric Laurent275e8e92014-11-30 15:14:47 -08005377 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005378 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005379 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005380 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005381 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005382 &channelMask /*updatedChannelMask*/,
5383 // FIXME ugly cast
5384 (audio_output_flags_t) flags,
5385 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005386 return profile;
5387 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005388 if (firstInexact == nullptr && profile->isCompatibleProfile(device, address,
5389 samplingRate,
5390 &updatedSamplingRate,
5391 format,
5392 &updatedFormat,
5393 channelMask,
5394 &updatedChannelMask,
5395 // FIXME ugly cast
5396 (audio_output_flags_t) flags,
5397 false /*exactMatchRequiredForInputFlags*/)) {
5398 firstInexact = profile;
5399 }
5400
Eric Laurente552edb2014-03-10 17:42:56 -07005401 }
5402 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005403 if (firstInexact != nullptr) {
5404 samplingRate = updatedSamplingRate;
5405 format = updatedFormat;
5406 channelMask = updatedChannelMask;
5407 return firstInexact;
5408 }
Eric Laurente552edb2014-03-10 17:42:56 -07005409 return NULL;
5410}
5411
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005412
5413audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005414 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005415{
Eric Laurent97ac8712018-07-27 18:59:02 -07005416 // Honor explicit routing requests only if all active clients have a preferred route in which
5417 // case the last active client route is used
5418 sp<DeviceDescriptor> deviceDesc =
5419 findPreferredDevice(mInputs, inputSource, mAvailableInputDevices);
5420 if (deviceDesc != nullptr) {
5421 return deviceDesc->type();
5422 }
5423
5424
François Gaffie036e1e92015-03-19 10:16:24 +01005425 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5426 audio_devices_t selectedDeviceFromMix =
5427 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005428
François Gaffie036e1e92015-03-19 10:16:24 +01005429 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5430 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005431 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005432 return getDeviceForInputSource(inputSource);
5433}
5434
5435audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5436{
Eric Laurent97ac8712018-07-27 18:59:02 -07005437 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005438}
5439
Eric Laurente0720872014-03-11 09:30:41 -07005440float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005441 int index,
5442 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005443{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005444 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005445
5446 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5447 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5448 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5449 // the ringtone volume
5450 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5451 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5452 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5453 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5454 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5455 }
5456
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005457 // in-call: always cap volume by voice volume + some low headroom
5458 if ((stream != AUDIO_STREAM_VOICE_CALL) &&
Eric Laurent7731b5a2018-04-06 15:47:22 -07005459 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005460 switch (stream) {
5461 case AUDIO_STREAM_SYSTEM:
5462 case AUDIO_STREAM_RING:
5463 case AUDIO_STREAM_MUSIC:
5464 case AUDIO_STREAM_ALARM:
5465 case AUDIO_STREAM_NOTIFICATION:
5466 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5467 case AUDIO_STREAM_DTMF:
5468 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005469 int voiceVolumeIndex =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005470 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, device);
Eric Laurent7731b5a2018-04-06 15:47:22 -07005471 const float maxVoiceVolDb =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005472 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, device)
Eric Laurent7731b5a2018-04-06 15:47:22 -07005473 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005474 if (volumeDB > maxVoiceVolDb) {
5475 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5476 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5477 volumeDB = maxVoiceVolDb;
5478 }
5479 } break;
5480 default:
5481 break;
5482 }
5483 }
5484
Eric Laurente552edb2014-03-10 17:42:56 -07005485 // if a headset is connected, apply the following rules to ring tones and notifications
5486 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005487 // - always attenuate notifications volume by 6dB
5488 // - attenuate ring tones volume by 6dB unless music is not playing and
5489 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005490 // - if music is playing, always limit the volume to current music volume,
5491 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005492 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005493 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5494 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5495 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005496 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005497 AUDIO_DEVICE_OUT_USB_HEADSET |
5498 AUDIO_DEVICE_OUT_HEARING_AID)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005499 ((stream_strategy == STRATEGY_SONIFICATION)
5500 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005501 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005502 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005503 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005504 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005505 // when the phone is ringing we must consider that music could have been paused just before
5506 // by the music application and behave as if music was active if the last music track was
5507 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005508 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005509 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005510 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005511 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005512 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005513 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5514 musicDevice),
5515 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005516 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5517 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005518 if (volumeDB > minVolDB) {
5519 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005520 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005521 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005522 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5523 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5524 // on A2DP, also ensure notification volume is not too low compared to media when
5525 // intended to be played
5526 if ((volumeDB > -96.0f) &&
5527 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5528 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5529 stream, device,
5530 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5531 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5532 }
5533 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005534 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5535 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005536 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005537 }
5538 }
5539
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005540 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005541}
5542
Eric Laurent3839bc02018-07-10 18:33:34 -07005543int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
5544 audio_stream_type_t srcStream,
5545 audio_stream_type_t dstStream)
5546{
5547 if (srcStream == dstStream) {
5548 return srcIndex;
5549 }
5550 float minSrc = (float)mVolumeCurves->getVolumeIndexMin(srcStream);
5551 float maxSrc = (float)mVolumeCurves->getVolumeIndexMax(srcStream);
5552 float minDst = (float)mVolumeCurves->getVolumeIndexMin(dstStream);
5553 float maxDst = (float)mVolumeCurves->getVolumeIndexMax(dstStream);
5554
5555 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
5556}
5557
Eric Laurente0720872014-03-11 09:30:41 -07005558status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005559 int index,
5560 const sp<AudioOutputDescriptor>& outputDesc,
5561 audio_devices_t device,
5562 int delayMs,
5563 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005564{
Eric Laurente552edb2014-03-10 17:42:56 -07005565 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005566 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005567 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005568 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005569 return NO_ERROR;
5570 }
François Gaffie2110e042015-03-24 08:41:51 +01005571 audio_policy_forced_cfg_t forceUseForComm =
5572 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005573 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005574 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5575 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005576 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005577 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005578 return INVALID_OPERATION;
5579 }
5580
Eric Laurentc75307b2015-03-17 15:29:32 -07005581 if (device == AUDIO_DEVICE_NONE) {
5582 device = outputDesc->device();
5583 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005584
Eric Laurentffbc80f2015-03-18 18:30:19 -07005585 float volumeDb = computeVolume(stream, index, device);
HW Leeda7581e2018-05-22 18:31:34 +08005586 if (outputDesc->isFixedVolume(device) ||
5587 // Force VoIP volume to max for bluetooth SCO
5588 ((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
5589 (device & AUDIO_DEVICE_OUT_ALL_SCO) != 0)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005590 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005591 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005592
Eric Laurentffbc80f2015-03-18 18:30:19 -07005593 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005594
Eric Laurent3b73df72014-03-11 09:06:29 -07005595 if (stream == AUDIO_STREAM_VOICE_CALL ||
5596 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005597 float voiceVolume;
5598 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005599 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurent3839bc02018-07-10 18:33:34 -07005600 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005601 } else {
5602 voiceVolume = 1.0;
5603 }
5604
Eric Laurent18fba842016-03-31 14:41:26 -07005605 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005606 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5607 mLastVoiceVolume = voiceVolume;
5608 }
5609 }
5610
5611 return NO_ERROR;
5612}
5613
Eric Laurentc75307b2015-03-17 15:29:32 -07005614void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5615 audio_devices_t device,
5616 int delayMs,
5617 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005618{
Eric Laurentc75307b2015-03-17 15:29:32 -07005619 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005620
Eric Laurent794fde22016-03-11 09:50:45 -08005621 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005622 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005623 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005624 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005625 device,
5626 delayMs,
5627 force);
5628 }
5629}
5630
Eric Laurente0720872014-03-11 09:30:41 -07005631void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005632 bool on,
5633 const sp<AudioOutputDescriptor>& outputDesc,
5634 int delayMs,
5635 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005636{
Eric Laurent72249d52015-06-08 11:12:15 -07005637 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5638 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005639 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005640 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005641 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005642 }
5643 }
5644}
5645
Eric Laurente0720872014-03-11 09:30:41 -07005646void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005647 bool on,
5648 const sp<AudioOutputDescriptor>& outputDesc,
5649 int delayMs,
5650 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005651{
Eric Laurente552edb2014-03-10 17:42:56 -07005652 if (device == AUDIO_DEVICE_NONE) {
5653 device = outputDesc->device();
5654 }
5655
Eric Laurentc75307b2015-03-17 15:29:32 -07005656 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5657 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005658
5659 if (on) {
5660 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005661 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005662 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005663 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005664 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005665 }
5666 }
5667 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5668 outputDesc->mMuteCount[stream]++;
5669 } else {
5670 if (outputDesc->mMuteCount[stream] == 0) {
5671 ALOGV("setStreamMute() unmuting non muted stream!");
5672 return;
5673 }
5674 if (--outputDesc->mMuteCount[stream] == 0) {
5675 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005676 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005677 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005678 device,
5679 delayMs);
5680 }
5681 }
5682}
5683
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005684audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5685{
5686 // flags to stream type mapping
5687 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5688 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5689 }
5690 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5691 return AUDIO_STREAM_BLUETOOTH_SCO;
5692 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005693 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5694 return AUDIO_STREAM_TTS;
5695 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005696
Ari Hausman-Cohen5c00d012018-06-26 17:09:11 -07005697 return audio_usage_to_stream_type(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005698}
Eric Laurente83b55d2014-11-14 10:06:21 -08005699
François Gaffie53615e22015-03-19 09:24:12 +01005700bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5701{
Eric Laurente83b55d2014-11-14 10:06:21 -08005702 // has flags that map to a strategy?
5703 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5704 return true;
5705 }
5706
5707 // has known usage?
5708 switch (paa->usage) {
5709 case AUDIO_USAGE_UNKNOWN:
5710 case AUDIO_USAGE_MEDIA:
5711 case AUDIO_USAGE_VOICE_COMMUNICATION:
5712 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5713 case AUDIO_USAGE_ALARM:
5714 case AUDIO_USAGE_NOTIFICATION:
5715 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5716 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5717 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5718 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5719 case AUDIO_USAGE_NOTIFICATION_EVENT:
5720 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5721 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5722 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5723 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005724 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005725 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005726 break;
5727 default:
5728 return false;
5729 }
5730 return true;
5731}
5732
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005733bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005734 routing_strategy strategy, uint32_t inPastMs,
5735 nsecs_t sysTime) const
5736{
5737 if ((sysTime == 0) && (inPastMs != 0)) {
5738 sysTime = systemTime();
5739 }
Eric Laurent794fde22016-03-11 09:50:45 -08005740 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005741 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurent97ac8712018-07-27 18:59:02 -07005742 (STRATEGY_NONE == strategy)) &&
François Gaffiead3183e2015-03-18 16:55:35 +01005743 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5744 return true;
5745 }
5746 }
5747 return false;
5748}
5749
Eric Laurent484e9272018-06-07 17:29:23 -07005750bool AudioPolicyManager::isStrategyActiveOnSameModule(const sp<AudioOutputDescriptor>& outputDesc,
5751 routing_strategy strategy, uint32_t inPastMs,
5752 nsecs_t sysTime) const
5753{
5754 for (size_t i = 0; i < mOutputs.size(); i++) {
5755 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5756 if (outputDesc->sharesHwModuleWith(desc)
5757 && isStrategyActive(desc, strategy, inPastMs, sysTime)) {
5758 return true;
5759 }
5760 }
5761 return false;
5762}
5763
François Gaffie2110e042015-03-24 08:41:51 +01005764audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5765{
5766 return mEngine->getForceUse(usage);
5767}
5768
5769bool AudioPolicyManager::isInCall()
5770{
5771 return isStateInCall(mEngine->getPhoneState());
5772}
5773
5774bool AudioPolicyManager::isStateInCall(int state)
5775{
5776 return is_state_in_call(state);
5777}
5778
Eric Laurentd60560a2015-04-10 11:31:20 -07005779void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5780{
5781 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005782 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5783 if (sourceDesc->srcDevice()->equals(deviceDesc)) {
5784 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->portId());
5785 stopAudioSource(sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005786 }
5787 }
5788
5789 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5790 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5791 bool release = false;
5792 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5793 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5794 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5795 source->ext.device.type == deviceDesc->type()) {
5796 release = true;
5797 }
5798 }
5799 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5800 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5801 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5802 sink->ext.device.type == deviceDesc->type()) {
5803 release = true;
5804 }
5805 }
5806 if (release) {
5807 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5808 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5809 }
5810 }
5811}
5812
Phil Burk09bc4612016-02-24 15:58:15 -08005813// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005814void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5815 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005816 // TODO Set this based on Config properties.
5817 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005818
5819 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5820 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005821 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005822
jiabin81772902018-04-02 17:52:27 -07005823 // If MANUAL, keep the supported surround sound formats as current enabled ones.
5824 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
5825 formats.clear();
5826 for (auto it = mSurroundFormats.begin(); it != mSurroundFormats.end(); it++) {
5827 formats.add(*it);
Phil Burk09bc4612016-02-24 15:58:15 -08005828 }
jiabin81772902018-04-02 17:52:27 -07005829 // Always enable IEC61937 when in MANUAL mode.
5830 formats.add(AUDIO_FORMAT_IEC61937);
5831 } else { // NEVER, AUTO or ALWAYS
5832 // Analyze original support for various formats.
5833 bool supportsAC3 = false;
5834 bool supportsOtherSurround = false;
5835 bool supportsIEC61937 = false;
5836 mSurroundFormats.clear();
5837 for (ssize_t formatIndex = 0; formatIndex < (ssize_t)formats.size(); formatIndex++) {
5838 audio_format_t format = formats[formatIndex];
5839 switch (format) {
5840 case AUDIO_FORMAT_AC3:
5841 supportsAC3 = true;
5842 break;
5843 case AUDIO_FORMAT_E_AC3:
5844 case AUDIO_FORMAT_DTS:
5845 case AUDIO_FORMAT_DTS_HD:
5846 // If ALWAYS, remove all other surround formats here
5847 // since we will add them later.
5848 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5849 formats.removeAt(formatIndex);
5850 formatIndex--;
5851 }
5852 supportsOtherSurround = true;
5853 break;
5854 case AUDIO_FORMAT_IEC61937:
5855 supportsIEC61937 = true;
5856 break;
5857 default:
5858 break;
5859 }
5860 }
Phil Burk09bc4612016-02-24 15:58:15 -08005861
jiabin81772902018-04-02 17:52:27 -07005862 // Modify formats based on surround preferences.
5863 // If NEVER, remove support for surround formats.
5864 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5865 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5866 // Remove surround sound related formats.
5867 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5868 audio_format_t format = formats[formatIndex];
5869 switch(format) {
5870 case AUDIO_FORMAT_AC3:
5871 case AUDIO_FORMAT_E_AC3:
5872 case AUDIO_FORMAT_DTS:
5873 case AUDIO_FORMAT_DTS_HD:
5874 case AUDIO_FORMAT_IEC61937:
5875 formats.removeAt(formatIndex);
5876 break;
5877 default:
5878 formatIndex++; // keep it
5879 break;
5880 }
5881 }
5882 supportsAC3 = false;
5883 supportsOtherSurround = false;
5884 supportsIEC61937 = false;
5885 }
5886 } else { // AUTO or ALWAYS
5887 // Most TVs support AC3 even if they do not report it in the EDID.
5888 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
5889 && !supportsAC3) {
5890 formats.add(AUDIO_FORMAT_AC3);
5891 supportsAC3 = true;
5892 }
5893
5894 // If ALWAYS, add support for raw surround formats if all are missing.
5895 // This assumes that if any of these formats are reported by the HAL
5896 // then the report is valid and should not be modified.
5897 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5898 formats.add(AUDIO_FORMAT_E_AC3);
5899 formats.add(AUDIO_FORMAT_DTS);
5900 formats.add(AUDIO_FORMAT_DTS_HD);
5901 supportsOtherSurround = true;
5902 }
5903
5904 // Add support for IEC61937 if any raw surround supported.
5905 // The HAL could do this but add it here, just in case.
5906 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
5907 formats.add(AUDIO_FORMAT_IEC61937);
5908 supportsIEC61937 = true;
5909 }
5910
5911 // Add reported surround sound formats to enabled surround formats.
5912 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
Phil Burk07ac1142016-03-25 13:39:29 -07005913 audio_format_t format = formats[formatIndex];
Mikhail Naganov02743e22018-11-28 15:56:55 -08005914 if (mConfig.getSurroundFormats().count(format) != 0) {
5915 mSurroundFormats.insert(format);
Phil Burk07ac1142016-03-25 13:39:29 -07005916 }
Phil Burk09bc4612016-02-24 15:58:15 -08005917 }
Phil Burk07ac1142016-03-25 13:39:29 -07005918 }
Phil Burk09bc4612016-02-24 15:58:15 -08005919 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005920}
5921
5922// Modify the list of channel masks supported.
5923void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
5924 ChannelsVector &channelMasks = *channelMasksPtr;
5925 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5926 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5927
5928 // If NEVER, then remove support for channelMasks > stereo.
5929 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5930 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5931 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5932 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5933 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5934 channelMasks.removeAt(maskIndex);
5935 } else {
5936 maskIndex++;
5937 }
5938 }
jiabin81772902018-04-02 17:52:27 -07005939 // If ALWAYS or MANUAL, then make sure we at least support 5.1
5940 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
5941 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005942 bool supports5dot1 = false;
5943 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005944 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005945 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5946 supports5dot1 = true;
5947 break;
5948 }
5949 }
5950 // If not then add 5.1 support.
5951 if (!supports5dot1) {
5952 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
5953 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
5954 }
Phil Burk09bc4612016-02-24 15:58:15 -08005955 }
5956}
5957
Phil Burk00eeb322016-03-31 12:41:00 -07005958void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
5959 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005960 AudioProfileVector &profiles)
5961{
5962 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07005963
François Gaffie112b0af2015-11-19 16:13:25 +01005964 // Format MUST be checked first to update the list of AudioProfile
5965 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005966 reply = mpClientInterface->getParameters(
5967 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07005968 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005969 AudioParameter repliedParameters(reply);
5970 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005971 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005972 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5973 return;
5974 }
Phil Burk09bc4612016-02-24 15:58:15 -08005975 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07005976 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005977 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005978 }
Phil Burk09bc4612016-02-24 15:58:15 -08005979 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005980 }
François Gaffie112b0af2015-11-19 16:13:25 +01005981
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005982 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08005983 ChannelsVector channelMasks;
5984 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005985 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07005986 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01005987
5988 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005989 reply = mpClientInterface->getParameters(
5990 ioHandle,
5991 requestedParameters.toString() + ";" +
5992 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01005993 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005994 AudioParameter repliedParameters(reply);
5995 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005996 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005997 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005998 }
5999 }
6000 if (profiles.hasDynamicChannelsFor(format)) {
6001 reply = mpClientInterface->getParameters(ioHandle,
6002 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07006003 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01006004 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006005 AudioParameter repliedParameters(reply);
6006 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006007 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006008 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07006009 if (device == AUDIO_DEVICE_OUT_HDMI) {
6010 filterSurroundChannelMasks(&channelMasks);
6011 }
François Gaffie112b0af2015-11-19 16:13:25 +01006012 }
6013 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08006014 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006015 }
6016}
Eric Laurentd60560a2015-04-10 11:31:20 -07006017
Mikhail Naganovdc769682018-05-04 15:34:08 -07006018status_t AudioPolicyManager::installPatch(const char *caller,
6019 audio_patch_handle_t *patchHandle,
6020 AudioIODescriptorInterface *ioDescriptor,
6021 const struct audio_patch *patch,
6022 int delayMs)
6023{
6024 ssize_t index = mAudioPatches.indexOfKey(
6025 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6026 *patchHandle : ioDescriptor->getPatchHandle());
6027 sp<AudioPatch> patchDesc;
6028 status_t status = installPatch(
6029 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6030 if (status == NO_ERROR) {
6031 ioDescriptor->setPatchHandle(patchDesc->mHandle);
6032 }
6033 return status;
6034}
6035
6036status_t AudioPolicyManager::installPatch(const char *caller,
6037 ssize_t index,
6038 audio_patch_handle_t *patchHandle,
6039 const struct audio_patch *patch,
6040 int delayMs,
6041 uid_t uid,
6042 sp<AudioPatch> *patchDescPtr)
6043{
6044 sp<AudioPatch> patchDesc;
6045 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6046 if (index >= 0) {
6047 patchDesc = mAudioPatches.valueAt(index);
6048 afPatchHandle = patchDesc->mAfPatchHandle;
6049 }
6050
6051 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6052 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6053 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6054 if (status == NO_ERROR) {
6055 if (index < 0) {
6056 patchDesc = new AudioPatch(patch, uid);
6057 addAudioPatch(patchDesc->mHandle, patchDesc);
6058 } else {
6059 patchDesc->mPatch = *patch;
6060 }
6061 patchDesc->mAfPatchHandle = afPatchHandle;
6062 if (patchHandle) {
6063 *patchHandle = patchDesc->mHandle;
6064 }
6065 nextAudioPortGeneration();
6066 mpClientInterface->onAudioPatchListUpdate();
6067 }
6068 if (patchDescPtr) *patchDescPtr = patchDesc;
6069 return status;
6070}
6071
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006072} // namespace android