blob: 6a5a646c66ece5ab682db274ab379a97d00b2161 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070017#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090018
19// Need to keep the log statements even in production builds
20// to enable VERBOSE logging dynamically.
21// You can enable VERBOSE logging as follows:
22// adb shell setprop log.tag.APM_AudioPolicyManager V
23#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070024
25//#define VERY_VERBOSE_LOGGING
26#ifdef VERY_VERBOSE_LOGGING
27#define ALOGVV ALOGV
28#else
29#define ALOGVV(a...) do { } while(0)
30#endif
31
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +090032#define AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH 128
33#define AUDIO_POLICY_XML_CONFIG_FILE_NAME "audio_policy_configuration.xml"
Petri Gyntherf497f292018-04-17 18:46:10 -070034#define AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME \
35 "audio_policy_configuration_a2dp_offload_disabled.xml"
François Gaffief4ad6e52015-11-19 16:59:57 +010036
Eric Laurentd4692962014-05-05 18:13:44 -070037#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070038#include <math.h>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110039#include <vector>
Eric Laurentd4692962014-05-05 18:13:44 -070040
François Gaffie2110e042015-03-24 08:41:51 +010041#include <AudioPolicyManagerInterface.h>
42#include <AudioPolicyEngineInstance.h>
Eric Laurente552edb2014-03-10 17:42:56 -070043#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070044#include <utils/Log.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070045#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080046#include <media/AudioPolicyHelper.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070047#include <private/android_filesystem_config.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070048#include <soundtrigger/SoundTrigger.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070049#include <system/audio.h>
Mikhail Naganov9ee05402016-10-13 15:58:17 -070050#include <audio_policy_conf.h>
Eric Laurentd4692962014-05-05 18:13:44 -070051#include "AudioPolicyManager.h"
François Gaffied1ab2bd2015-12-02 18:20:06 +010052#include <Serializer.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010053#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010054#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070055
Eric Laurent3b73df72014-03-11 09:06:29 -070056namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070057
Eric Laurentdc462862016-07-19 12:29:53 -070058//FIXME: workaround for truncated touch sounds
59// to be removed when the problem is handled by system UI
60#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070061
62// Largest difference in dB on earpiece in call between the voice volume and another
63// media / notification / system volume.
64constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
65
Mikhail Naganov15be9d22017-11-08 14:18:13 +110066// Compressed formats for MSD module, ordered from most preferred to least preferred.
67static const std::vector<audio_format_t> compressedFormatsOrder = {{
68 AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
69 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
70// Channel masks for MSD module, 3D > 2D > 1D ordering (most preferred to least preferred).
71static const std::vector<audio_channel_mask_t> surroundChannelMasksOrder = {{
72 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
73 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
74 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
75
Eric Laurente552edb2014-03-10 17:42:56 -070076// ----------------------------------------------------------------------------
77// AudioPolicyInterface implementation
78// ----------------------------------------------------------------------------
79
Eric Laurente0720872014-03-11 09:30:41 -070080status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -080081 audio_policy_dev_state_t state,
82 const char *device_address,
83 const char *device_name)
Eric Laurente552edb2014-03-10 17:42:56 -070084{
jiabina7b43792018-02-15 16:04:46 -080085 status_t status = setDeviceConnectionStateInt(device, state, device_address, device_name);
86 nextAudioPortGeneration();
87 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -080088}
89
François Gaffie44481e72016-04-20 07:49:57 +020090void AudioPolicyManager::broadcastDeviceConnectionState(audio_devices_t device,
91 audio_policy_dev_state_t state,
92 const String8 &device_address)
93{
94 AudioParameter param(device_address);
95 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganov388360c2016-10-17 17:09:41 -070096 AudioParameter::keyStreamConnect : AudioParameter::keyStreamDisconnect);
François Gaffie44481e72016-04-20 07:49:57 +020097 param.addInt(key, device);
98 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
99}
100
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800101status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800102 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -0800103 const char *device_address,
104 const char *device_name)
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800105{
Paul McLeane743a472015-01-28 11:07:31 -0800106 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s",
Mikhail Naganov7e22e942017-12-07 10:04:29 -0800107 device, state, device_address, device_name);
Eric Laurente552edb2014-03-10 17:42:56 -0700108
109 // connect/disconnect only 1 device at a time
110 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
111
François Gaffie53615e22015-03-19 09:24:12 +0100112 sp<DeviceDescriptor> devDesc =
113 mHwModules.getDeviceDescriptor(device, device_address, device_name);
Paul McLeane743a472015-01-28 11:07:31 -0800114
Eric Laurente552edb2014-03-10 17:42:56 -0700115 // handle output devices
116 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700117 SortedVector <audio_io_handle_t> outputs;
118
Eric Laurent3a4311c2014-03-17 12:00:47 -0700119 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
120
Eric Laurente552edb2014-03-10 17:42:56 -0700121 // save a copy of the opened output descriptors before any output is opened or closed
122 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
123 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700124 switch (state)
125 {
126 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800127 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700128 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700129 ALOGW("setDeviceConnectionState() device already connected: %x", device);
130 return INVALID_OPERATION;
131 }
132 ALOGV("setDeviceConnectionState() connecting device %x", device);
133
Eric Laurente552edb2014-03-10 17:42:56 -0700134 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700135 index = mAvailableOutputDevices.add(devDesc);
136 if (index >= 0) {
François Gaffie53615e22015-03-19 09:24:12 +0100137 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700138 if (module == 0) {
139 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
140 device);
141 mAvailableOutputDevices.remove(devDesc);
142 return INVALID_OPERATION;
143 }
Paul McLeane743a472015-01-28 11:07:31 -0800144 mAvailableOutputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700145 } else {
146 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700147 }
148
François Gaffie44481e72016-04-20 07:49:57 +0200149 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
150 // parameters on newly connected devices (instead of opening the outputs...)
151 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
152
Eric Laurenta1d525f2015-01-29 13:36:45 -0800153 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700154 mAvailableOutputDevices.remove(devDesc);
François Gaffie44481e72016-04-20 07:49:57 +0200155
156 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
157 devDesc->mAddress);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700158 return INVALID_OPERATION;
159 }
François Gaffie2110e042015-03-24 08:41:51 +0100160 // Propagate device availability to Engine
161 mEngine->setDeviceConnectionState(devDesc, state);
162
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700163 // outputs should never be empty here
164 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
165 "checkOutputsForDevice() returned no outputs but status OK");
166 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
167 outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800168
Eric Laurent3ae5f312015-02-03 17:12:08 -0800169 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700170 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700171 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700172 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700173 ALOGW("setDeviceConnectionState() device not connected: %x", device);
174 return INVALID_OPERATION;
175 }
176
Paul McLean5c477aa2014-08-20 16:47:57 -0700177 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
178
Paul McLeane743a472015-01-28 11:07:31 -0800179 // Send Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200180 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700181
Eric Laurente552edb2014-03-10 17:42:56 -0700182 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700183 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700184
Eric Laurenta1d525f2015-01-29 13:36:45 -0800185 checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress);
François Gaffie2110e042015-03-24 08:41:51 +0100186
187 // Propagate device availability to Engine
188 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700189 } break;
190
191 default:
192 ALOGE("setDeviceConnectionState() invalid state: %x", state);
193 return BAD_VALUE;
194 }
195
Mikhail Naganov37977152018-07-11 15:54:44 -0700196 checkForDeviceAndOutputChanges([&]() {
197 // outputs must be closed after checkOutputForAllStrategies() is executed
198 if (!outputs.isEmpty()) {
199 for (audio_io_handle_t output : outputs) {
200 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
201 // close unused outputs after device disconnection or direct outputs that have been
202 // opened by checkOutputsForDevice() to query dynamic parameters
203 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
204 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
205 (desc->mDirectOpenCount == 0))) {
206 closeOutput(output);
207 }
Eric Laurente552edb2014-03-10 17:42:56 -0700208 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700209 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
210 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700211 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700212 return false;
213 });
Eric Laurente552edb2014-03-10 17:42:56 -0700214
Eric Laurent87ffa392015-05-22 10:32:38 -0700215 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700216 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
217 updateCallRouting(newDevice);
218 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100219 const audio_devices_t msdOutDevice = getMsdAudioOutDeviceTypes();
Eric Laurente552edb2014-03-10 17:42:56 -0700220 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700221 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
222 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
223 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700224 // do not force device change on duplicated output because if device is 0, it will
225 // also force a device 0 for the two outputs it is duplicated to which may override
226 // a valid device selection on those outputs.
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100227 bool force = (msdOutDevice == AUDIO_DEVICE_NONE || msdOutDevice != desc->device())
228 && !desc->isDuplicated()
François Gaffie53615e22015-03-19 09:24:12 +0100229 && (!device_distinguishes_on_address(device)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700230 // always force when disconnecting (a non-duplicated device)
231 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
Eric Laurentc75307b2015-03-17 15:29:32 -0700232 setOutputDevice(desc, newDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700233 }
Eric Laurente552edb2014-03-10 17:42:56 -0700234 }
235
Eric Laurentd60560a2015-04-10 11:31:20 -0700236 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
237 cleanUpForDevice(devDesc);
238 }
239
Eric Laurent72aa32f2014-05-30 18:51:48 -0700240 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700241 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700242 } // end if is output device
243
Eric Laurente552edb2014-03-10 17:42:56 -0700244 // handle input devices
245 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700246 SortedVector <audio_io_handle_t> inputs;
247
Eric Laurent3a4311c2014-03-17 12:00:47 -0700248 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700249 switch (state)
250 {
251 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700252 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700253 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700254 ALOGW("setDeviceConnectionState() device already connected: %d", device);
255 return INVALID_OPERATION;
256 }
François Gaffie53615e22015-03-19 09:24:12 +0100257 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700258 if (module == NULL) {
259 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
260 device);
261 return INVALID_OPERATION;
262 }
François Gaffie44481e72016-04-20 07:49:57 +0200263
264 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
265 // parameters on newly connected devices (instead of opening the inputs...)
266 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
267
Paul McLean9080a4c2015-06-18 08:24:02 -0700268 if (checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress) != NO_ERROR) {
François Gaffie44481e72016-04-20 07:49:57 +0200269 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
270 devDesc->mAddress);
Eric Laurentd4692962014-05-05 18:13:44 -0700271 return INVALID_OPERATION;
272 }
273
Eric Laurent3a4311c2014-03-17 12:00:47 -0700274 index = mAvailableInputDevices.add(devDesc);
275 if (index >= 0) {
Paul McLeane743a472015-01-28 11:07:31 -0800276 mAvailableInputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700277 } else {
278 return NO_MEMORY;
279 }
Eric Laurent3ae5f312015-02-03 17:12:08 -0800280
François Gaffie2110e042015-03-24 08:41:51 +0100281 // Propagate device availability to Engine
282 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700283 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700284
285 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700286 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700287 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700288 ALOGW("setDeviceConnectionState() device not connected: %d", device);
289 return INVALID_OPERATION;
290 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700291
292 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
293
294 // Set Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200295 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700296
Paul McLean9080a4c2015-06-18 08:24:02 -0700297 checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700298 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700299
François Gaffie2110e042015-03-24 08:41:51 +0100300 // Propagate device availability to Engine
301 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700302 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700303
304 default:
305 ALOGE("setDeviceConnectionState() invalid state: %x", state);
306 return BAD_VALUE;
307 }
308
Eric Laurentd4692962014-05-05 18:13:44 -0700309 closeAllInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700310 // As the input device list can impact the output device selection, update
311 // getDeviceForStrategy() cache
312 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700313
Eric Laurent87ffa392015-05-22 10:32:38 -0700314 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700315 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
316 updateCallRouting(newDevice);
317 }
318
Eric Laurentd60560a2015-04-10 11:31:20 -0700319 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
320 cleanUpForDevice(devDesc);
321 }
322
Eric Laurentb52c1522014-05-20 11:27:36 -0700323 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700324 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700325 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700326
327 ALOGW("setDeviceConnectionState() invalid device: %x", device);
328 return BAD_VALUE;
329}
330
Eric Laurente0720872014-03-11 09:30:41 -0700331audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100332 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700333{
Eric Laurent634b7142016-04-20 13:48:02 -0700334 sp<DeviceDescriptor> devDesc =
335 mHwModules.getDeviceDescriptor(device, device_address, "",
336 (strlen(device_address) != 0)/*matchAddress*/);
337
338 if (devDesc == 0) {
339 ALOGW("getDeviceConnectionState() undeclared device, type %08x, address: %s",
340 device, device_address);
341 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
342 }
François Gaffie53615e22015-03-19 09:24:12 +0100343
Eric Laurent3a4311c2014-03-17 12:00:47 -0700344 DeviceVector *deviceVector;
345
Eric Laurente552edb2014-03-10 17:42:56 -0700346 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700347 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700348 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700349 deviceVector = &mAvailableInputDevices;
350 } else {
351 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
352 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700353 }
Eric Laurent634b7142016-04-20 13:48:02 -0700354
355 return (deviceVector->getDevice(device, String8(device_address)) != 0) ?
356 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800357}
358
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800359status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
360 const char *device_address,
361 const char *device_name)
362{
363 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700364 String8 reply;
365 AudioParameter param;
366 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800367
368 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s",
369 device, device_address, device_name);
370
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800371 // connect/disconnect only 1 device at a time
372 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
373
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800374 // Check if the device is currently connected
375 sp<DeviceDescriptor> devDesc =
376 mHwModules.getDeviceDescriptor(device, device_address, device_name);
377 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
378 if (index < 0) {
379 // Nothing to do: device is not connected
380 return NO_ERROR;
381 }
382
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700383 // For offloaded A2DP, Hw modules may have the capability to
384 // configure codecs. Check if any of the loaded hw modules
385 // supports this.
386 // If supported, send a set parameter to configure A2DP codecs
387 // and return. No need to toggle device state.
388 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
389 reply = mpClientInterface->getParameters(
390 AUDIO_IO_HANDLE_NONE,
391 String8(AudioParameter::keyReconfigA2dpSupported));
392 AudioParameter repliedParameters(reply);
393 repliedParameters.getInt(
394 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
395 if (isReconfigA2dpSupported) {
396 const String8 key(AudioParameter::keyReconfigA2dp);
397 param.add(key, String8("true"));
398 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
399 return NO_ERROR;
400 }
401 }
402
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800403 // Toggle the device state: UNAVAILABLE -> AVAILABLE
404 // This will force reading again the device configuration
405 status = setDeviceConnectionState(device,
406 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
407 device_address, device_name);
408 if (status != NO_ERROR) {
409 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
410 status);
411 return status;
412 }
413
414 status = setDeviceConnectionState(device,
415 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
416 device_address, device_name);
417 if (status != NO_ERROR) {
418 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
419 status);
420 return status;
421 }
422
423 return NO_ERROR;
424}
425
Eric Laurentdc462862016-07-19 12:29:53 -0700426uint32_t AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700427{
428 bool createTxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700429 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700430
Andy Hunga76c7de2016-12-13 19:14:31 -0800431 if(!hasPrimaryOutput() || mPrimaryOutput->device() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurentdc462862016-07-19 12:29:53 -0700432 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700433 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800434 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700435 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
436
437 // release existing RX patch if any
438 if (mCallRxPatch != 0) {
439 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
440 mCallRxPatch.clear();
441 }
442 // release TX patch if any
443 if (mCallTxPatch != 0) {
444 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
445 mCallTxPatch.clear();
446 }
447
448 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
449 // via setOutputDevice() on primary output.
450 // Otherwise, create two audio patches for TX and RX path.
451 if (availablePrimaryOutputDevices() & rxDevice) {
Eric Laurentdc462862016-07-19 12:29:53 -0700452 muteWaitMs = setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700453 // If the TX device is also on the primary HW module, setOutputDevice() will take care
454 // of it due to legacy implementation. If not, create a patch.
455 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
456 == AUDIO_DEVICE_NONE) {
457 createTxPatch = true;
458 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700459 } else { // create RX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800460 mCallRxPatch = createTelephonyPatch(true /*isRx*/, rxDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700461 createTxPatch = true;
462 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700463 if (createTxPatch) { // create TX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800464 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txDevice, delayMs);
465 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700466
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800467 return muteWaitMs;
468}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700469
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800470sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
471 bool isRx, audio_devices_t device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700472 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700473
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800474 sp<DeviceDescriptor> txSourceDeviceDesc;
475 if (isRx) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700476 patchBuilder.addSink(findDevice(mAvailableOutputDevices, device)).
477 addSource(findDevice(mAvailableInputDevices, AUDIO_DEVICE_IN_TELEPHONY_RX));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800478 } else {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700479 patchBuilder.addSource(txSourceDeviceDesc = findDevice(mAvailableInputDevices, device)).
480 addSink(findDevice(mAvailableOutputDevices, AUDIO_DEVICE_OUT_TELEPHONY_TX));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800481 }
482
483 audio_devices_t outputDevice = isRx ? device : AUDIO_DEVICE_OUT_TELEPHONY_TX;
484 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(outputDevice, mOutputs);
485 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
486 // request to reuse existing output stream if one is already opened to reach the target device
487 if (output != AUDIO_IO_HANDLE_NONE) {
488 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
489 ALOG_ASSERT(!outputDesc->isDuplicated(),
490 "%s() %#x device output %d is duplicated", __func__, outputDevice, output);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700491 patchBuilder.addSource(outputDesc, { .stream = AUDIO_STREAM_PATCH });
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800492 }
493
494 if (!isRx) {
Eric Laurentc0a889f2015-10-14 14:36:34 -0700495 // terminate active capture if on the same HW module as the call TX source device
496 // FIXME: would be better to refine to only inputs whose profile connects to the
497 // call TX device but this information is not in the audio patch and logic here must be
498 // symmetric to the one in startInput()
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800499 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800500 if (activeDesc->hasSameHwModuleAs(txSourceDeviceDesc)) {
Eric Laurent8f42ea12018-08-08 09:08:25 -0700501 closeActiveClients(activeDesc);
Eric Laurentc0a889f2015-10-14 14:36:34 -0700502 }
503 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700504 }
Eric Laurentdc462862016-07-19 12:29:53 -0700505
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800506 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Mikhail Naganovdc769682018-05-04 15:34:08 -0700507 status_t status = mpClientInterface->createAudioPatch(
508 patchBuilder.patch(), &afPatchHandle, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800509 ALOGW_IF(status != NO_ERROR,
510 "%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
511 sp<AudioPatch> audioPatch;
512 if (status == NO_ERROR) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700513 audioPatch = new AudioPatch(patchBuilder.patch(), mUidCached);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800514 audioPatch->mAfPatchHandle = afPatchHandle;
515 audioPatch->mUid = mUidCached;
516 }
517 return audioPatch;
518}
519
Mikhail Naganovdc769682018-05-04 15:34:08 -0700520sp<DeviceDescriptor> AudioPolicyManager::findDevice(
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100521 const DeviceVector& devices, audio_devices_t device) const {
Mikhail Naganov708e0382018-05-30 09:53:04 -0700522 DeviceVector deviceList = devices.getDevicesFromTypeMask(device);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800523 ALOG_ASSERT(!deviceList.isEmpty(),
524 "%s() selected device type %#x is not in devices list", __func__, device);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700525 return deviceList.itemAt(0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700526}
527
Eric Laurente0720872014-03-11 09:30:41 -0700528void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700529{
530 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100531 // store previous phone state for management of sonification strategy below
532 int oldState = mEngine->getPhoneState();
533
534 if (mEngine->setPhoneState(state) != NO_ERROR) {
535 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700536 return;
537 }
François Gaffie2110e042015-03-24 08:41:51 +0100538 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700539 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700540 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700541 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800542 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700543 }
544
François Gaffie2110e042015-03-24 08:41:51 +0100545 /**
546 * Switching to or from incall state or switching between telephony and VoIP lead to force
547 * routing command.
548 */
549 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
550 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700551
552 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700553 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700554
Eric Laurente552edb2014-03-10 17:42:56 -0700555 int delayMs = 0;
556 if (isStateInCall(state)) {
557 nsecs_t sysTime = systemTime();
558 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700559 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700560 // mute media and sonification strategies and delay device switch by the largest
561 // latency of any output where either strategy is active.
562 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100563 if ((isStrategyActive(desc, STRATEGY_MEDIA,
564 SONIFICATION_HEADSET_MUSIC_DELAY,
565 sysTime) ||
566 isStrategyActive(desc, STRATEGY_SONIFICATION,
567 SONIFICATION_HEADSET_MUSIC_DELAY,
568 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700569 (delayMs < (int)desc->latency()*2)) {
570 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700571 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700572 setStrategyMute(STRATEGY_MEDIA, true, desc);
573 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700574 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700575 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
576 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700577 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
578 }
579 }
580
Eric Laurent87ffa392015-05-22 10:32:38 -0700581 if (hasPrimaryOutput()) {
582 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
583 // the device returned is not necessarily reachable via this output
584 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
585 // force routing command to audio hardware when ending call
586 // even if no device change is needed
587 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
588 rxDevice = mPrimaryOutput->device();
589 }
Eric Laurente552edb2014-03-10 17:42:56 -0700590
Eric Laurent87ffa392015-05-22 10:32:38 -0700591 if (state == AUDIO_MODE_IN_CALL) {
592 updateCallRouting(rxDevice, delayMs);
593 } else if (oldState == AUDIO_MODE_IN_CALL) {
594 if (mCallRxPatch != 0) {
595 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
596 mCallRxPatch.clear();
597 }
598 if (mCallTxPatch != 0) {
599 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
600 mCallTxPatch.clear();
601 }
602 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
603 } else {
604 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700605 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700606 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700607
608 // reevaluate routing on all outputs in case tracks have been started during the call
609 for (size_t i = 0; i < mOutputs.size(); i++) {
610 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
611 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
612 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
Yung Ti Suf60c8242018-05-10 18:07:26 +0800613 setOutputDevice(desc, newDevice, (newDevice != AUDIO_DEVICE_NONE), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700614 }
615 }
616
Eric Laurente552edb2014-03-10 17:42:56 -0700617 if (isStateInCall(state)) {
618 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700619 // force reevaluating accessibility routing when call starts
620 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700621 }
622
623 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700624 if (state == AUDIO_MODE_RINGTONE &&
625 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700626 mLimitRingtoneVolume = true;
627 } else {
628 mLimitRingtoneVolume = false;
629 }
630}
631
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700632audio_mode_t AudioPolicyManager::getPhoneState() {
633 return mEngine->getPhoneState();
634}
635
Eric Laurente0720872014-03-11 09:30:41 -0700636void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700637 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700638{
François Gaffie2110e042015-03-24 08:41:51 +0100639 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700640 if (config == mEngine->getForceUse(usage)) {
641 return;
642 }
Eric Laurente552edb2014-03-10 17:42:56 -0700643
François Gaffie2110e042015-03-24 08:41:51 +0100644 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
645 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
646 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700647 }
François Gaffie2110e042015-03-24 08:41:51 +0100648 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
649 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
650 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700651
652 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700653 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800654
Eric Laurentdc462862016-07-19 12:29:53 -0700655 //FIXME: workaround for truncated touch sounds
656 // to be removed when the problem is handled by system UI
657 uint32_t delayMs = 0;
658 uint32_t waitMs = 0;
659 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
660 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
661 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700662 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700663 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
Eric Laurentdc462862016-07-19 12:29:53 -0700664 waitMs = updateCallRouting(newDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700665 }
Eric Laurente552edb2014-03-10 17:42:56 -0700666 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700667 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
668 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
669 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700670 waitMs = setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE),
671 delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700672 }
Eric Laurente552edb2014-03-10 17:42:56 -0700673 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700674 applyStreamVolumes(outputDesc, newDevice, waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700675 }
676 }
677
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800678 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800679 audio_devices_t newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700680 // Force new input selection if the new device can not be reached via current input
Eric Laurentfb66dd92016-01-28 18:32:03 -0800681 if (activeDesc->mProfile->getSupportedDevices().types() &
682 (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
683 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700684 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800685 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700686 }
Eric Laurente552edb2014-03-10 17:42:56 -0700687 }
Eric Laurente552edb2014-03-10 17:42:56 -0700688}
689
Eric Laurente0720872014-03-11 09:30:41 -0700690void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700691{
692 ALOGV("setSystemProperty() property %s, value %s", property, value);
693}
694
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);
752 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
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);
1067 output = selectOutput(outputs, *flags, config->format);
Eric Laurente552edb2014-03-10 17:42:56 -07001068 }
Eric Laurentf4e63452017-11-06 19:31:46 +00001069 ALOGW_IF((output == 0), "getOutputForDevice() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001070 "sampling rate %d, format %#x, channels %#x, flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +02001071 stream, config->sample_rate, config->format, config->channel_mask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001072
Eric Laurente552edb2014-03-10 17:42:56 -07001073 return output;
1074}
1075
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001076sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001077 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001078 if (msdModule != 0) {
1079 DeviceVector msdInputDevices = mAvailableInputDevices.getDevicesFromHwModule(
1080 msdModule->getHandle());
1081 if (!msdInputDevices.isEmpty()) return msdInputDevices.itemAt(0);
1082 }
1083 return 0;
1084}
1085
1086audio_devices_t AudioPolicyManager::getMsdAudioOutDeviceTypes() const {
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001087 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001088 if (msdModule != 0) {
1089 return mAvailableOutputDevices.getDeviceTypesFromHwModule(msdModule->getHandle());
1090 }
1091 return AUDIO_DEVICE_NONE;
1092}
1093
1094const AudioPatchCollection AudioPolicyManager::getMsdPatches() const {
1095 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001096 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1097 if (msdModule != 0) {
1098 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1099 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1100 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1101 const struct audio_port_config *source = &patch->mPatch.sources[j];
1102 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1103 source->ext.device.hw_module == msdModule->getHandle()) {
1104 msdPatches.addAudioPatch(patch->mHandle, patch);
1105 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001106 }
1107 }
1108 }
1109 return msdPatches;
1110}
1111
1112status_t AudioPolicyManager::getBestMsdAudioProfileFor(audio_devices_t outputDevice,
1113 bool hwAvSync, audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1114{
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001115 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001116 if (msdModule == nullptr) {
1117 ALOGE("%s() unable to get MSD module", __func__);
1118 return NO_INIT;
1119 }
1120 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(outputDevice);
1121 if (deviceModule == nullptr) {
1122 ALOGE("%s() unable to get module for %#x", __func__, outputDevice);
1123 return NO_INIT;
1124 }
1125 const InputProfileCollection &inputProfiles = msdModule->getInputProfiles();
1126 if (inputProfiles.isEmpty()) {
1127 ALOGE("%s() no input profiles for MSD module", __func__);
1128 return NO_INIT;
1129 }
1130 const OutputProfileCollection &outputProfiles = deviceModule->getOutputProfiles();
1131 if (outputProfiles.isEmpty()) {
1132 ALOGE("%s() no output profiles for device %#x", __func__, outputDevice);
1133 return NO_INIT;
1134 }
1135 AudioProfileVector msdProfiles;
1136 // Each IOProfile represents a MixPort from audio_policy_configuration.xml
1137 for (const auto &inProfile : inputProfiles) {
1138 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0)) {
1139 msdProfiles.appendVector(inProfile->getAudioProfiles());
1140 }
1141 }
1142 AudioProfileVector deviceProfiles;
1143 for (const auto &outProfile : outputProfiles) {
1144 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0)) {
1145 deviceProfiles.appendVector(outProfile->getAudioProfiles());
1146 }
1147 }
1148 struct audio_config_base bestSinkConfig;
1149 status_t result = msdProfiles.findBestMatchingOutputConfig(deviceProfiles,
1150 compressedFormatsOrder, surroundChannelMasksOrder, true /*preferHigherSamplingRates*/,
1151 &bestSinkConfig);
1152 if (result != NO_ERROR) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001153 ALOGD("%s() no matching profiles found for device: %#x, hwAvSync: %d",
1154 __func__, outputDevice, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001155 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001156 }
1157 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1158 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1159 sinkConfig->format = bestSinkConfig.format;
1160 // For encoded streams force direct flag to prevent downstream mixing.
1161 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1162 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
1163 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1164 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1165 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1166 sourceConfig->format = bestSinkConfig.format;
1167 // Copy input stream directly without any processing (e.g. resampling).
1168 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1169 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1170 if (hwAvSync) {
1171 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1172 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1173 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1174 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1175 }
1176 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1177 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1178 sinkConfig->config_mask |= config_mask;
1179 sourceConfig->config_mask |= config_mask;
1180 return NO_ERROR;
1181}
1182
1183PatchBuilder AudioPolicyManager::buildMsdPatch(audio_devices_t outputDevice) const
1184{
1185 PatchBuilder patchBuilder;
1186 patchBuilder.addSource(getMsdAudioInDevice()).
1187 addSink(findDevice(mAvailableOutputDevices, outputDevice));
1188 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1189 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
1190 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1191 // For now, we just forcefully try with HwAvSync first.
1192 status_t res = getBestMsdAudioProfileFor(outputDevice, true /*hwAvSync*/,
1193 &sourceConfig, &sinkConfig) == NO_ERROR ? NO_ERROR :
1194 getBestMsdAudioProfileFor(
1195 outputDevice, false /*hwAvSync*/, &sourceConfig, &sinkConfig);
1196 if (res == NO_ERROR) {
1197 // Found a matching profile for encoded audio. Re-create PatchBuilder with this config.
1198 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1199 }
1200 ALOGV("%s() no matching profile found. Fall through to default PCM patch"
1201 " supporting PCM format conversion.", __func__);
1202 return patchBuilder;
1203}
1204
1205status_t AudioPolicyManager::setMsdPatch(audio_devices_t outputDevice) {
1206 ALOGV("%s() for outputDevice %#x", __func__, outputDevice);
1207 if (outputDevice == AUDIO_DEVICE_NONE) {
1208 // Use media strategy for unspecified output device. This should only
1209 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1210 // therefore invalidate explicit routing requests.
1211 outputDevice = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
1212 }
1213 PatchBuilder patchBuilder = buildMsdPatch(outputDevice);
1214 const struct audio_patch* patch = patchBuilder.patch();
1215 const AudioPatchCollection msdPatches = getMsdPatches();
1216 if (!msdPatches.isEmpty()) {
1217 LOG_ALWAYS_FATAL_IF(msdPatches.size() > 1,
1218 "The current MSD prototype only supports one output patch");
1219 sp<AudioPatch> currentPatch = msdPatches.valueAt(0);
1220 if (audio_patches_are_equal(&currentPatch->mPatch, patch)) {
1221 return NO_ERROR;
1222 }
1223 releaseAudioPatch(currentPatch->mHandle, mUidCached);
1224 }
1225 status_t status = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1226 patch, 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1227 ALOGE_IF(status != NO_ERROR, "%s() error %d creating MSD audio patch", __func__, status);
1228 ALOGI_IF(status == NO_ERROR, "%s() Patch created from MSD_IN to "
1229 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__, outputDevice,
1230 patch->sources[0].format, patch->sources[0].channel_mask, patch->sources[0].sample_rate);
1231 return status;
1232}
1233
Eric Laurente0720872014-03-11 09:30:41 -07001234audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001235 audio_output_flags_t flags,
1236 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001237{
1238 // select one output among several that provide a path to a particular device or set of
1239 // devices (the list was previously build by getOutputsForDevice()).
1240 // The priority is as follows:
1241 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001242 // 2: the output with the bit depth the closest to the requested one
1243 // 3: the primary output
1244 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001245
1246 if (outputs.size() == 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001247 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001248 }
1249 if (outputs.size() == 1) {
1250 return outputs[0];
1251 }
1252
1253 int maxCommonFlags = 0;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001254 audio_io_handle_t outputForFlags = AUDIO_IO_HANDLE_NONE;
1255 audio_io_handle_t outputForPrimary = AUDIO_IO_HANDLE_NONE;
1256 audio_io_handle_t outputForFormat = AUDIO_IO_HANDLE_NONE;
Eric Laurente6930022016-02-11 10:20:40 -08001257 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1258 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001259
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001260 for (audio_io_handle_t output : outputs) {
1261 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001262 if (!outputDesc->isDuplicated()) {
chenhg1794d712018-10-09 15:20:37 -07001263 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1264 continue;
1265 }
Eric Laurent8838a382014-09-08 16:44:28 -07001266 // if a valid format is specified, skip output if not compatible
1267 if (format != AUDIO_FORMAT_INVALID) {
chenhg1794d712018-10-09 15:20:37 -07001268 if (!audio_is_linear_pcm(format)) {
Eric Laurent8838a382014-09-08 16:44:28 -07001269 continue;
1270 }
Eric Laurente6930022016-02-11 10:20:40 -08001271 if (AudioPort::isBetterFormatMatch(
1272 outputDesc->mFormat, bestFormat, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001273 outputForFormat = output;
Eric Laurente6930022016-02-11 10:20:40 -08001274 bestFormat = outputDesc->mFormat;
1275 }
Eric Laurent8838a382014-09-08 16:44:28 -07001276 }
1277
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001278 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001279 if (commonFlags >= maxCommonFlags) {
1280 if (commonFlags == maxCommonFlags) {
Andy Hungc9901522017-11-10 20:07:54 -08001281 if (format != AUDIO_FORMAT_INVALID
1282 && AudioPort::isBetterFormatMatch(
1283 outputDesc->mFormat, bestFormatForFlags, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001284 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001285 bestFormatForFlags = outputDesc->mFormat;
1286 }
1287 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001288 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001289 maxCommonFlags = commonFlags;
1290 bestFormatForFlags = outputDesc->mFormat;
1291 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001292 ALOGV("selectOutput() commonFlags for output %d, %04x", output, commonFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001293 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001294 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001295 outputForPrimary = output;
Eric Laurente552edb2014-03-10 17:42:56 -07001296 }
1297 }
1298 }
1299
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001300 if (outputForFlags != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001301 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001302 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001303 if (outputForFormat != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001304 return outputForFormat;
1305 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001306 if (outputForPrimary != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001307 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001308 }
1309
1310 return outputs[0];
1311}
1312
Eric Laurent8fc147b2018-07-22 19:13:55 -07001313status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001314{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001315 ALOGV("%s portId %d", __FUNCTION__, portId);
1316
1317 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1318 if (outputDesc == 0) {
1319 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001320 return BAD_VALUE;
1321 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001322 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001323
Eric Laurent8fc147b2018-07-22 19:13:55 -07001324 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001325 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001326
Eric Laurent733ce942017-12-07 12:18:25 -08001327 status_t status = outputDesc->start();
1328 if (status != NO_ERROR) {
1329 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001330 }
1331
Eric Laurent97ac8712018-07-27 18:59:02 -07001332 uint32_t delayMs;
1333 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001334
1335 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001336 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001337 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001338 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001339 if (delayMs != 0) {
1340 usleep(delayMs * 1000);
1341 }
1342
1343 return status;
1344}
1345
Eric Laurent97ac8712018-07-27 18:59:02 -07001346status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1347 const sp<TrackClientDescriptor>& client,
1348 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001349{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001350 // cannot start playback of STREAM_TTS if any other output is being used
1351 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001352
1353 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001354 audio_stream_type_t stream = client->stream();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001355 if (stream == AUDIO_STREAM_TTS) {
1356 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001357 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001358 return INVALID_OPERATION;
1359 } else {
1360 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1361 }
1362 } else {
1363 // some playback other than beacon starts
1364 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1365 }
1366
Eric Laurent77305a62016-07-25 16:39:22 -07001367 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001368 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001369 bool force = !outputDesc->isActive() &&
1370 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001371
Eric Laurent97ac8712018-07-27 18:59:02 -07001372 audio_devices_t device = AUDIO_DEVICE_NONE;
1373 AudioMix *policyMix = NULL;
1374 const char *address = NULL;
1375 if (outputDesc->mPolicyMix != NULL) {
1376 policyMix = outputDesc->mPolicyMix;
1377 address = policyMix->mDeviceAddress.string();
1378 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1379 device = policyMix->mDeviceType;
1380 } else {
1381 device = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1382 }
1383 }
1384
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001385 // requiresMuteCheck is false when we can bypass mute strategy.
1386 // It covers a common case when there is no materially active audio
1387 // and muting would result in unnecessary delay and dropped audio.
1388 const uint32_t outputLatencyMs = outputDesc->latency();
1389 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1390
Eric Laurente552edb2014-03-10 17:42:56 -07001391 // increment usage count for this stream on the requested output:
1392 // NOTE that the usage count is the same for duplicated output and hardware output which is
1393 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001394 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001395
1396 if (client->hasPreferredDevice(true)) {
1397 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
1398 if (device != outputDesc->device()) {
1399 checkStrategyRoute(getStrategy(stream), outputDesc->mIoHandle);
1400 }
1401 }
Eric Laurente552edb2014-03-10 17:42:56 -07001402
Eric Laurent36829f92017-04-07 19:04:42 -07001403 if (stream == AUDIO_STREAM_MUSIC) {
1404 selectOutputForMusicEffects();
1405 }
1406
Eric Laurent592dd7b2018-08-05 18:58:48 -07001407 if (outputDesc->streamActiveCount(stream) == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001408 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001409 if (device == AUDIO_DEVICE_NONE) {
1410 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001411 }
Eric Laurent36829f92017-04-07 19:04:42 -07001412
Eric Laurente552edb2014-03-10 17:42:56 -07001413 routing_strategy strategy = getStrategy(stream);
1414 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001415 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1416 (beaconMuteLatency > 0);
1417 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001418 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001419 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001420 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001421 // An output has a shared device if
1422 // - managed by the same hw module
1423 // - supports the currently selected device
1424 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
1425 && (desc->supportedDevices() & device) != AUDIO_DEVICE_NONE;
1426
Eric Laurent77305a62016-07-25 16:39:22 -07001427 // force a device change if any other output is:
1428 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001429 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001430 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001431 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001432 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001433 // change the device currently selected by the other output.
1434 if (sharedDevice &&
Eric Laurent77305a62016-07-25 16:39:22 -07001435 desc->device() != device &&
Eric Laurent77305a62016-07-25 16:39:22 -07001436 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001437 force = true;
1438 }
1439 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001440 // a notification so that audio focus effect can propagate, or that a mute/unmute
1441 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001442 const uint32_t latencyMs = desc->latency();
1443 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1444
1445 if (shouldWait && isActive && (waitMs < latencyMs)) {
1446 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001447 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001448
1449 // Require mute check if another output is on a shared device
1450 // and currently active to have proper drain and avoid pops.
1451 // Note restoring AudioTracks onto this output needs to invoke
1452 // a volume ramp if there is no mute.
1453 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001454 }
1455 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001456
1457 const uint32_t muteWaitMs =
1458 setOutputDevice(outputDesc, device, force, 0, NULL, address, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001459
Eric Laurente552edb2014-03-10 17:42:56 -07001460 // apply volume rules for current stream and device if necessary
1461 checkAndSetVolume(stream,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001462 mVolumeCurves->getVolumeIndex(stream, outputDesc->device()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001463 outputDesc,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001464 outputDesc->device());
Eric Laurente552edb2014-03-10 17:42:56 -07001465
1466 // update the outputs if starting an output with a stream that can affect notification
1467 // routing
1468 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001469
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001470 // force reevaluating accessibility routing when ringtone or alarm starts
1471 if (strategy == STRATEGY_SONIFICATION) {
1472 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1473 }
Eric Laurentdc462862016-07-19 12:29:53 -07001474
1475 if (waitMs > muteWaitMs) {
1476 *delayMs = waitMs - muteWaitMs;
1477 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001478
1479 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1480 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1481 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1482 // change occurs after the MixerThread starts and causes a stream volume
1483 // glitch.
1484 //
1485 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001486 }
Eric Laurentdc462862016-07-19 12:29:53 -07001487
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001488 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1489 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1490 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1491 }
1492
Eric Laurent97ac8712018-07-27 18:59:02 -07001493 // Automatically enable the remote submix input when output is started on a re routing mix
1494 // of type MIX_TYPE_RECORDERS
1495 if (audio_is_remote_submix_device(device) && policyMix != NULL &&
1496 policyMix->mMixType == MIX_TYPE_RECORDERS) {
1497 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1498 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1499 address,
1500 "remote-submix");
1501 }
1502
Eric Laurente552edb2014-03-10 17:42:56 -07001503 return NO_ERROR;
1504}
1505
Eric Laurent8fc147b2018-07-22 19:13:55 -07001506status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001507{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001508 ALOGV("%s portId %d", __FUNCTION__, portId);
1509
1510 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1511 if (outputDesc == 0) {
1512 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001513 return BAD_VALUE;
1514 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001515 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001516
Eric Laurent97ac8712018-07-27 18:59:02 -07001517 ALOGV("stopOutput() output %d, stream %d, session %d",
1518 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07001519
Eric Laurent97ac8712018-07-27 18:59:02 -07001520 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08001521
Eric Laurent733ce942017-12-07 12:18:25 -08001522 if (status == NO_ERROR ) {
1523 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001524 }
1525 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001526}
1527
Eric Laurent97ac8712018-07-27 18:59:02 -07001528status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1529 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07001530{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001531 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07001532 audio_stream_type_t stream = client->stream();
1533
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001534 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1535
Eric Laurent592dd7b2018-08-05 18:58:48 -07001536 if (outputDesc->streamActiveCount(stream) > 0) {
1537 if (outputDesc->streamActiveCount(stream) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001538 // Automatically disable the remote submix input when output is stopped on a
1539 // re routing mix of type MIX_TYPE_RECORDERS
1540 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1541 outputDesc->mPolicyMix != NULL &&
1542 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1543 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1544 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1545 outputDesc->mPolicyMix->mDeviceAddress,
1546 "remote-submix");
1547 }
1548 }
1549 bool forceDeviceUpdate = false;
1550 if (client->hasPreferredDevice(true)) {
1551 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1552 forceDeviceUpdate = true;
1553 }
1554
Eric Laurente552edb2014-03-10 17:42:56 -07001555 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07001556 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07001557
Eric Laurente552edb2014-03-10 17:42:56 -07001558 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001559 if (outputDesc->streamActiveCount(stream) == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001560 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001561 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001562 // delay the device switch by twice the latency because stopOutput() is executed when
1563 // the track stop() command is received and at that time the audio track buffer can
1564 // still contain data that needs to be drained. The latency only covers the audio HAL
1565 // and kernel buffers. Also the latency does not always include additional delay in the
1566 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001567 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001568
1569 // force restoring the device selection on other active outputs if it differs from the
1570 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001571 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001572 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001573 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001574 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001575 desc->isActive() &&
1576 outputDesc->sharesHwModuleWith(desc) &&
1577 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001578 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1579 bool force = desc->device() != newDevice2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001580
Eric Laurentc75307b2015-03-17 15:29:32 -07001581 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001582 newDevice2,
1583 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001584 delayMs);
1585 // re-apply device specific volume if not done by setOutputDevice()
1586 if (!force) {
1587 applyStreamVolumes(desc, newDevice2, delayMs);
1588 }
Eric Laurente552edb2014-03-10 17:42:56 -07001589 }
1590 }
1591 // update the outputs if stopping one with a stream that can affect notification routing
1592 handleNotificationRoutingForStream(stream);
1593 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001594
1595 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1596 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1597 setStrategyMute(STRATEGY_SONIFICATION, false, outputDesc);
1598 }
1599
Eric Laurent36829f92017-04-07 19:04:42 -07001600 if (stream == AUDIO_STREAM_MUSIC) {
1601 selectOutputForMusicEffects();
1602 }
Eric Laurente552edb2014-03-10 17:42:56 -07001603 return NO_ERROR;
1604 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001605 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001606 return INVALID_OPERATION;
1607 }
1608}
1609
Eric Laurent8fc147b2018-07-22 19:13:55 -07001610void AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001611{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001612 ALOGV("%s portId %d", __FUNCTION__, portId);
1613
1614 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1615 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07001616 // If an output descriptor is closed due to a device routing change,
1617 // then there are race conditions with releaseOutput from tracks
1618 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
1619 // destroyed shortly thereafter.
1620 //
1621 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07001622 ALOGW("releaseOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001623 return;
1624 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001625
1626 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001627
Eric Laurent8fc147b2018-07-22 19:13:55 -07001628 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1629 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001630 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07001631 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001632 return;
1633 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001634 if (--outputDesc->mDirectOpenCount == 0) {
1635 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07001636 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001637 }
1638 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001639 // stopOutput() needs to be successfully called before releaseOutput()
1640 // otherwise there may be inaccurate stream reference counts.
1641 // This is checked in outputDesc->removeClient below.
1642 outputDesc->removeClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001643}
1644
Eric Laurentcaf7f482014-11-25 17:50:47 -08001645status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1646 audio_io_handle_t *input,
1647 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001648 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001649 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001650 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001651 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001652 input_type_t *inputType,
1653 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001654{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001655 ALOGV("getInputForAttr() source %d, sampling rate %d, format %#x, channel mask %#x,"
Eric Laurentcaf7f482014-11-25 17:50:47 -08001656 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001657 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001658
Eric Laurentad2e7b92017-09-14 20:06:42 -07001659 status_t status = NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -08001660 // handle legacy remote submix case where the address was not always specified
1661 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001662 audio_source_t halInputSource;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001663 audio_source_t inputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001664 AudioMix *policyMix = NULL;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001665 DeviceVector inputDevices;
Eric Laurent8fc147b2018-07-22 19:13:55 -07001666 sp<AudioInputDescriptor> inputDesc;
1667 sp<RecordClientDescriptor> clientDesc;
1668 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001669 bool isSoundTrigger;
1670 audio_devices_t device;
1671
1672 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1673 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1674 return INVALID_OPERATION;
1675 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001676
Eric Laurentfe231122017-11-17 17:48:06 -08001677 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1678 inputSource = AUDIO_SOURCE_MIC;
1679 }
1680
Paul McLean466dc8e2015-04-17 13:15:36 -06001681 // Explicit routing?
1682 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -07001683 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
jiabinc0c831a2018-01-29 17:55:15 -08001684 deviceDesc = mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001685 }
Paul McLean466dc8e2015-04-17 13:15:36 -06001686
Eric Laurentad2e7b92017-09-14 20:06:42 -07001687 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1688 // possible
1689 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1690 *input != AUDIO_IO_HANDLE_NONE) {
1691 ssize_t index = mInputs.indexOfKey(*input);
1692 if (index < 0) {
1693 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1694 status = BAD_VALUE;
1695 goto error;
1696 }
1697 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001698 RecordClientVector clients = inputDesc->getClientsForSession(session);
1699 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001700 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1701 status = BAD_VALUE;
1702 goto error;
1703 }
1704 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1705 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001706 // corresponds to a new client and is only permitted from the same UID.
1707 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07001708 if (clients.size() > 1) {
1709 for (const auto& client : clients) {
1710 // The client map is ordered by key values (portId) and portIds are allocated
1711 // incrementaly. So the first client in this list is the one opened by audio flinger
1712 // when the mmap stream is created and should be ignored as it does not correspond
1713 // to an actual client
1714 if (client == *clients.cbegin()) {
1715 continue;
1716 }
1717 if (uid != client->uid() && !client->isSilenced()) {
1718 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
1719 uid, client->portId(), client->uid());
1720 status = INVALID_OPERATION;
1721 goto error;
1722 }
Eric Laurent331679c2018-04-16 17:03:16 -07001723 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001724 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001725 *inputType = API_INPUT_LEGACY;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001726 device = inputDesc->mDevice;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001727
Eric Laurent8f42ea12018-08-08 09:08:25 -07001728 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001729 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001730 }
1731
1732 *input = AUDIO_IO_HANDLE_NONE;
1733 *inputType = API_INPUT_INVALID;
1734
Eric Laurentad2e7b92017-09-14 20:06:42 -07001735 halInputSource = inputSource;
1736
Eric Laurentc447ded2015-01-06 08:47:05 -08001737 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001738 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001739 status = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
1740 if (status != NO_ERROR) {
1741 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001742 }
1743 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001744 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1745 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001746 } else {
Eric Laurent97ac8712018-07-27 18:59:02 -07001747 if (deviceDesc != 0) {
1748 device = deviceDesc->type();
1749 } else {
1750 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
1751 }
Eric Laurent275e8e92014-11-30 15:14:47 -08001752 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001753 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001754 status = BAD_VALUE;
1755 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001756 }
Eric Laurentc722f302014-12-10 11:21:49 -08001757 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001758 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001759 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1760 // there is an external policy, but this input is attached to a mix of recorders,
1761 // meaning it receives audio injected into the framework, so the recorder doesn't
1762 // know about it and is therefore considered "legacy"
1763 *inputType = API_INPUT_LEGACY;
1764 } else {
1765 // recording a mix of players defined by an external policy, we're rerouting for
1766 // an external policy
1767 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1768 }
Eric Laurentc722f302014-12-10 11:21:49 -08001769 } else if (audio_is_remote_submix_device(device)) {
1770 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001771 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001772 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1773 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001774 } else {
1775 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001776 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001777
Eric Laurent599c7582015-12-07 18:05:55 -08001778 }
1779
Eric Laurent8f42ea12018-08-08 09:08:25 -07001780 *input = getInputForDevice(device, address, session, inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001781 config, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001782 policyMix);
1783 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001784 status = INVALID_OPERATION;
1785 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001786 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001787
Eric Laurent8f42ea12018-08-08 09:08:25 -07001788exit:
1789
Mikhail Naganov708e0382018-05-30 09:53:04 -07001790 inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -07001791 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
Eric Laurent8f42ea12018-08-08 09:08:25 -07001792 : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07001793
Eric Laurent8f42ea12018-08-08 09:08:25 -07001794 isSoundTrigger = inputSource == AUDIO_SOURCE_HOTWORD &&
1795 mSoundTriggerSessions.indexOfKey(session) > 0;
1796 *portId = AudioPort::getNextUniqueId();
1797
Eric Laurent8fc147b2018-07-22 19:13:55 -07001798 clientDesc = new RecordClientDescriptor(*portId, uid, session,
Eric Laurent8f42ea12018-08-08 09:08:25 -07001799 *attr, *config, requestedDeviceId,
1800 inputSource,flags, isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001801 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07001802 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001803
1804 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
1805 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001806
Eric Laurent599c7582015-12-07 18:05:55 -08001807 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001808
1809error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07001810 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001811}
1812
1813
1814audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1815 String8 address,
1816 audio_session_t session,
Eric Laurent599c7582015-12-07 18:05:55 -08001817 audio_source_t inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001818 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08001819 audio_input_flags_t flags,
1820 AudioMix *policyMix)
1821{
1822 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1823 audio_source_t halInputSource = inputSource;
1824 bool isSoundTrigger = false;
1825
1826 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1827 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1828 if (index >= 0) {
1829 input = mSoundTriggerSessions.valueFor(session);
1830 isSoundTrigger = true;
1831 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1832 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1833 } else {
1834 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001835 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001836 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08001837 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001838 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001839 }
1840
Andy Hungf129b032015-04-07 13:45:50 -07001841 // find a compatible input profile (not necessarily identical in parameters)
1842 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08001843 // sampling rate and flags may be updated by getInputProfile
1844 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
1845 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07001846 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08001847 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07001848 audio_input_flags_t profileFlags = flags;
1849 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07001850 profileFormat = config->format; // reset each time through loop, in case it is updated
Eric Laurent275e8e92014-11-30 15:14:47 -08001851 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001852 profileSamplingRate, profileFormat, profileChannelMask,
1853 profileFlags);
1854 if (profile != 0) {
1855 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001856 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1857 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001858 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1859 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1860 } else { // fail
Glenn Kastenfaa10a62017-05-25 15:52:05 -07001861 ALOGW("getInputForDevice() could not find profile for device 0x%X, "
Eric Laurentfe231122017-11-17 17:48:06 -08001862 "sampling rate %u, format %#x, channel mask 0x%X, flags %#x",
1863 device, config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001864 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001865 }
Eric Laurente552edb2014-03-10 17:42:56 -07001866 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001867 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08001868 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08001869 if (samplingRate == 0) {
1870 samplingRate = profileSamplingRate;
1871 }
Eric Laurente552edb2014-03-10 17:42:56 -07001872
Eric Laurent322b4d22015-04-03 15:57:54 -07001873 if (profile->getModuleHandle() == 0) {
1874 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001875 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001876 }
1877
Eric Laurent3974e3b2017-12-07 17:58:43 -08001878 if (!profile->canOpenNewIo()) {
1879 return AUDIO_IO_HANDLE_NONE;
1880 }
1881
Eric Laurentfe231122017-11-17 17:48:06 -08001882 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001883
Eric Laurentfe231122017-11-17 17:48:06 -08001884 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
1885 lConfig.sample_rate = profileSamplingRate;
1886 lConfig.channel_mask = profileChannelMask;
1887 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07001888
Eric Laurent53b810e2017-12-10 17:25:10 -08001889 if (address == "") {
Mikhail Naganov708e0382018-05-30 09:53:04 -07001890 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -08001891 // the inputs vector must be of size >= 1, but we don't want to crash here
1892 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress : String8("");
1893 }
1894
Eric Laurentfe231122017-11-17 17:48:06 -08001895 status_t status = inputDesc->open(&lConfig, device, address,
1896 halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001897
1898 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001899 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08001900 (profileSamplingRate != lConfig.sample_rate) ||
1901 !audio_formats_match(profileFormat, lConfig.format) ||
1902 (profileChannelMask != lConfig.channel_mask)) {
1903 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001904 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08001905 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001906 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001907 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07001908 }
Eric Laurent599c7582015-12-07 18:05:55 -08001909 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001910 }
1911
Eric Laurentc722f302014-12-10 11:21:49 -08001912 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001913
Eric Laurent599c7582015-12-07 18:05:55 -08001914 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001915 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001916
Eric Laurent599c7582015-12-07 18:05:55 -08001917 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001918}
1919
Eric Laurentbb948092017-01-23 18:33:30 -08001920//static
1921bool AudioPolicyManager::isConcurrentSource(audio_source_t source)
1922{
1923 return (source == AUDIO_SOURCE_HOTWORD) ||
1924 (source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
1925 (source == AUDIO_SOURCE_FM_TUNER);
1926}
1927
Chris Thornton2b864642017-06-27 21:26:07 -07001928// FIXME: remove when concurrent capture is ready. This is a hack to work around bug b/63083537.
1929bool AudioPolicyManager::soundTriggerSupportsConcurrentCapture() {
1930 if (!mHasComputedSoundTriggerSupportsConcurrentCapture) {
1931 bool soundTriggerSupportsConcurrentCapture = false;
1932 unsigned int numModules = 0;
1933 struct sound_trigger_module_descriptor* nModules = NULL;
1934
1935 status_t status = SoundTrigger::listModules(nModules, &numModules);
1936 if (status == NO_ERROR && numModules != 0) {
1937 nModules = (struct sound_trigger_module_descriptor*) calloc(
1938 numModules, sizeof(struct sound_trigger_module_descriptor));
1939 if (nModules == NULL) {
1940 // We failed to malloc the buffer, so just say no for now, and hope that we have more
1941 // ram the next time this function is called.
1942 ALOGE("Failed to allocate buffer for module descriptors");
1943 return false;
1944 }
1945
1946 status = SoundTrigger::listModules(nModules, &numModules);
1947 if (status == NO_ERROR) {
1948 soundTriggerSupportsConcurrentCapture = true;
1949 for (size_t i = 0; i < numModules; ++i) {
1950 soundTriggerSupportsConcurrentCapture &=
1951 nModules[i].properties.concurrent_capture;
1952 }
1953 }
1954 free(nModules);
1955 }
1956 mSoundTriggerSupportsConcurrentCapture = soundTriggerSupportsConcurrentCapture;
1957 mHasComputedSoundTriggerSupportsConcurrentCapture = true;
1958 }
1959 return mSoundTriggerSupportsConcurrentCapture;
1960}
1961
Eric Laurentfb66dd92016-01-28 18:32:03 -08001962
Eric Laurent8fc147b2018-07-22 19:13:55 -07001963status_t AudioPolicyManager::startInput(audio_port_handle_t portId,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001964 bool silenced,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001965 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07001966{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001967 *concurrency = API_INPUT_CONCURRENCY_NONE;
1968
1969 ALOGV("%s portId %d", __FUNCTION__, portId);
1970
1971 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
1972 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07001973 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001974 return BAD_VALUE;
1975 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001976 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07001977 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001978 if (client->active()) {
1979 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
1980 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07001981 }
1982
Eric Laurent8f42ea12018-08-08 09:08:25 -07001983 audio_session_t session = client->session();
1984
1985 ALOGV("%s input:%d, session:%d, silenced:%d, concurrency:%d)",
1986 __FUNCTION__, input, session, silenced, *concurrency);
1987
Eric Laurent74708e72017-04-07 17:13:42 -07001988 if (!is_virtual_input_device(inputDesc->mDevice)) {
1989 if (mCallTxPatch != 0 &&
1990 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1991 ALOGW("startInput(%d) failed: call in progress", input);
Ray Essick84e84a52018-05-03 18:45:07 -07001992 *concurrency |= API_INPUT_CONCURRENCY_CALL;
Eric Laurent74708e72017-04-07 17:13:42 -07001993 return INVALID_OPERATION;
1994 }
1995
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001996 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07001997
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001998 // If a UID is idle and records silence and another not silenced recording starts
1999 // from another UID (idle or active) we stop the current idle UID recording in
2000 // favor of the new one - "There can be only one" TM
2001 if (!silenced) {
2002 for (const auto& activeDesc : activeInputs) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002003 if ((activeDesc->getAudioPort()->getFlags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002004 activeDesc->getId() == inputDesc->getId()) {
2005 continue;
2006 }
2007
Eric Laurent8f42ea12018-08-08 09:08:25 -07002008 RecordClientVector activeClients = activeDesc->clientsList(true /*activeOnly*/);
2009 for (const auto& activeClient : activeClients) {
2010 if (activeClient->isSilenced()) {
2011 closeClient(activeClient->portId());
2012 ALOGV("%s client %d stopping silenced client %d", __FUNCTION__,
2013 portId, activeClient->portId());
2014 activeInputs = mInputs.getActiveInputs();
2015 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002016 }
2017 }
2018 }
2019
2020 for (const auto& activeDesc : activeInputs) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002021 if ((client->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
Eric Laurentcb4dae22017-07-01 19:39:32 -07002022 activeDesc->getId() == inputDesc->getId()) {
2023 continue;
2024 }
2025
Eric Laurent74708e72017-04-07 17:13:42 -07002026 audio_source_t activeSource = activeDesc->inputSource(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002027 if (client->source() == AUDIO_SOURCE_HOTWORD) {
Eric Laurent74708e72017-04-07 17:13:42 -07002028 if (activeSource == AUDIO_SOURCE_HOTWORD) {
2029 if (activeDesc->hasPreemptedSession(session)) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002030 ALOGW("%s input %d failed for HOTWORD: "
2031 "other input %d already started for HOTWORD", __FUNCTION__,
Eric Laurent74708e72017-04-07 17:13:42 -07002032 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07002033 *concurrency |= API_INPUT_CONCURRENCY_HOTWORD;
Eric Laurent74708e72017-04-07 17:13:42 -07002034 return INVALID_OPERATION;
2035 }
2036 } else {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002037 ALOGV("%s input %d failed for HOTWORD: other input %d already started",
2038 __FUNCTION__, input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07002039 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07002040 return INVALID_OPERATION;
2041 }
2042 } else {
2043 if (activeSource != AUDIO_SOURCE_HOTWORD) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002044 ALOGW("%s input %d failed: other input %d already started", __FUNCTION__,
Eric Laurent74708e72017-04-07 17:13:42 -07002045 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07002046 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07002047 return INVALID_OPERATION;
2048 }
2049 }
2050 }
2051
Chris Thornton2b864642017-06-27 21:26:07 -07002052 // We only need to check if the sound trigger session supports concurrent capture if the
2053 // input is also a sound trigger input. Otherwise, we should preempt any hotword stream
2054 // that's running.
2055 const bool allowConcurrentWithSoundTrigger =
2056 inputDesc->isSoundTrigger() ? soundTriggerSupportsConcurrentCapture() : false;
2057
Eric Laurent74708e72017-04-07 17:13:42 -07002058 // if capture is allowed, preempt currently active HOTWORD captures
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002059 for (const auto& activeDesc : activeInputs) {
Chris Thornton2b864642017-06-27 21:26:07 -07002060 if (allowConcurrentWithSoundTrigger && activeDesc->isSoundTrigger()) {
2061 continue;
2062 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002063 RecordClientVector activeHotwordClients =
2064 activeDesc->clientsList(true, AUDIO_SOURCE_HOTWORD);
2065 if (activeHotwordClients.size() > 0) {
Eric Laurent74708e72017-04-07 17:13:42 -07002066 SortedVector<audio_session_t> sessions = activeDesc->getPreemptedSessions();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002067
2068 for (const auto& activeClient : activeHotwordClients) {
2069 *concurrency |= API_INPUT_CONCURRENCY_PREEMPT;
2070 sessions.add(activeClient->session());
2071 closeClient(activeClient->portId());
2072 ALOGV("%s input %d for HOTWORD preempting HOTWORD input %d", __FUNCTION__,
2073 input, activeDesc->mIoHandle);
2074 }
2075
Eric Laurent74708e72017-04-07 17:13:42 -07002076 inputDesc->setPreemptedSessions(sessions);
Eric Laurent74708e72017-04-07 17:13:42 -07002077 }
2078 }
2079 }
Eric Laurente552edb2014-03-10 17:42:56 -07002080
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002081 // Make sure we start with the correct silence state
Eric Laurent8f42ea12018-08-08 09:08:25 -07002082 client->setSilenced(silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002083
Eric Laurent313d1e72016-01-29 09:56:57 -08002084 // increment activity count before calling getNewInputDevice() below as only active sessions
2085 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002086 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002087
Eric Laurent8f42ea12018-08-08 09:08:25 -07002088 // indicate active capture to sound trigger service if starting capture from a mic on
2089 // primary HW module
2090 audio_devices_t device = getNewInputDevice(inputDesc);
2091 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002092
Eric Laurent8f42ea12018-08-08 09:08:25 -07002093 status_t status = inputDesc->start();
2094 if (status != NO_ERROR) {
2095 inputDesc->setClientActive(client, false);
2096 return status;
2097 }
2098
2099 if (inputDesc->activeCount() == 1) {
2100 // if input maps to a dynamic policy with an activity listener, notify of state change
2101 if ((inputDesc->mPolicyMix != NULL)
2102 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2103 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2104 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002105 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002106
Eric Laurent8f42ea12018-08-08 09:08:25 -07002107 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2108 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2109 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
2110 SoundTrigger::setCaptureState(true);
2111 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002112
Eric Laurent8f42ea12018-08-08 09:08:25 -07002113 // automatically enable the remote submix output when input is started if not
2114 // used by a policy mix of type MIX_TYPE_RECORDERS
2115 // For remote submix (a virtual device), we open only one input per capture request.
2116 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2117 String8 address = String8("");
2118 if (inputDesc->mPolicyMix == NULL) {
2119 address = String8("0");
2120 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2121 address = inputDesc->mPolicyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002122 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002123 if (address != "") {
2124 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2125 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2126 address, "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08002127 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002128 }
Eric Laurente552edb2014-03-10 17:42:56 -07002129 }
2130
Eric Laurent8f42ea12018-08-08 09:08:25 -07002131 ALOGV("%s input %d source = %d exit", __FUNCTION__, input, client->source());
Eric Laurente552edb2014-03-10 17:42:56 -07002132
Eric Laurente552edb2014-03-10 17:42:56 -07002133 return NO_ERROR;
2134}
2135
Eric Laurent8fc147b2018-07-22 19:13:55 -07002136status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002137{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002138 ALOGV("%s portId %d", __FUNCTION__, portId);
2139
2140 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2141 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002142 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002143 return BAD_VALUE;
2144 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002145 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002146 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002147 if (!client->active()) {
2148 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002149 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002150 }
2151
Eric Laurent8f42ea12018-08-08 09:08:25 -07002152 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002153
Eric Laurent8f42ea12018-08-08 09:08:25 -07002154 inputDesc->stop();
2155 if (inputDesc->isActive()) {
2156 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2157 } else {
2158 // if input maps to a dynamic policy with an activity listener, notify of state change
2159 if ((inputDesc->mPolicyMix != NULL)
2160 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2161 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2162 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002163 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002164
2165 // automatically disable the remote submix output when input is stopped if not
2166 // used by a policy mix of type MIX_TYPE_RECORDERS
2167 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2168 String8 address = String8("");
2169 if (inputDesc->mPolicyMix == NULL) {
2170 address = String8("0");
2171 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2172 address = inputDesc->mPolicyMix->mDeviceAddress;
2173 }
2174 if (address != "") {
2175 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2176 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2177 address, "remote-submix");
2178 }
2179 }
2180
2181 audio_devices_t device = inputDesc->mDevice;
2182 resetInputDevice(input);
2183
2184 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2185 // primary HW module
2186 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2187 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2188 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
2189 SoundTrigger::setCaptureState(false);
2190 }
2191 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002192 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002193 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002194}
2195
Eric Laurent8fc147b2018-07-22 19:13:55 -07002196void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002197{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002198 ALOGV("%s portId %d", __FUNCTION__, portId);
2199
2200 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2201 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002202 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002203 return;
2204 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002205 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002206 audio_io_handle_t input = inputDesc->mIoHandle;
2207
Eric Laurent8f42ea12018-08-08 09:08:25 -07002208 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002209
Andy Hung39efb7a2018-09-26 15:39:28 -07002210 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002211
Andy Hung39efb7a2018-09-26 15:39:28 -07002212 if (inputDesc->getClientCount() > 0) {
2213 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002214 return;
2215 }
2216
Eric Laurent05b90f82014-08-27 15:32:29 -07002217 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002218 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002219 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002220}
2221
Eric Laurent8f42ea12018-08-08 09:08:25 -07002222void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002223{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002224 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002225
2226 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002227 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002228 }
2229}
2230
Eric Laurent8f42ea12018-08-08 09:08:25 -07002231void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2232{
2233 stopInput(portId);
2234 releaseInput(portId);
2235}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002236
Eric Laurentd4692962014-05-05 18:13:44 -07002237void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002238 bool patchRemoved = false;
2239
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002240 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002241 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002242 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002243 if (patch_index >= 0) {
2244 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002245 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002246 mAudioPatches.removeItemsAt(patch_index);
2247 patchRemoved = true;
2248 }
Eric Laurentfe231122017-11-17 17:48:06 -08002249 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002250 }
2251 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002252 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002253 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002254
2255 if (patchRemoved) {
2256 mpClientInterface->onAudioPatchListUpdate();
2257 }
Eric Laurentd4692962014-05-05 18:13:44 -07002258}
2259
Eric Laurente0720872014-03-11 09:30:41 -07002260void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002261 int indexMin,
2262 int indexMax)
2263{
2264 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002265 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002266
2267 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002268 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2269 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002270 continue;
2271 }
2272 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002273 }
Eric Laurente552edb2014-03-10 17:42:56 -07002274}
2275
Eric Laurente0720872014-03-11 09:30:41 -07002276status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002277 int index,
2278 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002279{
2280
Nadav Bar7c605f62017-12-25 00:01:52 +02002281 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2282 // app that has MODIFY_PHONE_STATE permission.
2283 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
2284 !(stream == AUDIO_STREAM_VOICE_CALL && index == 0)) ||
François Gaffied1ab2bd2015-12-02 18:20:06 +01002285 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002286 return BAD_VALUE;
2287 }
2288 if (!audio_is_output_device(device)) {
2289 return BAD_VALUE;
2290 }
2291
2292 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002293 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002294
Eric Laurent1fd372e2016-04-06 14:23:53 -07002295 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002296 stream, device, index);
2297
Eric Laurent28d09f02016-03-08 10:43:05 -08002298 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002299 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2300 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002301 continue;
2302 }
2303 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2304 }
Eric Laurente552edb2014-03-10 17:42:56 -07002305
Eric Laurent1fd372e2016-04-06 14:23:53 -07002306 // update volume on all outputs and streams matching the following:
2307 // - The requested stream (or a stream matching for volume control) is active on the output
2308 // - The device (or devices) selected by the strategy corresponding to this stream includes
2309 // the requested device
2310 // - For non default requested device, currently selected device on the output is either the
2311 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002312 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2313 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002314 status_t status = NO_ERROR;
2315 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002316 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2317 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08002318 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
Eric Laurent3839bc02018-07-10 18:33:34 -07002319 if (!(streamsMatchForvolume(stream, (audio_stream_type_t)curStream))) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002320 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002321 }
Eric Laurentdcd4ab12018-06-29 17:45:13 -07002322 if (!(desc->isStreamActive((audio_stream_type_t)curStream) || isInCall())) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002323 continue;
2324 }
Eric Laurent794fde22016-03-11 09:50:45 -08002325 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002326 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2327 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002328 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2329 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002330 continue;
2331 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002332 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002333 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002334 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07002335 applyVolume = (curDevice & curStreamDevice) != 0;
2336 } else {
2337 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002338 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002339 }
Eric Laurent3839bc02018-07-10 18:33:34 -07002340 // rescale index before applying to curStream as ranges may be different for
2341 // stream and curStream
2342 int idx = rescaleVolumeIndex(index, stream, (audio_stream_type_t)curStream);
Eric Laurente76f29c2016-09-14 17:17:53 -07002343 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002344 //FIXME: workaround for truncated touch sounds
2345 // delayed volume change for system stream to be removed when the problem is
2346 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002347 status_t volStatus =
Eric Laurent3839bc02018-07-10 18:33:34 -07002348 checkAndSetVolume((audio_stream_type_t)curStream, idx, desc, curDevice,
Eric Laurentdc462862016-07-19 12:29:53 -07002349 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002350 if (volStatus != NO_ERROR) {
2351 status = volStatus;
2352 }
2353 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002354 }
Eric Laurente552edb2014-03-10 17:42:56 -07002355 }
2356 return status;
2357}
2358
Eric Laurente0720872014-03-11 09:30:41 -07002359status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002360 int *index,
2361 audio_devices_t device)
2362{
2363 if (index == NULL) {
2364 return BAD_VALUE;
2365 }
2366 if (!audio_is_output_device(device)) {
2367 return BAD_VALUE;
2368 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002369 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002370 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002371 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002372 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2373 }
François Gaffiedfd74092015-03-19 12:10:59 +01002374 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002375
François Gaffied1ab2bd2015-12-02 18:20:06 +01002376 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002377 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2378 return NO_ERROR;
2379}
2380
Eric Laurent36829f92017-04-07 19:04:42 -07002381audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002382{
2383 // select one output among several suitable for global effects.
2384 // The priority is as follows:
2385 // 1: An offloaded output. If the effect ends up not being offloadable,
2386 // AudioFlinger will invalidate the track and the offloaded output
2387 // will be closed causing the effect to be moved to a PCM output.
2388 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002389 // 3: The primary output
2390 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002391
Eric Laurent3b73df72014-03-11 09:06:29 -07002392 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002393 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent36829f92017-04-07 19:04:42 -07002394 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002395
Eric Laurent36829f92017-04-07 19:04:42 -07002396 if (outputs.size() == 0) {
2397 return AUDIO_IO_HANDLE_NONE;
2398 }
Eric Laurente552edb2014-03-10 17:42:56 -07002399
Eric Laurent36829f92017-04-07 19:04:42 -07002400 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2401 bool activeOnly = true;
2402
2403 while (output == AUDIO_IO_HANDLE_NONE) {
2404 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2405 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2406 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2407
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002408 for (audio_io_handle_t output : outputs) {
2409 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002410 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2411 continue;
2412 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002413 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2414 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002415 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002416 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002417 }
2418 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002419 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002420 }
2421 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002422 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002423 }
2424 }
2425 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2426 output = outputOffloaded;
2427 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2428 output = outputDeepBuffer;
2429 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2430 output = outputPrimary;
2431 } else {
2432 output = outputs[0];
2433 }
2434 activeOnly = false;
2435 }
2436
2437 if (output != mMusicEffectOutput) {
2438 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2439 mMusicEffectOutput = output;
2440 }
2441
2442 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002443 return output;
2444}
2445
Eric Laurent36829f92017-04-07 19:04:42 -07002446audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2447{
2448 return selectOutputForMusicEffects();
2449}
2450
Eric Laurente0720872014-03-11 09:30:41 -07002451status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002452 audio_io_handle_t io,
2453 uint32_t strategy,
2454 int session,
2455 int id)
2456{
2457 ssize_t index = mOutputs.indexOfKey(io);
2458 if (index < 0) {
2459 index = mInputs.indexOfKey(io);
2460 if (index < 0) {
2461 ALOGW("registerEffect() unknown io %d", io);
2462 return INVALID_OPERATION;
2463 }
2464 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002465 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002466}
2467
Eric Laurentc75307b2015-03-17 15:29:32 -07002468bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2469{
Eric Laurent28d09f02016-03-08 10:43:05 -08002470 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002471 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2472 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002473 continue;
2474 }
2475 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2476 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002477 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002478}
2479
2480bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2481{
2482 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2483}
2484
Eric Laurente0720872014-03-11 09:30:41 -07002485bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002486{
2487 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002488 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002489 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002490 return true;
2491 }
2492 }
2493 return false;
2494}
2495
Eric Laurent275e8e92014-11-30 15:14:47 -08002496// Register a list of custom mixes with their attributes and format.
2497// When a mix is registered, corresponding input and output profiles are
2498// added to the remote submix hw module. The profile contains only the
2499// parameters (sampling rate, format...) specified by the mix.
2500// The corresponding input remote submix device is also connected.
2501//
2502// When a remote submix device is connected, the address is checked to select the
2503// appropriate profile and the corresponding input or output stream is opened.
2504//
2505// When capture starts, getInputForAttr() will:
2506// - 1 look for a mix matching the address passed in attribtutes tags if any
2507// - 2 if none found, getDeviceForInputSource() will:
2508// - 2.1 look for a mix matching the attributes source
2509// - 2.2 if none found, default to device selection by policy rules
2510// At this time, the corresponding output remote submix device is also connected
2511// and active playback use cases can be transferred to this mix if needed when reconnecting
2512// after AudioTracks are invalidated
2513//
2514// When playback starts, getOutputForAttr() will:
2515// - 1 look for a mix matching the address passed in attribtutes tags if any
2516// - 2 if none found, look for a mix matching the attributes usage
2517// - 3 if none found, default to device and output selection by policy rules.
2518
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002519status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002520{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002521 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2522 status_t res = NO_ERROR;
2523
2524 sp<HwModule> rSubmixModule;
2525 // examine each mix's route type
2526 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002527 AudioMix mix = mixes[i];
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002528 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
Eric Laurent97ac8712018-07-27 18:59:02 -07002529 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002530 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002531 break;
2532 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002533 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002534 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002535 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002536 rSubmixModule = mHwModules.getModuleFromName(
2537 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2538 if (rSubmixModule == 0) {
2539 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2540 i);
2541 res = INVALID_OPERATION;
2542 break;
2543 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002544 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002545
Eric Laurent97ac8712018-07-27 18:59:02 -07002546 String8 address = mix.mDeviceAddress;
2547 if (mix.mMixType == MIX_TYPE_PLAYERS) {
2548 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2549 } else {
2550 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
2551 }
François Gaffie036e1e92015-03-19 10:16:24 +01002552
Eric Laurent97ac8712018-07-27 18:59:02 -07002553 if (mPolicyMixes.registerMix(address, mix, 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002554 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002555 res = INVALID_OPERATION;
2556 break;
2557 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002558 audio_config_t outputConfig = mix.mFormat;
2559 audio_config_t inputConfig = mix.mFormat;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002560 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2561 // stereo and let audio flinger do the channel conversion if needed.
2562 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2563 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2564 rSubmixModule->addOutputProfile(address, &outputConfig,
2565 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2566 rSubmixModule->addInputProfile(address, &inputConfig,
2567 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002568
Eric Laurent97ac8712018-07-27 18:59:02 -07002569 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002570 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2571 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2572 address.string(), "remote-submix");
2573 } else {
2574 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2575 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2576 address.string(), "remote-submix");
2577 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002578 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2579 String8 address = mix.mDeviceAddress;
2580 audio_devices_t device = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002581 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2582 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002583
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002584 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002585 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2586 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2587 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2588 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2589 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2590 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002591 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2592 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002593 if (mPolicyMixes.registerMix(address, mix, desc) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002594 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002595 } else {
2596 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002597 }
2598 break;
2599 }
2600 }
2601
2602 if (res != NO_ERROR) {
2603 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002604 i, device, address.string());
2605 res = INVALID_OPERATION;
2606 break;
2607 } else if (!foundOutput) {
2608 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2609 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002610 res = INVALID_OPERATION;
2611 break;
2612 }
Eric Laurentc722f302014-12-10 11:21:49 -08002613 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002614 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002615 if (res != NO_ERROR) {
2616 unregisterPolicyMixes(mixes);
2617 }
2618 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002619}
2620
2621status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2622{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002623 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002624 status_t res = NO_ERROR;
2625 sp<HwModule> rSubmixModule;
2626 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002627 for (const auto& mix : mixes) {
2628 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002629
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002630 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002631 rSubmixModule = mHwModules.getModuleFromName(
2632 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2633 if (rSubmixModule == 0) {
2634 res = INVALID_OPERATION;
2635 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002636 }
2637 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002638
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002639 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002640
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002641 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2642 res = INVALID_OPERATION;
2643 continue;
2644 }
2645
2646 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2647 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2648 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2649 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2650 address.string(), "remote-submix");
2651 }
2652 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2653 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2654 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2655 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2656 address.string(), "remote-submix");
2657 }
2658 rSubmixModule->removeOutputProfile(address);
2659 rSubmixModule->removeInputProfile(address);
2660
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002661 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2662 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002663 res = INVALID_OPERATION;
2664 continue;
2665 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002666 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002667 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002668 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002669}
2670
Andy Hungc29d82b2018-10-05 12:23:17 -07002671void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07002672{
Andy Hungc29d82b2018-10-05 12:23:17 -07002673 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
2674 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07002675 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002676 std::string stateLiteral;
2677 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07002678 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002679 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
2680 "communications", "media", "record", "dock", "system",
2681 "HDMI system audio", "encoded surround output", "vibrate ringing" };
2682 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
2683 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Andy Hungc29d82b2018-10-05 12:23:17 -07002684 dst->appendFormat(" Force use for %s: %d\n",
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002685 forceUses[i], mEngine->getForceUse(i));
2686 }
Andy Hungc29d82b2018-10-05 12:23:17 -07002687 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
2688 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
2689 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
2690 mAvailableOutputDevices.dump(dst, String8("Available output"));
2691 mAvailableInputDevices.dump(dst, String8("Available input"));
2692 mHwModulesAll.dump(dst);
2693 mOutputs.dump(dst);
2694 mInputs.dump(dst);
2695 mVolumeCurves->dump(dst);
2696 mEffects.dump(dst);
2697 mAudioPatches.dump(dst);
2698 mPolicyMixes.dump(dst);
2699 mAudioSources.dump(dst);
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002700 if (!mSurroundFormats.empty()) {
Andy Hungc29d82b2018-10-05 12:23:17 -07002701 dst->append("\nEnabled Surround Formats:\n");
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002702 size_t i = 0;
2703 for (const auto& fmt : mSurroundFormats) {
Andy Hungc29d82b2018-10-05 12:23:17 -07002704 dst->append(i++ == 0 ? " " : ", ");
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002705 std::string sfmt;
2706 FormatConverter::toString(fmt, sfmt);
Andy Hungc29d82b2018-10-05 12:23:17 -07002707 dst->append(sfmt.c_str());
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002708 }
Andy Hungc29d82b2018-10-05 12:23:17 -07002709 dst->append("\n");
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002710 }
Andy Hungc29d82b2018-10-05 12:23:17 -07002711}
2712
2713status_t AudioPolicyManager::dump(int fd)
2714{
2715 String8 result;
2716 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07002717 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002718 return NO_ERROR;
2719}
2720
2721// This function checks for the parameters which can be offloaded.
2722// This can be enhanced depending on the capability of the DSP and policy
2723// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002724bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002725{
2726 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002727 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002728 offloadInfo.sample_rate, offloadInfo.channel_mask,
2729 offloadInfo.format,
2730 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2731 offloadInfo.has_video);
2732
Andy Hung2ddee192015-12-18 17:34:44 -08002733 if (mMasterMono) {
2734 return false; // no offloading if mono is set.
2735 }
2736
Eric Laurente552edb2014-03-10 17:42:56 -07002737 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07002738 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
2739 ALOGV("offload disabled by audio.offload.disable");
2740 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002741 }
2742
2743 // Check if stream type is music, then only allow offload as of now.
2744 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2745 {
2746 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2747 return false;
2748 }
2749
2750 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002751 const bool allowOffloadWithVideo =
2752 property_get_bool("audio.offload.video", false /* default_value */);
2753 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002754 ALOGV("isOffloadSupported: has_video == true, returning false");
2755 return false;
2756 }
2757
2758 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07002759 const int min_duration_secs = property_get_int32(
2760 "audio.offload.min.duration.secs", -1 /* default_value */);
2761 if (min_duration_secs >= 0) {
2762 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
2763 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%d)",
2764 min_duration_secs);
Eric Laurente552edb2014-03-10 17:42:56 -07002765 return false;
2766 }
2767 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2768 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2769 return false;
2770 }
2771
2772 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2773 // creating an offloaded track and tearing it down immediately after start when audioflinger
2774 // detects there is an active non offloadable effect.
2775 // FIXME: We should check the audio session here but we do not have it in this context.
2776 // This may prevent offloading in rare situations where effects are left active by apps
2777 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002778 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002779 return false;
2780 }
2781
2782 // See if there is a profile to support this.
2783 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002784 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002785 offloadInfo.sample_rate,
2786 offloadInfo.format,
2787 offloadInfo.channel_mask,
2788 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002789 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2790 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002791}
2792
Eric Laurent6a94d692014-05-20 11:18:06 -07002793status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2794 audio_port_type_t type,
2795 unsigned int *num_ports,
2796 struct audio_port *ports,
2797 unsigned int *generation)
2798{
2799 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2800 generation == NULL) {
2801 return BAD_VALUE;
2802 }
2803 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2804 if (ports == NULL) {
2805 *num_ports = 0;
2806 }
2807
2808 size_t portsWritten = 0;
2809 size_t portsMax = *num_ports;
2810 *num_ports = 0;
2811 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002812 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2813 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002814 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002815 for (const auto& dev : mAvailableOutputDevices) {
2816 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002817 continue;
2818 }
2819 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002820 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002821 }
2822 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002823 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002824 }
2825 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002826 for (const auto& dev : mAvailableInputDevices) {
2827 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002828 continue;
2829 }
2830 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002831 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002832 }
2833 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002834 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002835 }
2836 }
2837 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2838 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2839 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2840 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2841 }
2842 *num_ports += mInputs.size();
2843 }
2844 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002845 size_t numOutputs = 0;
2846 for (size_t i = 0; i < mOutputs.size(); i++) {
2847 if (!mOutputs[i]->isDuplicated()) {
2848 numOutputs++;
2849 if (portsWritten < portsMax) {
2850 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2851 }
2852 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002853 }
Eric Laurent84c70242014-06-23 08:46:27 -07002854 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002855 }
2856 }
2857 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002858 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002859 return NO_ERROR;
2860}
2861
Eric Laurent99fcae42018-05-17 16:59:18 -07002862status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07002863{
Eric Laurent99fcae42018-05-17 16:59:18 -07002864 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
2865 return BAD_VALUE;
2866 }
2867 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
2868 if (dev != 0) {
2869 dev->toAudioPort(port);
2870 return NO_ERROR;
2871 }
2872 dev = mAvailableInputDevices.getDeviceFromId(port->id);
2873 if (dev != 0) {
2874 dev->toAudioPort(port);
2875 return NO_ERROR;
2876 }
2877 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
2878 if (out != 0) {
2879 out->toAudioPort(port);
2880 return NO_ERROR;
2881 }
2882 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
2883 if (in != 0) {
2884 in->toAudioPort(port);
2885 return NO_ERROR;
2886 }
2887 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002888}
2889
Eric Laurent6a94d692014-05-20 11:18:06 -07002890status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2891 audio_patch_handle_t *handle,
2892 uid_t uid)
2893{
2894 ALOGV("createAudioPatch()");
2895
2896 if (handle == NULL || patch == NULL) {
2897 return BAD_VALUE;
2898 }
2899 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2900
Mikhail Naganovac9858b2018-06-15 13:12:37 -07002901 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07002902 return BAD_VALUE;
2903 }
2904 // only one source per audio patch supported for now
2905 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002906 return INVALID_OPERATION;
2907 }
Eric Laurent874c42872014-08-08 15:13:39 -07002908
2909 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002910 return INVALID_OPERATION;
2911 }
Eric Laurent874c42872014-08-08 15:13:39 -07002912 for (size_t i = 0; i < patch->num_sinks; i++) {
2913 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2914 return INVALID_OPERATION;
2915 }
2916 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002917
2918 sp<AudioPatch> patchDesc;
2919 ssize_t index = mAudioPatches.indexOfKey(*handle);
2920
Eric Laurent6a94d692014-05-20 11:18:06 -07002921 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2922 patch->sources[0].role,
2923 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002924#if LOG_NDEBUG == 0
2925 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002926 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002927 patch->sinks[i].role,
2928 patch->sinks[i].type);
2929 }
2930#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002931
2932 if (index >= 0) {
2933 patchDesc = mAudioPatches.valueAt(index);
2934 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2935 mUidCached, patchDesc->mUid, uid);
2936 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2937 return INVALID_OPERATION;
2938 }
2939 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002940 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002941 }
2942
2943 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002944 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002945 if (outputDesc == NULL) {
2946 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2947 return BAD_VALUE;
2948 }
Eric Laurent84c70242014-06-23 08:46:27 -07002949 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2950 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002951 if (patchDesc != 0) {
2952 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2953 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2954 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2955 return BAD_VALUE;
2956 }
2957 }
Eric Laurent874c42872014-08-08 15:13:39 -07002958 DeviceVector devices;
2959 for (size_t i = 0; i < patch->num_sinks; i++) {
2960 // Only support mix to devices connection
2961 // TODO add support for mix to mix connection
2962 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2963 ALOGV("createAudioPatch() source mix but sink is not a device");
2964 return INVALID_OPERATION;
2965 }
2966 sp<DeviceDescriptor> devDesc =
2967 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2968 if (devDesc == 0) {
2969 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2970 return BAD_VALUE;
2971 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002972
François Gaffie53615e22015-03-19 09:24:12 +01002973 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002974 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002975 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002976 NULL, // updatedSamplingRate
2977 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002978 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002979 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002980 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002981 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002982 ALOGV("createAudioPatch() profile not supported for device %08x",
2983 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002984 return INVALID_OPERATION;
2985 }
2986 devices.add(devDesc);
2987 }
2988 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002989 return INVALID_OPERATION;
2990 }
Eric Laurent874c42872014-08-08 15:13:39 -07002991
Eric Laurent6a94d692014-05-20 11:18:06 -07002992 // TODO: reconfigure output format and channels here
2993 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002994 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002995 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002996 index = mAudioPatches.indexOfKey(*handle);
2997 if (index >= 0) {
2998 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2999 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
3000 }
3001 patchDesc = mAudioPatches.valueAt(index);
3002 patchDesc->mUid = uid;
3003 ALOGV("createAudioPatch() success");
3004 } else {
3005 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
3006 return INVALID_OPERATION;
3007 }
3008 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3009 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3010 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003011 // only one sink supported when connecting an input device to a mix
3012 if (patch->num_sinks > 1) {
3013 return INVALID_OPERATION;
3014 }
François Gaffie53615e22015-03-19 09:24:12 +01003015 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003016 if (inputDesc == NULL) {
3017 return BAD_VALUE;
3018 }
3019 if (patchDesc != 0) {
3020 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3021 return BAD_VALUE;
3022 }
3023 }
3024 sp<DeviceDescriptor> devDesc =
3025 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
3026 if (devDesc == 0) {
3027 return BAD_VALUE;
3028 }
3029
François Gaffie53615e22015-03-19 09:24:12 +01003030 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08003031 devDesc->mAddress,
3032 patch->sinks[0].sample_rate,
3033 NULL, /*updatedSampleRate*/
3034 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003035 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003036 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003037 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003038 // FIXME for the parameter type,
3039 // and the NONE
3040 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003041 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003042 return INVALID_OPERATION;
3043 }
3044 // TODO: reconfigure output format and channels here
3045 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01003046 devDesc->type(), inputDesc->mIoHandle);
3047 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003048 index = mAudioPatches.indexOfKey(*handle);
3049 if (index >= 0) {
3050 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3051 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
3052 }
3053 patchDesc = mAudioPatches.valueAt(index);
3054 patchDesc->mUid = uid;
3055 ALOGV("createAudioPatch() success");
3056 } else {
3057 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
3058 return INVALID_OPERATION;
3059 }
3060 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3061 // device to device connection
3062 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003063 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003064 return BAD_VALUE;
3065 }
3066 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003067 sp<DeviceDescriptor> srcDeviceDesc =
3068 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07003069 if (srcDeviceDesc == 0) {
3070 return BAD_VALUE;
3071 }
Eric Laurent874c42872014-08-08 15:13:39 -07003072
Eric Laurent6a94d692014-05-20 11:18:06 -07003073 //update source and sink with our own data as the data passed in the patch may
3074 // be incomplete.
3075 struct audio_patch newPatch = *patch;
3076 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003077
Eric Laurent874c42872014-08-08 15:13:39 -07003078 for (size_t i = 0; i < patch->num_sinks; i++) {
3079 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3080 ALOGV("createAudioPatch() source device but one sink is not a device");
3081 return INVALID_OPERATION;
3082 }
3083
3084 sp<DeviceDescriptor> sinkDeviceDesc =
3085 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3086 if (sinkDeviceDesc == 0) {
3087 return BAD_VALUE;
3088 }
3089 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
3090
Eric Laurent3bcf8592015-04-03 12:13:24 -07003091 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003092 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003093 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08003094 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003095 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003096 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003097 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003098 return INVALID_OPERATION;
3099 }
Eric Laurent874c42872014-08-08 15:13:39 -07003100 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01003101 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003102 // if the sink device is reachable via an opened output stream, request to go via
3103 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07003104 audio_io_handle_t output = selectOutput(outputs,
3105 AUDIO_OUTPUT_FLAG_NONE,
3106 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07003107 if (output != AUDIO_IO_HANDLE_NONE) {
3108 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3109 if (outputDesc->isDuplicated()) {
3110 return INVALID_OPERATION;
3111 }
3112 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003113 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003114 newPatch.num_sources = 2;
3115 }
Eric Laurent83b88082014-06-20 18:31:16 -07003116 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003117 }
3118 // TODO: check from routing capabilities in config file and other conflicting patches
3119
Mikhail Naganovdc769682018-05-04 15:34:08 -07003120 status_t status = installPatch(__func__, index, handle, &newPatch, 0, uid, &patchDesc);
3121 if (status != NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003122 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3123 status);
3124 return INVALID_OPERATION;
3125 }
3126 } else {
3127 return BAD_VALUE;
3128 }
3129 } else {
3130 return BAD_VALUE;
3131 }
3132 return NO_ERROR;
3133}
3134
3135status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3136 uid_t uid)
3137{
3138 ALOGV("releaseAudioPatch() patch %d", handle);
3139
3140 ssize_t index = mAudioPatches.indexOfKey(handle);
3141
3142 if (index < 0) {
3143 return BAD_VALUE;
3144 }
3145 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3146 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3147 mUidCached, patchDesc->mUid, uid);
3148 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3149 return INVALID_OPERATION;
3150 }
3151
3152 struct audio_patch *patch = &patchDesc->mPatch;
3153 patchDesc->mUid = mUidCached;
3154 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003155 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003156 if (outputDesc == NULL) {
3157 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3158 return BAD_VALUE;
3159 }
3160
Eric Laurentc75307b2015-03-17 15:29:32 -07003161 setOutputDevice(outputDesc,
3162 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07003163 true,
3164 0,
3165 NULL);
3166 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3167 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003168 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003169 if (inputDesc == NULL) {
3170 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3171 return BAD_VALUE;
3172 }
3173 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003174 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003175 true,
3176 NULL);
3177 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003178 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3179 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3180 status, patchDesc->mAfPatchHandle);
3181 removeAudioPatch(patchDesc->mHandle);
3182 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003183 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003184 } else {
3185 return BAD_VALUE;
3186 }
3187 } else {
3188 return BAD_VALUE;
3189 }
3190 return NO_ERROR;
3191}
3192
3193status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3194 struct audio_patch *patches,
3195 unsigned int *generation)
3196{
François Gaffie53615e22015-03-19 09:24:12 +01003197 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003198 return BAD_VALUE;
3199 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003200 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003201 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003202}
3203
Eric Laurente1715a42014-05-20 11:30:42 -07003204status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003205{
Eric Laurente1715a42014-05-20 11:30:42 -07003206 ALOGV("setAudioPortConfig()");
3207
3208 if (config == NULL) {
3209 return BAD_VALUE;
3210 }
3211 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3212 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003213 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3214 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003215 }
3216
Eric Laurenta121f902014-06-03 13:32:54 -07003217 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003218 if (config->type == AUDIO_PORT_TYPE_MIX) {
3219 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003220 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003221 if (outputDesc == NULL) {
3222 return BAD_VALUE;
3223 }
Eric Laurent84c70242014-06-23 08:46:27 -07003224 ALOG_ASSERT(!outputDesc->isDuplicated(),
3225 "setAudioPortConfig() called on duplicated output %d",
3226 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003227 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003228 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003229 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003230 if (inputDesc == NULL) {
3231 return BAD_VALUE;
3232 }
Eric Laurenta121f902014-06-03 13:32:54 -07003233 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003234 } else {
3235 return BAD_VALUE;
3236 }
3237 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3238 sp<DeviceDescriptor> deviceDesc;
3239 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3240 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3241 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3242 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3243 } else {
3244 return BAD_VALUE;
3245 }
3246 if (deviceDesc == NULL) {
3247 return BAD_VALUE;
3248 }
Eric Laurenta121f902014-06-03 13:32:54 -07003249 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003250 } else {
3251 return BAD_VALUE;
3252 }
3253
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003254 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003255 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3256 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003257 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003258 audioPortConfig->toAudioPortConfig(&newConfig, config);
3259 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003260 }
Eric Laurenta121f902014-06-03 13:32:54 -07003261 if (status != NO_ERROR) {
3262 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003263 }
Eric Laurente1715a42014-05-20 11:30:42 -07003264
3265 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003266}
3267
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003268void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3269{
Eric Laurentd60560a2015-04-10 11:31:20 -07003270 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003271 clearAudioPatches(uid);
3272 clearSessionRoutes(uid);
3273}
3274
Eric Laurent6a94d692014-05-20 11:18:06 -07003275void AudioPolicyManager::clearAudioPatches(uid_t uid)
3276{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003277 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003278 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3279 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003280 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003281 }
3282 }
3283}
3284
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003285void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3286 audio_io_handle_t ouptutToSkip)
3287{
3288 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3289 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3290 for (size_t j = 0; j < mOutputs.size(); j++) {
3291 if (mOutputs.keyAt(j) == ouptutToSkip) {
3292 continue;
3293 }
3294 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3295 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3296 continue;
3297 }
3298 // If the default device for this strategy is on another output mix,
3299 // invalidate all tracks in this strategy to force re connection.
3300 // Otherwise select new device on the output mix.
3301 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003302 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003303 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3304 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3305 }
3306 }
3307 } else {
3308 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3309 setOutputDevice(outputDesc, newDevice, false);
3310 }
3311 }
3312}
3313
3314void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3315{
3316 // remove output routes associated with this uid
3317 SortedVector<routing_strategy> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07003318 for (size_t i = 0; i < mOutputs.size(); i++) {
3319 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003320 for (const auto& client : outputDesc->getClientIterable()) {
3321 if (client->hasPreferredDevice() && client->uid() == uid) {
3322 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3323 affectedStrategies.add(getStrategy(client->stream()));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003324 }
3325 }
3326 }
3327 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003328 for (const auto& strategy : affectedStrategies) {
3329 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003330 }
3331
3332 // remove input routes associated with this uid
3333 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07003334 for (size_t i = 0; i < mInputs.size(); i++) {
3335 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003336 for (const auto& client : inputDesc->getClientIterable()) {
3337 if (client->hasPreferredDevice() && client->uid() == uid) {
3338 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3339 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003340 }
3341 }
3342 }
3343 // reroute inputs if necessary
3344 SortedVector<audio_io_handle_t> inputsToClose;
3345 for (size_t i = 0; i < mInputs.size(); i++) {
3346 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003347 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003348 inputsToClose.add(inputDesc->mIoHandle);
3349 }
3350 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003351 for (const auto& input : inputsToClose) {
3352 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003353 }
3354}
3355
Eric Laurentd60560a2015-04-10 11:31:20 -07003356void AudioPolicyManager::clearAudioSources(uid_t uid)
3357{
3358 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003359 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3360 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07003361 stopAudioSource(mAudioSources.keyAt(i));
3362 }
3363 }
3364}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003365
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003366status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3367 audio_io_handle_t *ioHandle,
3368 audio_devices_t *device)
3369{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003370 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3371 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003372 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003373
François Gaffiedf372692015-03-19 10:43:27 +01003374 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003375}
3376
Eric Laurentd60560a2015-04-10 11:31:20 -07003377status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003378 const audio_attributes_t *attributes,
3379 audio_port_handle_t *portId,
3380 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003381{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003382 ALOGV("%s", __FUNCTION__);
3383 *portId = AUDIO_PORT_HANDLE_NONE;
3384
3385 if (source == NULL || attributes == NULL || portId == NULL) {
3386 ALOGW("%s invalid argument: source %p attributes %p handle %p",
3387 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003388 return BAD_VALUE;
3389 }
3390
Eric Laurentd60560a2015-04-10 11:31:20 -07003391 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3392 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003393 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
3394 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003395 return INVALID_OPERATION;
3396 }
3397
3398 sp<DeviceDescriptor> srcDeviceDesc =
3399 mAvailableInputDevices.getDevice(source->ext.device.type,
3400 String8(source->ext.device.address));
3401 if (srcDeviceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003402 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003403 return BAD_VALUE;
3404 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003405
3406 *portId = AudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07003407
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003408 struct audio_patch dummyPatch = {};
Eric Laurentd60560a2015-04-10 11:31:20 -07003409 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003410
3411 sp<SourceClientDescriptor> sourceDesc =
3412 new SourceClientDescriptor(*portId, uid, *attributes, patchDesc, srcDeviceDesc,
Eric Laurent97ac8712018-07-27 18:59:02 -07003413 streamTypefromAttributesInt(attributes),
3414 getStrategyForAttr(attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07003415
3416 status_t status = connectAudioSource(sourceDesc);
3417 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003418 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003419 }
3420 return status;
3421}
3422
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003423status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003424{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003425 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003426
3427 // make sure we only have one patch per source.
3428 disconnectAudioSource(sourceDesc);
3429
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003430 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003431 routing_strategy strategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003432 audio_stream_type_t stream = sourceDesc->stream();
3433 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->srcDevice();
Eric Laurentd60560a2015-04-10 11:31:20 -07003434
3435 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3436 sp<DeviceDescriptor> sinkDeviceDesc =
3437 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3438
3439 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003440
3441 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3442 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003443 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003444 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3445 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3446 // create patch between src device and output device
3447 // create Hwoutput and add to mHwOutputs
3448 } else {
3449 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3450 audio_io_handle_t output =
3451 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3452 if (output == AUDIO_IO_HANDLE_NONE) {
3453 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3454 return INVALID_OPERATION;
3455 }
3456 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3457 if (outputDesc->isDuplicated()) {
3458 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3459 return INVALID_OPERATION;
3460 }
Eric Laurent733ce942017-12-07 12:18:25 -08003461 status_t status = outputDesc->start();
3462 if (status != NO_ERROR) {
3463 return status;
3464 }
3465
Eric Laurentd60560a2015-04-10 11:31:20 -07003466 // create a special patch with no sink and two sources:
3467 // - the second source indicates to PatchPanel through which output mix this patch should
3468 // be connected as well as the stream type for volume control
3469 // - the sink is defined by whatever output device is currently selected for the output
3470 // though which this patch is routed.
Mikhail Naganovdc769682018-05-04 15:34:08 -07003471 PatchBuilder patchBuilder;
3472 patchBuilder.addSource(srcDeviceDesc).addSource(outputDesc, { .stream = stream });
3473 status = mpClientInterface->createAudioPatch(patchBuilder.patch(),
Eric Laurentd60560a2015-04-10 11:31:20 -07003474 &afPatchHandle,
3475 0);
3476 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3477 status, afPatchHandle);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003478 sourceDesc->patchDesc()->mPatch = *patchBuilder.patch();
Eric Laurentd60560a2015-04-10 11:31:20 -07003479 if (status != NO_ERROR) {
3480 ALOGW("%s patch panel could not connect device patch, error %d",
3481 __FUNCTION__, status);
3482 return INVALID_OPERATION;
3483 }
3484 uint32_t delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07003485 status = startSource(outputDesc, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003486
3487 if (status != NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003488 mpClientInterface->releaseAudioPatch(sourceDesc->patchDesc()->mAfPatchHandle, 0);
Eric Laurentd60560a2015-04-10 11:31:20 -07003489 return status;
3490 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003491 sourceDesc->setSwOutput(outputDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003492 if (delayMs != 0) {
3493 usleep(delayMs * 1000);
3494 }
3495 }
3496
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003497 sourceDesc->patchDesc()->mAfPatchHandle = afPatchHandle;
3498 addAudioPatch(sourceDesc->patchDesc()->mHandle, sourceDesc->patchDesc());
Eric Laurentd60560a2015-04-10 11:31:20 -07003499
3500 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003501}
3502
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003503status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07003504{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003505 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
3506 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003507 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003508 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003509 return BAD_VALUE;
3510 }
3511 status_t status = disconnectAudioSource(sourceDesc);
3512
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003513 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003514 return status;
3515}
3516
Andy Hung2ddee192015-12-18 17:34:44 -08003517status_t AudioPolicyManager::setMasterMono(bool mono)
3518{
3519 if (mMasterMono == mono) {
3520 return NO_ERROR;
3521 }
3522 mMasterMono = mono;
3523 // if enabling mono we close all offloaded devices, which will invalidate the
3524 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3525 // for recreating the new AudioTrack as non-offloaded PCM.
3526 //
3527 // If disabling mono, we leave all tracks as is: we don't know which clients
3528 // and tracks are able to be recreated as offloaded. The next "song" should
3529 // play back offloaded.
3530 if (mMasterMono) {
3531 Vector<audio_io_handle_t> offloaded;
3532 for (size_t i = 0; i < mOutputs.size(); ++i) {
3533 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3534 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3535 offloaded.push(desc->mIoHandle);
3536 }
3537 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003538 for (const auto& handle : offloaded) {
3539 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003540 }
3541 }
3542 // update master mono for all remaining outputs
3543 for (size_t i = 0; i < mOutputs.size(); ++i) {
3544 updateMono(mOutputs.keyAt(i));
3545 }
3546 return NO_ERROR;
3547}
3548
3549status_t AudioPolicyManager::getMasterMono(bool *mono)
3550{
3551 *mono = mMasterMono;
3552 return NO_ERROR;
3553}
3554
Eric Laurentac9cef52017-06-09 15:46:26 -07003555float AudioPolicyManager::getStreamVolumeDB(
3556 audio_stream_type_t stream, int index, audio_devices_t device)
3557{
3558 return computeVolume(stream, index, device);
3559}
3560
jiabin81772902018-04-02 17:52:27 -07003561status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3562 audio_format_t *surroundFormats,
3563 bool *surroundFormatsEnabled,
3564 bool reported)
3565{
3566 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3567 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3568 return BAD_VALUE;
3569 }
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003570 ALOGV("getSurroundFormats() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p"
3571 " reported %d", *numSurroundFormats, surroundFormats, surroundFormatsEnabled, reported);
jiabin81772902018-04-02 17:52:27 -07003572
3573 // Only return value if there is HDMI output.
3574 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3575 return INVALID_OPERATION;
3576 }
3577
3578 size_t formatsWritten = 0;
3579 size_t formatsMax = *numSurroundFormats;
3580 *numSurroundFormats = 0;
Mikhail Naganov2563f232018-09-27 14:48:01 -07003581 std::unordered_set<audio_format_t> formats;
jiabin81772902018-04-02 17:52:27 -07003582 if (reported) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003583 // Return formats from HDMI profiles, that have already been resolved by
3584 // checkOutputsForDevice().
3585 DeviceVector hdmiOutputDevs = mAvailableOutputDevices.getDevicesFromTypeMask(
3586 AUDIO_DEVICE_OUT_HDMI);
3587 for (size_t i = 0; i < hdmiOutputDevs.size(); i++) {
3588 FormatVector supportedFormats =
3589 hdmiOutputDevs[i]->getAudioPort()->getAudioProfiles().getSupportedFormats();
3590 for (size_t j = 0; j < supportedFormats.size(); j++) {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003591 if (mConfig.getSurroundFormats().count(supportedFormats[j]) != 0) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003592 formats.insert(supportedFormats[j]);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003593 } else {
3594 for (const auto& pair : mConfig.getSurroundFormats()) {
3595 if (pair.second.count(supportedFormats[j]) != 0) {
3596 formats.insert(pair.first);
3597 break;
3598 }
3599 }
Mikhail Naganov2563f232018-09-27 14:48:01 -07003600 }
3601 }
jiabin81772902018-04-02 17:52:27 -07003602 }
3603 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003604 for (const auto& pair : mConfig.getSurroundFormats()) {
3605 formats.insert(pair.first);
jiabin81772902018-04-02 17:52:27 -07003606 }
3607 }
Mikhail Naganov2563f232018-09-27 14:48:01 -07003608 for (const auto& format: formats) {
jiabin81772902018-04-02 17:52:27 -07003609 if (formatsWritten < formatsMax) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003610 surroundFormats[formatsWritten] = format;
jiabin81772902018-04-02 17:52:27 -07003611 bool formatEnabled = false;
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003612 if (mConfig.getSurroundFormats().count(format) == 0) {
3613 // Check sub-formats
3614 for (const auto& pair : mConfig.getSurroundFormats()) {
3615 for (const auto& subformat : pair.second) {
3616 formatEnabled = mSurroundFormats.count(subformat) != 0;
3617 if (formatEnabled) break;
3618 }
3619 if (formatEnabled) break;
jiabin81772902018-04-02 17:52:27 -07003620 }
3621 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003622 formatEnabled = mSurroundFormats.count(format) != 0;
jiabin81772902018-04-02 17:52:27 -07003623 }
3624 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3625 }
3626 (*numSurroundFormats)++;
3627 }
3628 return NO_ERROR;
3629}
3630
3631status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3632{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003633 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
jiabin81772902018-04-02 17:52:27 -07003634 // Check if audio format is a surround formats.
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003635 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
3636 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003637 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07003638 return BAD_VALUE;
3639 }
3640
3641 // Should only be called when MANUAL.
3642 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3643 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
3644 if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003645 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07003646 return INVALID_OPERATION;
3647 }
3648
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003649 if ((mSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07003650 return NO_ERROR;
3651 }
3652
3653 // The operation is valid only when there is HDMI output available.
3654 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003655 ALOGW("%s() no HDMI out devices found", __func__);
jiabin81772902018-04-02 17:52:27 -07003656 return INVALID_OPERATION;
3657 }
3658
Mikhail Naganov2563f232018-09-27 14:48:01 -07003659 std::unordered_set<audio_format_t> surroundFormatsBackup(mSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07003660 if (enabled) {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003661 mSurroundFormats.insert(audioFormat);
3662 for (const auto& subFormat : formatIter->second) {
3663 mSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07003664 }
3665 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003666 mSurroundFormats.erase(audioFormat);
3667 for (const auto& subFormat : formatIter->second) {
3668 mSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07003669 }
3670 }
3671
3672 sp<SwAudioOutputDescriptor> outputDesc;
3673 bool profileUpdated = false;
Mikhail Naganov708e0382018-05-30 09:53:04 -07003674 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003675 AUDIO_DEVICE_OUT_HDMI);
3676 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3677 // Simulate reconnection to update enabled surround sound formats.
3678 String8 address = hdmiOutputDevices[i]->mAddress;
3679 String8 name = hdmiOutputDevices[i]->getName();
3680 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3681 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3682 address.c_str(),
3683 name.c_str());
3684 if (status != NO_ERROR) {
3685 continue;
3686 }
3687 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3688 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3689 address.c_str(),
3690 name.c_str());
3691 profileUpdated |= (status == NO_ERROR);
3692 }
Mikhail Naganov708e0382018-05-30 09:53:04 -07003693 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003694 AUDIO_DEVICE_IN_HDMI);
3695 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3696 // Simulate reconnection to update enabled surround sound formats.
3697 String8 address = hdmiInputDevices[i]->mAddress;
3698 String8 name = hdmiInputDevices[i]->getName();
3699 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3700 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3701 address.c_str(),
3702 name.c_str());
3703 if (status != NO_ERROR) {
3704 continue;
3705 }
3706 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3707 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3708 address.c_str(),
3709 name.c_str());
3710 profileUpdated |= (status == NO_ERROR);
3711 }
3712
jiabin81772902018-04-02 17:52:27 -07003713 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003714 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov2563f232018-09-27 14:48:01 -07003715 mSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07003716 }
3717
3718 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3719}
3720
Eric Laurentf32108e2018-10-04 17:22:04 -07003721void AudioPolicyManager::setAppState(uid_t uid, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003722{
Eric Laurentf32108e2018-10-04 17:22:04 -07003723 Vector<sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
3724 bool silenced = state == APP_STATE_IDLE;
3725
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003726 ALOGV("AudioPolicyManager:setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
3727
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003728 for (size_t i = 0; i < activeInputs.size(); i++) {
3729 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
Eric Laurent8f42ea12018-08-08 09:08:25 -07003730 RecordClientVector clients = activeDesc->clientsList(true /*activeOnly*/);
3731 for (const auto& client : clients) {
3732 if (uid == client->uid()) {
3733 client->setSilenced(silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003734 }
3735 }
3736 }
3737}
3738
jiabin6012f912018-11-02 17:06:30 -07003739bool AudioPolicyManager::isHapticPlaybackSupported()
3740{
3741 for (const auto& hwModule : mHwModules) {
3742 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
3743 for (const auto &outProfile : outputProfiles) {
3744 struct audio_port audioPort;
3745 outProfile->toAudioPort(&audioPort);
3746 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
3747 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
3748 return true;
3749 }
3750 }
3751 }
3752 }
3753 return false;
3754}
3755
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003756status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003757{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003758 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003759
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003760 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003761 if (patchDesc == 0) {
3762 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003763 sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003764 return BAD_VALUE;
3765 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003766 removeAudioPatch(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003767
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003768 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003769 if (swOutputDesc != 0) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003770 status_t status = stopSource(swOutputDesc, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08003771 if (status == NO_ERROR) {
3772 swOutputDesc->stop();
3773 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003774 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3775 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003776 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003777 if (hwOutputDesc != 0) {
3778 // release patch between src device and output device
3779 // close Hwoutput and remove from mHwOutputs
3780 } else {
3781 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3782 }
3783 }
3784 return NO_ERROR;
3785}
3786
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003787sp<SourceClientDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
Eric Laurentd60560a2015-04-10 11:31:20 -07003788 audio_io_handle_t output, routing_strategy strategy)
3789{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003790 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07003791 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003792 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3793 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003794 routing_strategy sourceStrategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003795 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003796 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3797 source = sourceDesc;
3798 break;
3799 }
3800 }
3801 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003802}
3803
Eric Laurente552edb2014-03-10 17:42:56 -07003804// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003805// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003806// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003807uint32_t AudioPolicyManager::nextAudioPortGeneration()
3808{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003809 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003810}
3811
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003812// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3813static const char *kConfigLocationList[] =
3814 {"/odm/etc", "/vendor/etc", "/system/etc"};
3815static const int kConfigLocationListSize =
3816 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3817
3818static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3819 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07003820 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003821 status_t ret;
3822
Petri Gyntherf497f292018-04-17 18:46:10 -07003823 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
3824 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
3825 // A2DP offload supported but disabled: try to use special XML file
3826 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
3827 }
3828 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3829
3830 for (const char* fileName : fileNames) {
3831 for (int i = 0; i < kConfigLocationListSize; i++) {
Petri Gyntherf497f292018-04-17 18:46:10 -07003832 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
3833 "%s/%s", kConfigLocationList[i], fileName);
Mikhail Naganova289aea2018-09-17 15:26:23 -07003834 ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile, &config);
Petri Gyntherf497f292018-04-17 18:46:10 -07003835 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003836 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07003837 return ret;
3838 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003839 }
3840 }
3841 return ret;
3842}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003843
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003844AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
3845 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07003846 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07003847 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003848 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07003849 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003850 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003851 mVolumeCurves(new VolumeCurvesCollection()),
3852 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08003853 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003854 mAudioPortGeneration(1),
3855 mBeaconMuteRefCount(0),
3856 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003857 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003858 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003859 mMasterMono(false),
Chris Thornton2b864642017-06-27 21:26:07 -07003860 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE),
3861 mHasComputedSoundTriggerSupportsConcurrentCapture(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003862{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003863}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003864
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003865AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
3866 : AudioPolicyManager(clientInterface, false /*forTesting*/)
3867{
3868 loadConfig();
3869 initialize();
3870}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003871
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07003872// This check is to catch any legacy platform updating to Q without having
3873// switched to XML since its deprecation on O.
3874// TODO: after Q release, remove this check and flag as XML is now the only
3875// option and all legacy platform should have transitioned to XML.
3876#ifndef USE_XML_AUDIO_POLICY_CONF
3877#error Audio policy no longer supports legacy .conf configuration format
François Gaffied1ab2bd2015-12-02 18:20:06 +01003878#endif
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07003879
3880void AudioPolicyManager::loadConfig() {
3881 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003882 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003883 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01003884 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003885}
3886
3887status_t AudioPolicyManager::initialize() {
3888 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01003889
3890 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003891 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3892 if (!engineInstance) {
3893 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003894 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003895 }
3896 // Retrieve the Policy Manager Interface
3897 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3898 if (mEngine == NULL) {
3899 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003900 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003901 }
3902 mEngine->setObserver(this);
3903 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003904 if (status != NO_ERROR) {
3905 LOG_FATAL("Policy engine not initialized(err=%d)", status);
3906 return status;
3907 }
François Gaffie2110e042015-03-24 08:41:51 +01003908
Eric Laurent3a4311c2014-03-17 12:00:47 -07003909 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003910 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003911 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3912 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Mikhail Naganovd4120142017-12-06 15:49:22 -08003913 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003914 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08003915 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
3916 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003917 continue;
3918 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08003919 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07003920 // open all output streams needed to access attached devices
3921 // except for direct output streams that are only opened when they are actually
3922 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003923 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003924 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003925 if (!outProfile->canOpenNewIo()) {
3926 ALOGE("Invalid Output profile max open count %u for profile %s",
3927 outProfile->maxOpenCount, outProfile->getTagName().c_str());
3928 continue;
3929 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003930 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003931 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003932 continue;
3933 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003934 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003935 mTtsOutputAvailable = true;
3936 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003937
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003938 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003939 continue;
3940 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003941 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003942 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3943 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003944 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003945 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003946 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003947 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003948 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003949 if ((profileType & outputDeviceTypes) == 0) {
3950 continue;
3951 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003952 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3953 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003954 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov708e0382018-05-30 09:53:04 -07003955 const DeviceVector &devicesForType = supportedDevices.getDevicesFromTypeMask(
3956 profileType);
Eric Laurentc40d9692016-04-13 19:14:13 -07003957 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3958 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003959 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08003960 status_t status = outputDesc->open(nullptr, profileType, address,
3961 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07003962
3963 if (status != NO_ERROR) {
3964 ALOGW("Cannot open output stream for device %08x on hw module %s",
3965 outputDesc->mDevice,
Mikhail Naganovd4120142017-12-06 15:49:22 -08003966 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003967 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003968 for (const auto& dev : supportedDevices) {
3969 ssize_t index = mAvailableOutputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07003970 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003971 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003972 mAvailableOutputDevices[index]->attach(hwModule);
Eric Laurentd78f1532014-09-16 16:38:20 -07003973 }
3974 }
3975 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003976 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003977 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003978 }
3979 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003980 setOutputDevice(outputDesc,
Eric Laurentfe231122017-11-17 17:48:06 -08003981 profileType,
Eric Laurentc40d9692016-04-13 19:14:13 -07003982 true,
3983 0,
3984 NULL,
Eric Laurentfe231122017-11-17 17:48:06 -08003985 address);
Eric Laurentd78f1532014-09-16 16:38:20 -07003986 }
Eric Laurente552edb2014-03-10 17:42:56 -07003987 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003988 // open input streams needed to access attached devices to validate
3989 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003990 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003991 if (!inProfile->canOpenNewIo()) {
3992 ALOGE("Invalid Input profile max open count %u for profile %s",
3993 inProfile->maxOpenCount, inProfile->getTagName().c_str());
3994 continue;
3995 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003996 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003997 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003998 continue;
3999 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004000 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07004001 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004002 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
4003
Eric Laurentd78f1532014-09-16 16:38:20 -07004004 if ((profileType & inputDeviceTypes) == 0) {
4005 continue;
4006 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08004007 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08004008 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004009
Mikhail Naganov708e0382018-05-30 09:53:04 -07004010 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(profileType);
Eric Laurent53b810e2017-12-10 17:25:10 -08004011 // the inputs vector must be of size >= 1, but we don't want to crash here
4012 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
4013 : String8("");
4014 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
4015 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
4016
Eric Laurentd78f1532014-09-16 16:38:20 -07004017 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004018 status_t status = inputDesc->open(nullptr,
4019 profileType,
Eric Laurent53b810e2017-12-10 17:25:10 -08004020 address,
Eric Laurentfe231122017-11-17 17:48:06 -08004021 AUDIO_SOURCE_MIC,
4022 AUDIO_INPUT_FLAG_NONE,
4023 &input);
Eric Laurentd78f1532014-09-16 16:38:20 -07004024
4025 if (status == NO_ERROR) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004026 for (const auto& dev : inProfile->getSupportedDevices()) {
4027 ssize_t index = mAvailableInputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07004028 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07004029 if (index >= 0) {
4030 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
4031 if (!devDesc->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004032 devDesc->attach(hwModule);
Eric Laurent83efe1c2017-07-09 16:51:08 -07004033 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07004034 }
Eric Laurentd78f1532014-09-16 16:38:20 -07004035 }
4036 }
Eric Laurentfe231122017-11-17 17:48:06 -08004037 inputDesc->close();
Eric Laurentd78f1532014-09-16 16:38:20 -07004038 } else {
4039 ALOGW("Cannot open input stream for device %08x on hw module %s",
Eric Laurentfe231122017-11-17 17:48:06 -08004040 profileType,
Mikhail Naganovd4120142017-12-06 15:49:22 -08004041 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07004042 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004043 }
4044 }
4045 // make sure all attached devices have been allocated a unique ID
4046 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004047 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004048 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004049 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
4050 continue;
4051 }
François Gaffie2110e042015-03-24 08:41:51 +01004052 // The device is now validated and can be appended to the available devices of the engine
4053 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
4054 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004055 i++;
4056 }
4057 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004058 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01004059 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004060 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
4061 continue;
4062 }
François Gaffie2110e042015-03-24 08:41:51 +01004063 // The device is now validated and can be appended to the available devices of the engine
4064 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
4065 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004066 i++;
4067 }
4068 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004069 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01004070 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004071 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004072 }
jiabin9ff780e2018-03-19 18:19:52 -07004073 // If microphones address is empty, set it according to device type
4074 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
4075 if (mAvailableInputDevices[i]->mAddress.isEmpty()) {
4076 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
4077 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
4078 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
4079 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BACK_MICROPHONE_ADDRESS);
4080 }
4081 }
4082 }
Eric Laurente552edb2014-03-10 17:42:56 -07004083
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004084 if (mPrimaryOutput == 0) {
4085 ALOGE("Failed to open primary output");
4086 status = NO_INIT;
4087 }
Eric Laurente552edb2014-03-10 17:42:56 -07004088
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09004089 // Silence ALOGV statements
4090 property_set("log.tag." LOG_TAG, "D");
4091
Eric Laurente552edb2014-03-10 17:42:56 -07004092 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004093 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004094}
4095
Eric Laurente0720872014-03-11 09:30:41 -07004096AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004097{
Eric Laurente552edb2014-03-10 17:42:56 -07004098 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004099 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004100 }
4101 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004102 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004103 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004104 mAvailableOutputDevices.clear();
4105 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004106 mOutputs.clear();
4107 mInputs.clear();
4108 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004109 mHwModulesAll.clear();
jiabin81772902018-04-02 17:52:27 -07004110 mSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004111}
4112
Eric Laurente0720872014-03-11 09:30:41 -07004113status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004114{
Eric Laurent87ffa392015-05-22 10:32:38 -07004115 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004116}
4117
Eric Laurente552edb2014-03-10 17:42:56 -07004118// ---
4119
Eric Laurent98e38192018-02-15 18:31:53 -08004120void AudioPolicyManager::addOutput(audio_io_handle_t output,
4121 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004122{
Eric Laurent1c333e22014-05-20 10:48:17 -07004123 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08004124 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004125 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004126 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004127 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004128}
4129
François Gaffie53615e22015-03-19 09:24:12 +01004130void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4131{
4132 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004133 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004134}
4135
Eric Laurent98e38192018-02-15 18:31:53 -08004136void AudioPolicyManager::addInput(audio_io_handle_t input,
4137 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004138{
Eric Laurent1c333e22014-05-20 10:48:17 -07004139 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004140 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004141}
Eric Laurente552edb2014-03-10 17:42:56 -07004142
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004143void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08004144 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004145 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004146 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08004147 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004148 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08004149 if (devDesc != 0) {
4150 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
4151 desc->mIoHandle, address.string());
4152 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004153 }
4154}
4155
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004156status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004157 audio_policy_dev_state_t state,
4158 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004159 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07004160{
François Gaffie53615e22015-03-19 09:24:12 +01004161 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07004162 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004163
4164 if (audio_device_is_digital(device)) {
4165 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004166 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004167 }
Eric Laurente552edb2014-03-10 17:42:56 -07004168
Eric Laurent3b73df72014-03-11 09:06:29 -07004169 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004170 // first list already open outputs that can be routed to this device
4171 for (size_t i = 0; i < mOutputs.size(); i++) {
4172 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07004173 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004174 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004175 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
4176 outputs.add(mOutputs.keyAt(i));
4177 } else {
4178 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08004179 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004180 }
Eric Laurente552edb2014-03-10 17:42:56 -07004181 }
4182 }
4183 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004184 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004185 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004186 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4187 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004188 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004189 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004190 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004191 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004192 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4193 j, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004194 }
Eric Laurente552edb2014-03-10 17:42:56 -07004195 }
4196 }
4197 }
4198
Eric Laurent7b279bb2015-12-14 10:18:23 -08004199 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004200
Eric Laurente552edb2014-03-10 17:42:56 -07004201 if (profiles.isEmpty() && outputs.isEmpty()) {
4202 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4203 return BAD_VALUE;
4204 }
4205
4206 // open outputs for matching profiles if needed. Direct outputs are also opened to
4207 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4208 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004209 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004210
4211 // nothing to do if one output is already opened for this profile
4212 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004213 for (j = 0; j < outputs.size(); j++) {
4214 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004215 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004216 // matching profile: save the sample rates, format and channel masks supported
4217 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07004218 if (audio_device_is_digital(device)) {
4219 devDesc->importAudioPort(profile);
4220 }
Eric Laurente552edb2014-03-10 17:42:56 -07004221 break;
4222 }
4223 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004224 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004225 continue;
4226 }
4227
Eric Laurent3974e3b2017-12-07 17:58:43 -08004228 if (!profile->canOpenNewIo()) {
4229 ALOGW("Max Output number %u already opened for this profile %s",
4230 profile->maxOpenCount, profile->getTagName().c_str());
4231 continue;
4232 }
4233
Eric Laurent83efe1c2017-07-09 16:51:08 -07004234 ALOGV("opening output for device %08x with params %s profile %p name %s",
4235 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004236 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004237 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004238 status_t status = desc->open(nullptr, device, address,
4239 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004240
Eric Laurentfe231122017-11-17 17:48:06 -08004241 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004242 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004243 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004244 char *param = audio_device_address_to_parameter(device, address);
4245 mpClientInterface->setParameters(output, String8(param));
4246 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004247 }
Phil Burk00eeb322016-03-31 12:41:00 -07004248 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004249 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004250 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004251 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004252 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004253 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004254 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004255 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004256 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4257 profile->pickAudioProfile(
4258 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004259 config.offload_info.sample_rate = config.sample_rate;
4260 config.offload_info.channel_mask = config.channel_mask;
4261 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004262
4263 status_t status = desc->open(&config, device, address, AUDIO_STREAM_DEFAULT,
4264 AUDIO_OUTPUT_FLAG_NONE, &output);
4265 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004266 output = AUDIO_IO_HANDLE_NONE;
4267 }
Eric Laurentd4692962014-05-05 18:13:44 -07004268 }
4269
Eric Laurentcf2c0212014-07-25 16:20:43 -07004270 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004271 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01004272 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004273 sp<AudioPolicyMix> policyMix;
4274 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004275 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
4276 address.string());
4277 }
François Gaffie036e1e92015-03-19 10:16:24 +01004278 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07004279 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01004280
Eric Laurent87ffa392015-05-22 10:32:38 -07004281 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4282 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004283 // no duplicated output for direct outputs and
4284 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004285 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004286
Eric Laurentd4692962014-05-05 18:13:44 -07004287 //TODO: configure audio effect output stage here
4288
4289 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004290 sp<SwAudioOutputDescriptor> dupOutputDesc =
4291 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4292 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4293 &duplicatedOutput);
4294 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004295 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004296 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004297 } else {
4298 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004299 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004300 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004301 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004302 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004303 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004304 }
Eric Laurente552edb2014-03-10 17:42:56 -07004305 }
4306 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004307 } else {
4308 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004309 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004310 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004311 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004312 profiles.removeAt(profile_index);
4313 profile_index--;
4314 } else {
4315 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004316 // Load digital format info only for digital devices
4317 if (audio_device_is_digital(device)) {
4318 devDesc->importAudioPort(profile);
4319 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004320
François Gaffie53615e22015-03-19 09:24:12 +01004321 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004322 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4323 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004324 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004325 NULL/*patch handle*/, address.string());
4326 }
Eric Laurente552edb2014-03-10 17:42:56 -07004327 ALOGV("checkOutputsForDevice(): adding output %d", output);
4328 }
4329 }
4330
4331 if (profiles.isEmpty()) {
4332 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4333 return BAD_VALUE;
4334 }
Eric Laurentd4692962014-05-05 18:13:44 -07004335 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004336 // check if one opened output is not needed any more after disconnecting one device
4337 for (size_t i = 0; i < mOutputs.size(); i++) {
4338 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004339 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004340 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004341 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004342 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004343 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004344 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004345 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4346 mOutputs.keyAt(i));
4347 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004348 }
Eric Laurente552edb2014-03-10 17:42:56 -07004349 }
4350 }
Eric Laurentd4692962014-05-05 18:13:44 -07004351 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004352 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004353 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4354 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004355 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004356 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004357 "clearing direct output profile %zu on module %s",
4358 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004359 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004360 }
4361 }
4362 }
4363 }
4364 return NO_ERROR;
4365}
4366
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004367status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004368 audio_policy_dev_state_t state,
4369 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004370 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004371{
Paul McLean9080a4c2015-06-18 08:24:02 -07004372 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004373 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004374
4375 if (audio_device_is_digital(device)) {
4376 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004377 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004378 }
4379
Eric Laurentd4692962014-05-05 18:13:44 -07004380 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4381 // first list already open inputs that can be routed to this device
4382 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4383 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004384 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004385 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4386 inputs.add(mInputs.keyAt(input_index));
4387 }
4388 }
4389
4390 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004391 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004392 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004393 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004394 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004395 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004396 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004397
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004398 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004399 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004400 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004401 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004402 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4403 profile_index, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004404 }
Eric Laurentd4692962014-05-05 18:13:44 -07004405 }
4406 }
4407 }
4408
4409 if (profiles.isEmpty() && inputs.isEmpty()) {
4410 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4411 return BAD_VALUE;
4412 }
4413
4414 // open inputs for matching profiles if needed. Direct inputs are also opened to
4415 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4416 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4417
Eric Laurent1c333e22014-05-20 10:48:17 -07004418 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004419
Eric Laurentd4692962014-05-05 18:13:44 -07004420 // nothing to do if one input is already opened for this profile
4421 size_t input_index;
4422 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4423 desc = mInputs.valueAt(input_index);
4424 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004425 if (audio_device_is_digital(device)) {
4426 devDesc->importAudioPort(profile);
4427 }
Eric Laurentd4692962014-05-05 18:13:44 -07004428 break;
4429 }
4430 }
4431 if (input_index != mInputs.size()) {
4432 continue;
4433 }
4434
Eric Laurent3974e3b2017-12-07 17:58:43 -08004435 if (!profile->canOpenNewIo()) {
4436 ALOGW("Max Input number %u already opened for this profile %s",
4437 profile->maxOpenCount, profile->getTagName().c_str());
4438 continue;
4439 }
4440
Eric Laurentfe231122017-11-17 17:48:06 -08004441 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004442 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004443 status_t status = desc->open(nullptr,
4444 device,
4445 address,
4446 AUDIO_SOURCE_MIC,
4447 AUDIO_INPUT_FLAG_NONE,
4448 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004449
Eric Laurentcf2c0212014-07-25 16:20:43 -07004450 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004451 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004452 char *param = audio_device_address_to_parameter(device, address);
4453 mpClientInterface->setParameters(input, String8(param));
4454 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004455 }
Phil Burk00eeb322016-03-31 12:41:00 -07004456 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004457 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004458 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004459 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004460 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004461 }
4462
4463 if (input != 0) {
4464 addInput(input, desc);
4465 }
4466 } // endif input != 0
4467
Eric Laurentcf2c0212014-07-25 16:20:43 -07004468 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004469 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004470 profiles.removeAt(profile_index);
4471 profile_index--;
4472 } else {
4473 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004474 if (audio_device_is_digital(device)) {
4475 devDesc->importAudioPort(profile);
4476 }
Eric Laurentd4692962014-05-05 18:13:44 -07004477 ALOGV("checkInputsForDevice(): adding input %d", input);
4478 }
4479 } // end scan profiles
4480
4481 if (profiles.isEmpty()) {
4482 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4483 return BAD_VALUE;
4484 }
4485 } else {
4486 // Disconnect
4487 // check if one opened input is not needed any more after disconnecting one device
4488 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4489 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004490 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004491 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4492 mInputs.keyAt(input_index));
4493 inputs.add(mInputs.keyAt(input_index));
4494 }
4495 }
4496 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004497 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004498 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004499 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004500 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004501 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004502 if (profile->supportDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004503 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4504 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004505 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004506 }
4507 }
4508 }
4509 } // end disconnect
4510
4511 return NO_ERROR;
4512}
4513
4514
Eric Laurente0720872014-03-11 09:30:41 -07004515void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004516{
4517 ALOGV("closeOutput(%d)", output);
4518
Eric Laurentc75307b2015-03-17 15:29:32 -07004519 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004520 if (outputDesc == NULL) {
4521 ALOGW("closeOutput() unknown output %d", output);
4522 return;
4523 }
François Gaffie036e1e92015-03-19 10:16:24 +01004524 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004525
Eric Laurente552edb2014-03-10 17:42:56 -07004526 // look for duplicated outputs connected to the output being removed.
4527 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004528 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004529 if (dupOutputDesc->isDuplicated() &&
4530 (dupOutputDesc->mOutput1 == outputDesc ||
4531 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004532 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004533 if (dupOutputDesc->mOutput1 == outputDesc) {
4534 outputDesc2 = dupOutputDesc->mOutput2;
4535 } else {
4536 outputDesc2 = dupOutputDesc->mOutput1;
4537 }
4538 // As all active tracks on duplicated output will be deleted,
4539 // and as they were also referenced on the other output, the reference
4540 // count for their stream type must be adjusted accordingly on
4541 // the other output.
Andy Hungaf036da2018-09-21 10:46:21 -07004542 const bool wasActive = outputDesc2->isActive();
4543 for (const auto &clientPair : dupOutputDesc->getActiveClients()) {
4544 outputDesc2->changeStreamActiveCount(clientPair.first, -clientPair.second);
Eric Laurente552edb2014-03-10 17:42:56 -07004545 }
Eric Laurent733ce942017-12-07 12:18:25 -08004546 // stop() will be a no op if the output is still active but is needed in case all
4547 // active streams refcounts where cleared above
4548 if (wasActive) {
4549 outputDesc2->stop();
4550 }
Eric Laurente552edb2014-03-10 17:42:56 -07004551 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4552 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4553
4554 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004555 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004556 }
4557 }
4558
Eric Laurent05b90f82014-08-27 15:32:29 -07004559 nextAudioPortGeneration();
4560
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004561 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004562 if (index >= 0) {
4563 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004564 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004565 mAudioPatches.removeItemsAt(index);
4566 mpClientInterface->onAudioPatchListUpdate();
4567 }
4568
Eric Laurentfe231122017-11-17 17:48:06 -08004569 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004570
François Gaffie53615e22015-03-19 09:24:12 +01004571 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004572 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10004573
4574 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
4575 // no direct outputs are open.
4576 if (getMsdAudioOutDeviceTypes() != AUDIO_DEVICE_NONE) {
4577 bool directOutputOpen = false;
4578 for (size_t i = 0; i < mOutputs.size(); i++) {
4579 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
4580 directOutputOpen = true;
4581 break;
4582 }
4583 }
4584 if (!directOutputOpen) {
4585 ALOGV("no direct outputs open, reset MSD patch");
4586 setMsdPatch();
4587 }
4588 }
Eric Laurent05b90f82014-08-27 15:32:29 -07004589}
4590
4591void AudioPolicyManager::closeInput(audio_io_handle_t input)
4592{
4593 ALOGV("closeInput(%d)", input);
4594
4595 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4596 if (inputDesc == NULL) {
4597 ALOGW("closeInput() unknown input %d", input);
4598 return;
4599 }
4600
Eric Laurent6a94d692014-05-20 11:18:06 -07004601 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004602
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004603 audio_devices_t device = inputDesc->mDevice;
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004604 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004605 if (index >= 0) {
4606 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004607 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004608 mAudioPatches.removeItemsAt(index);
4609 mpClientInterface->onAudioPatchListUpdate();
4610 }
4611
Eric Laurentfe231122017-11-17 17:48:06 -08004612 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004613 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004614
4615 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
4616 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
4617 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
4618 SoundTrigger::setCaptureState(false);
4619 }
Eric Laurente552edb2014-03-10 17:42:56 -07004620}
4621
Eric Laurentc75307b2015-03-17 15:29:32 -07004622SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4623 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004624 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004625{
4626 SortedVector<audio_io_handle_t> outputs;
4627
4628 ALOGVV("getOutputsForDevice() device %04x", device);
4629 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004630 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004631 i, openOutputs.valueAt(i)->isDuplicated(),
4632 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004633 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4634 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4635 outputs.add(openOutputs.keyAt(i));
4636 }
4637 }
4638 return outputs;
4639}
4640
Mikhail Naganov37977152018-07-11 15:54:44 -07004641void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
4642{
4643 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
4644 // output is suspended before any tracks are moved to it
4645 checkA2dpSuspend();
4646 checkOutputForAllStrategies();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004647 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07004648 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00004649 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004650 setMsdPatch();
4651 }
Mikhail Naganov37977152018-07-11 15:54:44 -07004652}
4653
Eric Laurente0720872014-03-11 09:30:41 -07004654void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004655{
4656 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4657 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4658 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4659 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4660
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004661 // also take into account external policy-related changes: add all outputs which are
4662 // associated with policies in the "before" and "after" output vectors
4663 ALOGVV("checkOutputForStrategy(): policy related outputs");
4664 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004665 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004666 if (desc != 0 && desc->mPolicyMix != NULL) {
4667 srcOutputs.add(desc->mIoHandle);
4668 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4669 }
4670 }
4671 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004672 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004673 if (desc != 0 && desc->mPolicyMix != NULL) {
4674 dstOutputs.add(desc->mIoHandle);
4675 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4676 }
4677 }
4678
Mikhail Naganov9de8bd12018-07-23 16:41:31 -07004679 if (srcOutputs != dstOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004680 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4681 // audio from invalidated tracks will be rendered when unmuting
4682 uint32_t maxLatency = 0;
4683 for (audio_io_handle_t srcOut : srcOutputs) {
4684 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4685 if (desc != 0 && maxLatency < desc->latency()) {
4686 maxLatency = desc->latency();
4687 }
4688 }
Eric Laurente552edb2014-03-10 17:42:56 -07004689 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4690 strategy, srcOutputs[0], dstOutputs[0]);
4691 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004692 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004693 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4694 if (desc != 0 && isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004695 setStrategyMute(strategy, true, desc);
Eric Laurentac3a6902018-05-11 16:39:10 -07004696 setStrategyMute(strategy, false, desc, maxLatency * LATENCY_MUTE_FACTOR, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004697 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004698 sp<SourceClientDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004699 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004700 if (source != 0){
4701 connectAudioSource(source);
4702 }
Eric Laurente552edb2014-03-10 17:42:56 -07004703 }
4704
4705 // Move effects associated to this strategy from previous output to new output
4706 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004707 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004708 }
4709 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004710 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004711 if (getStrategy((audio_stream_type_t)i) == strategy) {
4712 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004713 }
4714 }
4715 }
4716}
4717
Eric Laurente0720872014-03-11 09:30:41 -07004718void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004719{
François Gaffie2110e042015-03-24 08:41:51 +01004720 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004721 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004722 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004723 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004724 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004725 checkOutputForStrategy(STRATEGY_SONIFICATION);
4726 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004727 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004728 checkOutputForStrategy(STRATEGY_MEDIA);
4729 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004730 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004731}
4732
Eric Laurente0720872014-03-11 09:30:41 -07004733void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004734{
François Gaffie53615e22015-03-19 09:24:12 +01004735 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004736 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004737 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004738 return;
4739 }
4740
Eric Laurent3a4311c2014-03-17 12:00:47 -07004741 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004742 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4743 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4744 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004745
4746 // if suspended, restore A2DP output if:
4747 // ((SCO device is NOT connected) ||
4748 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4749 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004750 //
Eric Laurentf732e072016-08-03 19:30:28 -07004751 // if not suspended, suspend A2DP output if:
4752 // (SCO device is connected) &&
4753 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4754 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004755 //
4756 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004757 if (!isScoConnected ||
4758 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4759 AUDIO_POLICY_FORCE_BT_SCO) &&
4760 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4761 AUDIO_POLICY_FORCE_BT_SCO) &&
4762 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004763 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004764
4765 mpClientInterface->restoreOutput(a2dpOutput);
4766 mA2dpSuspended = false;
4767 }
4768 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004769 if (isScoConnected &&
4770 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4771 AUDIO_POLICY_FORCE_BT_SCO) ||
4772 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4773 AUDIO_POLICY_FORCE_BT_SCO) ||
4774 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004775 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004776
4777 mpClientInterface->suspendOutput(a2dpOutput);
4778 mA2dpSuspended = true;
4779 }
4780 }
4781}
4782
Eric Laurent97ac8712018-07-27 18:59:02 -07004783template <class IoDescriptor, class Filter>
4784sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4785 IoDescriptor& desc, Filter filter, bool& active, const DeviceVector& devices)
4786{
4787 auto activeClients = desc->clientsList(true /*activeOnly*/);
4788 auto activeClientsWithRoute =
4789 desc->clientsList(true /*activeOnly*/, filter, true /*preferredDevice*/);
4790 active = activeClients.size() > 0;
4791 if (active && activeClients.size() == activeClientsWithRoute.size()) {
4792 return devices.getDeviceFromId(activeClientsWithRoute[0]->preferredDeviceId());
4793 }
4794 return nullptr;
4795}
4796
4797template <class IoCollection, class Filter>
4798sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4799 IoCollection& ioCollection, Filter filter, const DeviceVector& devices)
4800{
4801 sp<DeviceDescriptor> device;
4802 for (size_t i = 0; i < ioCollection.size(); i++) {
4803 auto desc = ioCollection.valueAt(i);
4804 bool active;
4805 sp<DeviceDescriptor> curDevice = findPreferredDevice(desc, filter, active, devices);
4806 if (active && curDevice == nullptr) {
4807 return nullptr;
4808 } else if (curDevice != nullptr) {
4809 device = curDevice;
4810 }
4811 }
4812 return device;
4813}
4814
Eric Laurentc75307b2015-03-17 15:29:32 -07004815audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4816 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004817{
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004818 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004819 if (index >= 0) {
4820 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4821 if (patchDesc->mUid != mUidCached) {
4822 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004823 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004824 return outputDesc->device();
4825 }
4826 }
4827
Eric Laurent97ac8712018-07-27 18:59:02 -07004828 // Honor explicit routing requests only if no client using default routing is active on this
4829 // input: a specific app can not force routing for other apps by setting a preferred device.
4830 bool active; // unused
4831 sp<DeviceDescriptor> deviceDesc =
4832 findPreferredDevice(outputDesc, STRATEGY_NONE, active, mAvailableOutputDevices);
4833 if (deviceDesc != nullptr) {
4834 return deviceDesc->type();
Eric Laurentf3a5a602018-05-22 18:42:55 -07004835 }
4836
Eric Laurente552edb2014-03-10 17:42:56 -07004837 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004838 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004839 // use device for strategy enforced audible
4840 // 2: we are in call or the strategy phone is active on the output:
4841 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004842 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004843 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004844 // 4: the strategy for enforced audible is active but not enforced on the output:
4845 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004846 // 5: the strategy accessibility is active on the output:
4847 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004848 // 6: the strategy "respectful" sonification is active on the output:
4849 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004850 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004851 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004852 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004853 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004854 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004855 // use device for strategy t-t-s
Eric Laurent484e9272018-06-07 17:29:23 -07004856
4857 // FIXME: extend use of isStrategyActiveOnSameModule() to all strategies
4858 // with a refined rule considering mutually exclusive devices (using same backend)
4859 // as opposed to all streams on the same audio HAL module.
Eric Laurent97ac8712018-07-27 18:59:02 -07004860 audio_devices_t device = AUDIO_DEVICE_NONE;
François Gaffiead3183e2015-03-18 16:55:35 +01004861 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004862 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004863 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4864 } else if (isInCall() ||
Eric Laurent484e9272018-06-07 17:29:23 -07004865 isStrategyActiveOnSameModule(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004866 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
Yung Ti Su3e7eb5e2018-06-13 11:48:42 +08004867 } else if (isStrategyActiveOnSameModule(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004868 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004869 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
4870 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004871 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4872 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004873 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004874 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004875 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004876 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004877 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004878 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004879 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004880 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004881 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004882 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004883 }
4884
Eric Laurent1c333e22014-05-20 10:48:17 -07004885 ALOGV("getNewOutputDevice() selected device %x", device);
4886 return device;
4887}
4888
Eric Laurentfb66dd92016-01-28 18:32:03 -08004889audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004890{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004891 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004892
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004893 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004894 if (index >= 0) {
4895 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4896 if (patchDesc->mUid != mUidCached) {
4897 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004898 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004899 return inputDesc->mDevice;
4900 }
4901 }
4902
Eric Laurent97ac8712018-07-27 18:59:02 -07004903 // Honor explicit routing requests only if no client using default routing is active on this
4904 // input: a specific app can not force routing for other apps by setting a preferred device.
4905 bool active;
4906 sp<DeviceDescriptor> deviceDesc =
4907 findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
4908 if (deviceDesc != nullptr) {
4909 return deviceDesc->type();
4910 }
4911
Eric Laurentdc95a252018-04-12 12:46:56 -07004912 // If we are not in call and no client is active on this input, this methods returns
4913 // AUDIO_DEVICE_NONE, causing the patch on the input stream to be released.
Eric Laurentfb66dd92016-01-28 18:32:03 -08004914 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
Eric Laurentdc95a252018-04-12 12:46:56 -07004915 if (source == AUDIO_SOURCE_DEFAULT && isInCall()) {
4916 source = AUDIO_SOURCE_VOICE_COMMUNICATION;
4917 }
4918 if (source != AUDIO_SOURCE_DEFAULT) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08004919 device = getDeviceAndMixForInputSource(source);
4920 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004921
Eric Laurente552edb2014-03-10 17:42:56 -07004922 return device;
4923}
4924
Eric Laurent794fde22016-03-11 09:50:45 -08004925bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4926 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004927 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004928}
4929
Eric Laurente0720872014-03-11 09:30:41 -07004930uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004931 return (uint32_t)getStrategy(stream);
4932}
4933
Eric Laurente0720872014-03-11 09:30:41 -07004934audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004935 // By checking the range of stream before calling getStrategy, we avoid
4936 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4937 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004938 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004939 return AUDIO_DEVICE_NONE;
4940 }
Eric Laurentb0688d62018-08-14 15:49:18 -07004941 audio_devices_t activeDevices = AUDIO_DEVICE_NONE;
Eric Laurent28d09f02016-03-08 10:43:05 -08004942 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004943 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4944 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004945 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004946 }
Eric Laurent794fde22016-03-11 09:50:45 -08004947 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004948 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004949 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Eric Laurentb0688d62018-08-14 15:49:18 -07004950 devices |= curDevices;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004951 for (audio_io_handle_t output : getOutputsForDevice(curDevices, mOutputs)) {
4952 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08004953 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurentb0688d62018-08-14 15:49:18 -07004954 activeDevices |= outputDesc->device();
Eric Laurent28d09f02016-03-08 10:43:05 -08004955 }
4956 }
Eric Laurente552edb2014-03-10 17:42:56 -07004957 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004958
Eric Laurentb0688d62018-08-14 15:49:18 -07004959 // Favor devices selected on active streams if any to report correct device in case of
4960 // explicit device selection
4961 if (activeDevices != AUDIO_DEVICE_NONE) {
4962 devices = activeDevices;
4963 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004964 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4965 and doesn't really need to.*/
4966 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4967 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4968 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4969 }
Eric Laurente552edb2014-03-10 17:42:56 -07004970 return devices;
4971}
4972
François Gaffie2110e042015-03-24 08:41:51 +01004973routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4974{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004975 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004976 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004977}
4978
Eric Laurent97ac8712018-07-27 18:59:02 -07004979routing_strategy AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004980 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004981 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004982 return STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004983 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004984 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004985 return STRATEGY_ENFORCED_AUDIBLE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004986 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004987 // usage to strategy mapping
Eric Laurent97ac8712018-07-27 18:59:02 -07004988 return mEngine->getStrategyForUsage(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004989}
4990
Eric Laurente0720872014-03-11 09:30:41 -07004991void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004992 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004993 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004994 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4995 updateDevicesAndOutputs();
4996 break;
4997 default:
4998 break;
4999 }
5000}
5001
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005002uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07005003
5004 // skip beacon mute management if a dedicated TTS output is available
5005 if (mTtsOutputAvailable) {
5006 return 0;
5007 }
5008
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005009 switch(event) {
5010 case STARTING_OUTPUT:
5011 mBeaconMuteRefCount++;
5012 break;
5013 case STOPPING_OUTPUT:
5014 if (mBeaconMuteRefCount > 0) {
5015 mBeaconMuteRefCount--;
5016 }
5017 break;
5018 case STARTING_BEACON:
5019 mBeaconPlayingRefCount++;
5020 break;
5021 case STOPPING_BEACON:
5022 if (mBeaconPlayingRefCount > 0) {
5023 mBeaconPlayingRefCount--;
5024 }
5025 break;
5026 }
5027
5028 if (mBeaconMuteRefCount > 0) {
5029 // any playback causes beacon to be muted
5030 return setBeaconMute(true);
5031 } else {
5032 // no other playback: unmute when beacon starts playing, mute when it stops
5033 return setBeaconMute(mBeaconPlayingRefCount == 0);
5034 }
5035}
5036
5037uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5038 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5039 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5040 // keep track of muted state to avoid repeating mute/unmute operations
5041 if (mBeaconMuted != mute) {
5042 // mute/unmute AUDIO_STREAM_TTS on all outputs
5043 ALOGV("\t muting %d", mute);
5044 uint32_t maxLatency = 0;
5045 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005046 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005047 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07005048 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005049 0 /*delay*/, AUDIO_DEVICE_NONE);
5050 const uint32_t latency = desc->latency() * 2;
5051 if (latency > maxLatency) {
5052 maxLatency = latency;
5053 }
5054 }
5055 mBeaconMuted = mute;
5056 return maxLatency;
5057 }
5058 return 0;
5059}
5060
Eric Laurente0720872014-03-11 09:30:41 -07005061audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01005062 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005063{
Eric Laurent97ac8712018-07-27 18:59:02 -07005064 // Honor explicit routing requests only if all active clients have a preferred route in which
5065 // case the last active client route is used
5066 sp<DeviceDescriptor> deviceDesc = findPreferredDevice(mOutputs, strategy, mAvailableOutputDevices);
5067 if (deviceDesc != nullptr) {
5068 return deviceDesc->type();
Paul McLeanaa981192015-03-21 09:55:15 -07005069 }
5070
Eric Laurente552edb2014-03-10 17:42:56 -07005071 if (fromCache) {
5072 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
5073 strategy, mDeviceForStrategy[strategy]);
5074 return mDeviceForStrategy[strategy];
5075 }
François Gaffie2110e042015-03-24 08:41:51 +01005076 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07005077}
5078
Eric Laurente0720872014-03-11 09:30:41 -07005079void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005080{
5081 for (int i = 0; i < NUM_STRATEGIES; i++) {
5082 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
5083 }
5084 mPreviousOutputs = mOutputs;
5085}
5086
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005087uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005088 audio_devices_t prevDevice,
5089 uint32_t delayMs)
5090{
5091 // mute/unmute strategies using an incompatible device combination
5092 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5093 // if unmuting, unmute only after the specified delay
5094 if (outputDesc->isDuplicated()) {
5095 return 0;
5096 }
5097
5098 uint32_t muteWaitMs = 0;
5099 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07005100 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005101
5102 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
5103 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07005104 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07005105 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
5106 bool doMute = false;
5107
5108 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
5109 doMute = true;
5110 outputDesc->mStrategyMutedByDevice[i] = true;
5111 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
5112 doMute = true;
5113 outputDesc->mStrategyMutedByDevice[i] = false;
5114 }
Eric Laurent99401132014-05-07 19:48:15 -07005115 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005116 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005117 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005118 // skip output if it does not share any device with current output
5119 if ((desc->supportedDevices() & outputDesc->supportedDevices())
5120 == AUDIO_DEVICE_NONE) {
5121 continue;
5122 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005123 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07005124 mute ? "muting" : "unmuting", i, curDevice);
5125 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005126 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005127 if (mute) {
5128 // FIXME: should not need to double latency if volume could be applied
5129 // immediately by the audioflinger mixer. We must account for the delay
5130 // between now and the next time the audioflinger thread for this output
5131 // will process a buffer (which corresponds to one buffer size,
5132 // usually 1/2 or 1/4 of the latency).
5133 if (muteWaitMs < desc->latency() * 2) {
5134 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005135 }
5136 }
5137 }
5138 }
5139 }
5140 }
5141
Eric Laurent99401132014-05-07 19:48:15 -07005142 // temporary mute output if device selection changes to avoid volume bursts due to
5143 // different per device volumes
5144 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005145 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5146 // temporary mute duration is conservatively set to 4 times the reported latency
5147 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5148 if (muteWaitMs < tempMuteWaitMs) {
5149 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005150 }
Eric Laurentdc462862016-07-19 12:29:53 -07005151
Eric Laurent99401132014-05-07 19:48:15 -07005152 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005153 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005154 // make sure that we do not start the temporary mute period too early in case of
5155 // delayed device change
5156 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005157 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07005158 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07005159 }
5160 }
5161 }
5162
Eric Laurente552edb2014-03-10 17:42:56 -07005163 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5164 if (muteWaitMs > delayMs) {
5165 muteWaitMs -= delayMs;
5166 usleep(muteWaitMs * 1000);
5167 return muteWaitMs;
5168 }
5169 return 0;
5170}
5171
Eric Laurentc75307b2015-03-17 15:29:32 -07005172uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005173 audio_devices_t device,
5174 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07005175 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005176 audio_patch_handle_t *patchHandle,
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005177 const char *address,
5178 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005179{
Eric Laurentc75307b2015-03-17 15:29:32 -07005180 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005181 AudioParameter param;
5182 uint32_t muteWaitMs;
5183
5184 if (outputDesc->isDuplicated()) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005185 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs,
5186 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
5187 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs,
5188 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005189 return muteWaitMs;
5190 }
5191 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5192 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07005193 if ((device != AUDIO_DEVICE_NONE) &&
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005194 ((device & outputDesc->supportedDevices()) == AUDIO_DEVICE_NONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005195 return 0;
5196 }
5197
5198 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07005199 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07005200
5201 audio_devices_t prevDevice = outputDesc->mDevice;
5202
Paul McLeanaa981192015-03-21 09:55:15 -07005203 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005204
5205 if (device != AUDIO_DEVICE_NONE) {
5206 outputDesc->mDevice = device;
5207 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005208
5209 // if the outputs are not materially active, there is no need to mute.
5210 if (requiresMuteCheck) {
5211 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
5212 } else {
5213 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5214 muteWaitMs = 0;
5215 }
Eric Laurente552edb2014-03-10 17:42:56 -07005216
5217 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005218 // the requested device is AUDIO_DEVICE_NONE
5219 // OR the requested device is the same as current device
5220 // AND force is not specified
5221 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07005222 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07005223 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
5224 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005225 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005226 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005227 return muteWaitMs;
5228 }
5229
5230 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07005231
Eric Laurente552edb2014-03-10 17:42:56 -07005232 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07005233 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005234 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005235 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07005236 DeviceVector deviceList;
5237 if ((address == NULL) || (strlen(address) == 0)) {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005238 deviceList = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurentc40d9692016-04-13 19:14:13 -07005239 } else {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005240 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
5241 device, String8(address));
5242 if (deviceDesc) deviceList.add(deviceDesc);
Eric Laurentc40d9692016-04-13 19:14:13 -07005243 }
5244
Eric Laurent1c333e22014-05-20 10:48:17 -07005245 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005246 PatchBuilder patchBuilder;
5247 patchBuilder.addSource(outputDesc);
Eric Laurent1c333e22014-05-20 10:48:17 -07005248 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005249 patchBuilder.addSink(deviceList.itemAt(i));
Eric Laurent1c333e22014-05-20 10:48:17 -07005250 }
Mikhail Naganovdc769682018-05-04 15:34:08 -07005251 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005252 }
bryant_liuf5e7e792014-08-19 20:07:05 +08005253
5254 // inform all input as well
5255 for (size_t i = 0; i < mInputs.size(); i++) {
5256 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01005257 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08005258 AudioParameter inputCmd = AudioParameter();
5259 ALOGV("%s: inform input %d of device:%d", __func__,
5260 inputDescriptor->mIoHandle, device);
5261 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
5262 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
5263 inputCmd.toString(),
5264 delayMs);
5265 }
5266 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005267 }
Eric Laurente552edb2014-03-10 17:42:56 -07005268
5269 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07005270 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005271
5272 return muteWaitMs;
5273}
5274
Eric Laurentc75307b2015-03-17 15:29:32 -07005275status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005276 int delayMs,
5277 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005278{
Eric Laurent6a94d692014-05-20 11:18:06 -07005279 ssize_t index;
5280 if (patchHandle) {
5281 index = mAudioPatches.indexOfKey(*patchHandle);
5282 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005283 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005284 }
5285 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005286 return INVALID_OPERATION;
5287 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005288 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5289 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005290 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005291 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005292 removeAudioPatch(patchDesc->mHandle);
5293 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005294 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005295 return status;
5296}
5297
5298status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5299 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005300 bool force,
5301 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005302{
5303 status_t status = NO_ERROR;
5304
Eric Laurent1f2f2232014-06-02 12:01:23 -07005305 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005306 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5307 inputDesc->mDevice = device;
5308
Mikhail Naganov708e0382018-05-30 09:53:04 -07005309 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005310 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005311 PatchBuilder patchBuilder;
5312 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005313 // AUDIO_SOURCE_HOTWORD is for internal use only:
5314 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07005315 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5316 auto result = usecase;
5317 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5318 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5319 }
5320 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07005321 //only one input device for now
Mikhail Naganovdc769682018-05-04 15:34:08 -07005322 addSource(deviceList.itemAt(0));
5323 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005324 }
5325 }
5326 return status;
5327}
5328
Eric Laurent6a94d692014-05-20 11:18:06 -07005329status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5330 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005331{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005332 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005333 ssize_t index;
5334 if (patchHandle) {
5335 index = mAudioPatches.indexOfKey(*patchHandle);
5336 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005337 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005338 }
5339 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005340 return INVALID_OPERATION;
5341 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005342 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5343 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005344 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005345 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005346 removeAudioPatch(patchDesc->mHandle);
5347 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005348 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005349 return status;
5350}
5351
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005352sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005353 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005354 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005355 audio_format_t& format,
5356 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005357 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005358{
5359 // Choose an input profile based on the requested capture parameters: select the first available
5360 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005361 //
5362 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5363 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005364
Glenn Kasten730b9262018-03-29 15:01:26 -07005365 sp<IOProfile> firstInexact;
5366 uint32_t updatedSamplingRate = 0;
5367 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5368 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005369 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005370 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005371 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005372 //updatedFormat = format;
Eric Laurent275e8e92014-11-30 15:14:47 -08005373 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005374 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005375 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005376 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005377 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005378 &channelMask /*updatedChannelMask*/,
5379 // FIXME ugly cast
5380 (audio_output_flags_t) flags,
5381 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005382 return profile;
5383 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005384 if (firstInexact == nullptr && profile->isCompatibleProfile(device, address,
5385 samplingRate,
5386 &updatedSamplingRate,
5387 format,
5388 &updatedFormat,
5389 channelMask,
5390 &updatedChannelMask,
5391 // FIXME ugly cast
5392 (audio_output_flags_t) flags,
5393 false /*exactMatchRequiredForInputFlags*/)) {
5394 firstInexact = profile;
5395 }
5396
Eric Laurente552edb2014-03-10 17:42:56 -07005397 }
5398 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005399 if (firstInexact != nullptr) {
5400 samplingRate = updatedSamplingRate;
5401 format = updatedFormat;
5402 channelMask = updatedChannelMask;
5403 return firstInexact;
5404 }
Eric Laurente552edb2014-03-10 17:42:56 -07005405 return NULL;
5406}
5407
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005408
5409audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005410 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005411{
Eric Laurent97ac8712018-07-27 18:59:02 -07005412 // Honor explicit routing requests only if all active clients have a preferred route in which
5413 // case the last active client route is used
5414 sp<DeviceDescriptor> deviceDesc =
5415 findPreferredDevice(mInputs, inputSource, mAvailableInputDevices);
5416 if (deviceDesc != nullptr) {
5417 return deviceDesc->type();
5418 }
5419
5420
François Gaffie036e1e92015-03-19 10:16:24 +01005421 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5422 audio_devices_t selectedDeviceFromMix =
5423 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005424
François Gaffie036e1e92015-03-19 10:16:24 +01005425 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5426 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005427 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005428 return getDeviceForInputSource(inputSource);
5429}
5430
5431audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5432{
Eric Laurent97ac8712018-07-27 18:59:02 -07005433 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005434}
5435
Eric Laurente0720872014-03-11 09:30:41 -07005436float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005437 int index,
5438 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005439{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005440 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005441
5442 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5443 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5444 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5445 // the ringtone volume
5446 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5447 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5448 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5449 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5450 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5451 }
5452
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005453 // in-call: always cap volume by voice volume + some low headroom
5454 if ((stream != AUDIO_STREAM_VOICE_CALL) &&
Eric Laurent7731b5a2018-04-06 15:47:22 -07005455 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005456 switch (stream) {
5457 case AUDIO_STREAM_SYSTEM:
5458 case AUDIO_STREAM_RING:
5459 case AUDIO_STREAM_MUSIC:
5460 case AUDIO_STREAM_ALARM:
5461 case AUDIO_STREAM_NOTIFICATION:
5462 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5463 case AUDIO_STREAM_DTMF:
5464 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005465 int voiceVolumeIndex =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005466 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, device);
Eric Laurent7731b5a2018-04-06 15:47:22 -07005467 const float maxVoiceVolDb =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005468 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, device)
Eric Laurent7731b5a2018-04-06 15:47:22 -07005469 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005470 if (volumeDB > maxVoiceVolDb) {
5471 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5472 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5473 volumeDB = maxVoiceVolDb;
5474 }
5475 } break;
5476 default:
5477 break;
5478 }
5479 }
5480
Eric Laurente552edb2014-03-10 17:42:56 -07005481 // if a headset is connected, apply the following rules to ring tones and notifications
5482 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005483 // - always attenuate notifications volume by 6dB
5484 // - attenuate ring tones volume by 6dB unless music is not playing and
5485 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005486 // - if music is playing, always limit the volume to current music volume,
5487 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005488 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005489 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5490 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5491 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005492 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005493 AUDIO_DEVICE_OUT_USB_HEADSET |
5494 AUDIO_DEVICE_OUT_HEARING_AID)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005495 ((stream_strategy == STRATEGY_SONIFICATION)
5496 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005497 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005498 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005499 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005500 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005501 // when the phone is ringing we must consider that music could have been paused just before
5502 // by the music application and behave as if music was active if the last music track was
5503 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005504 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005505 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005506 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005507 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005508 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005509 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5510 musicDevice),
5511 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005512 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5513 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005514 if (volumeDB > minVolDB) {
5515 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005516 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005517 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005518 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5519 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5520 // on A2DP, also ensure notification volume is not too low compared to media when
5521 // intended to be played
5522 if ((volumeDB > -96.0f) &&
5523 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5524 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5525 stream, device,
5526 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5527 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5528 }
5529 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005530 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5531 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005532 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005533 }
5534 }
5535
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005536 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005537}
5538
Eric Laurent3839bc02018-07-10 18:33:34 -07005539int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
5540 audio_stream_type_t srcStream,
5541 audio_stream_type_t dstStream)
5542{
5543 if (srcStream == dstStream) {
5544 return srcIndex;
5545 }
5546 float minSrc = (float)mVolumeCurves->getVolumeIndexMin(srcStream);
5547 float maxSrc = (float)mVolumeCurves->getVolumeIndexMax(srcStream);
5548 float minDst = (float)mVolumeCurves->getVolumeIndexMin(dstStream);
5549 float maxDst = (float)mVolumeCurves->getVolumeIndexMax(dstStream);
5550
5551 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
5552}
5553
Eric Laurente0720872014-03-11 09:30:41 -07005554status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005555 int index,
5556 const sp<AudioOutputDescriptor>& outputDesc,
5557 audio_devices_t device,
5558 int delayMs,
5559 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005560{
Eric Laurente552edb2014-03-10 17:42:56 -07005561 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005562 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005563 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005564 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005565 return NO_ERROR;
5566 }
François Gaffie2110e042015-03-24 08:41:51 +01005567 audio_policy_forced_cfg_t forceUseForComm =
5568 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005569 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005570 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5571 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005572 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005573 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005574 return INVALID_OPERATION;
5575 }
5576
Eric Laurentc75307b2015-03-17 15:29:32 -07005577 if (device == AUDIO_DEVICE_NONE) {
5578 device = outputDesc->device();
5579 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005580
Eric Laurentffbc80f2015-03-18 18:30:19 -07005581 float volumeDb = computeVolume(stream, index, device);
HW Leeda7581e2018-05-22 18:31:34 +08005582 if (outputDesc->isFixedVolume(device) ||
5583 // Force VoIP volume to max for bluetooth SCO
5584 ((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
5585 (device & AUDIO_DEVICE_OUT_ALL_SCO) != 0)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005586 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005587 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005588
Eric Laurentffbc80f2015-03-18 18:30:19 -07005589 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005590
Eric Laurent3b73df72014-03-11 09:06:29 -07005591 if (stream == AUDIO_STREAM_VOICE_CALL ||
5592 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005593 float voiceVolume;
5594 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005595 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurent3839bc02018-07-10 18:33:34 -07005596 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005597 } else {
5598 voiceVolume = 1.0;
5599 }
5600
Eric Laurent18fba842016-03-31 14:41:26 -07005601 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005602 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5603 mLastVoiceVolume = voiceVolume;
5604 }
5605 }
5606
5607 return NO_ERROR;
5608}
5609
Eric Laurentc75307b2015-03-17 15:29:32 -07005610void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5611 audio_devices_t device,
5612 int delayMs,
5613 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005614{
Eric Laurentc75307b2015-03-17 15:29:32 -07005615 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005616
Eric Laurent794fde22016-03-11 09:50:45 -08005617 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005618 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005619 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005620 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005621 device,
5622 delayMs,
5623 force);
5624 }
5625}
5626
Eric Laurente0720872014-03-11 09:30:41 -07005627void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005628 bool on,
5629 const sp<AudioOutputDescriptor>& outputDesc,
5630 int delayMs,
5631 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005632{
Eric Laurent72249d52015-06-08 11:12:15 -07005633 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5634 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005635 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005636 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005637 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005638 }
5639 }
5640}
5641
Eric Laurente0720872014-03-11 09:30:41 -07005642void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005643 bool on,
5644 const sp<AudioOutputDescriptor>& outputDesc,
5645 int delayMs,
5646 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005647{
Eric Laurente552edb2014-03-10 17:42:56 -07005648 if (device == AUDIO_DEVICE_NONE) {
5649 device = outputDesc->device();
5650 }
5651
Eric Laurentc75307b2015-03-17 15:29:32 -07005652 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5653 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005654
5655 if (on) {
5656 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005657 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005658 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005659 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005660 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005661 }
5662 }
5663 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5664 outputDesc->mMuteCount[stream]++;
5665 } else {
5666 if (outputDesc->mMuteCount[stream] == 0) {
5667 ALOGV("setStreamMute() unmuting non muted stream!");
5668 return;
5669 }
5670 if (--outputDesc->mMuteCount[stream] == 0) {
5671 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005672 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005673 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005674 device,
5675 delayMs);
5676 }
5677 }
5678}
5679
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005680audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5681{
5682 // flags to stream type mapping
5683 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5684 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5685 }
5686 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5687 return AUDIO_STREAM_BLUETOOTH_SCO;
5688 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005689 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5690 return AUDIO_STREAM_TTS;
5691 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005692
Ari Hausman-Cohen5c00d012018-06-26 17:09:11 -07005693 return audio_usage_to_stream_type(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005694}
Eric Laurente83b55d2014-11-14 10:06:21 -08005695
François Gaffie53615e22015-03-19 09:24:12 +01005696bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5697{
Eric Laurente83b55d2014-11-14 10:06:21 -08005698 // has flags that map to a strategy?
5699 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5700 return true;
5701 }
5702
5703 // has known usage?
5704 switch (paa->usage) {
5705 case AUDIO_USAGE_UNKNOWN:
5706 case AUDIO_USAGE_MEDIA:
5707 case AUDIO_USAGE_VOICE_COMMUNICATION:
5708 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5709 case AUDIO_USAGE_ALARM:
5710 case AUDIO_USAGE_NOTIFICATION:
5711 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5712 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5713 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5714 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5715 case AUDIO_USAGE_NOTIFICATION_EVENT:
5716 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5717 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5718 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5719 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005720 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005721 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005722 break;
5723 default:
5724 return false;
5725 }
5726 return true;
5727}
5728
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005729bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005730 routing_strategy strategy, uint32_t inPastMs,
5731 nsecs_t sysTime) const
5732{
5733 if ((sysTime == 0) && (inPastMs != 0)) {
5734 sysTime = systemTime();
5735 }
Eric Laurent794fde22016-03-11 09:50:45 -08005736 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005737 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurent97ac8712018-07-27 18:59:02 -07005738 (STRATEGY_NONE == strategy)) &&
François Gaffiead3183e2015-03-18 16:55:35 +01005739 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5740 return true;
5741 }
5742 }
5743 return false;
5744}
5745
Eric Laurent484e9272018-06-07 17:29:23 -07005746bool AudioPolicyManager::isStrategyActiveOnSameModule(const sp<AudioOutputDescriptor>& outputDesc,
5747 routing_strategy strategy, uint32_t inPastMs,
5748 nsecs_t sysTime) const
5749{
5750 for (size_t i = 0; i < mOutputs.size(); i++) {
5751 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5752 if (outputDesc->sharesHwModuleWith(desc)
5753 && isStrategyActive(desc, strategy, inPastMs, sysTime)) {
5754 return true;
5755 }
5756 }
5757 return false;
5758}
5759
François Gaffie2110e042015-03-24 08:41:51 +01005760audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5761{
5762 return mEngine->getForceUse(usage);
5763}
5764
5765bool AudioPolicyManager::isInCall()
5766{
5767 return isStateInCall(mEngine->getPhoneState());
5768}
5769
5770bool AudioPolicyManager::isStateInCall(int state)
5771{
5772 return is_state_in_call(state);
5773}
5774
Eric Laurentd60560a2015-04-10 11:31:20 -07005775void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5776{
5777 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005778 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5779 if (sourceDesc->srcDevice()->equals(deviceDesc)) {
5780 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->portId());
5781 stopAudioSource(sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005782 }
5783 }
5784
5785 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5786 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5787 bool release = false;
5788 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5789 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5790 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5791 source->ext.device.type == deviceDesc->type()) {
5792 release = true;
5793 }
5794 }
5795 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5796 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5797 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5798 sink->ext.device.type == deviceDesc->type()) {
5799 release = true;
5800 }
5801 }
5802 if (release) {
5803 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5804 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5805 }
5806 }
5807}
5808
Phil Burk09bc4612016-02-24 15:58:15 -08005809// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005810void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5811 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005812 // TODO Set this based on Config properties.
5813 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005814
5815 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5816 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005817 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005818
jiabin81772902018-04-02 17:52:27 -07005819 // If MANUAL, keep the supported surround sound formats as current enabled ones.
5820 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
5821 formats.clear();
5822 for (auto it = mSurroundFormats.begin(); it != mSurroundFormats.end(); it++) {
5823 formats.add(*it);
Phil Burk09bc4612016-02-24 15:58:15 -08005824 }
jiabin81772902018-04-02 17:52:27 -07005825 // Always enable IEC61937 when in MANUAL mode.
5826 formats.add(AUDIO_FORMAT_IEC61937);
5827 } else { // NEVER, AUTO or ALWAYS
5828 // Analyze original support for various formats.
5829 bool supportsAC3 = false;
5830 bool supportsOtherSurround = false;
5831 bool supportsIEC61937 = false;
5832 mSurroundFormats.clear();
5833 for (ssize_t formatIndex = 0; formatIndex < (ssize_t)formats.size(); formatIndex++) {
5834 audio_format_t format = formats[formatIndex];
5835 switch (format) {
5836 case AUDIO_FORMAT_AC3:
5837 supportsAC3 = true;
5838 break;
5839 case AUDIO_FORMAT_E_AC3:
5840 case AUDIO_FORMAT_DTS:
5841 case AUDIO_FORMAT_DTS_HD:
5842 // If ALWAYS, remove all other surround formats here
5843 // since we will add them later.
5844 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5845 formats.removeAt(formatIndex);
5846 formatIndex--;
5847 }
5848 supportsOtherSurround = true;
5849 break;
5850 case AUDIO_FORMAT_IEC61937:
5851 supportsIEC61937 = true;
5852 break;
5853 default:
5854 break;
5855 }
5856 }
Phil Burk09bc4612016-02-24 15:58:15 -08005857
jiabin81772902018-04-02 17:52:27 -07005858 // Modify formats based on surround preferences.
5859 // If NEVER, remove support for surround formats.
5860 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5861 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5862 // Remove surround sound related formats.
5863 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5864 audio_format_t format = formats[formatIndex];
5865 switch(format) {
5866 case AUDIO_FORMAT_AC3:
5867 case AUDIO_FORMAT_E_AC3:
5868 case AUDIO_FORMAT_DTS:
5869 case AUDIO_FORMAT_DTS_HD:
5870 case AUDIO_FORMAT_IEC61937:
5871 formats.removeAt(formatIndex);
5872 break;
5873 default:
5874 formatIndex++; // keep it
5875 break;
5876 }
5877 }
5878 supportsAC3 = false;
5879 supportsOtherSurround = false;
5880 supportsIEC61937 = false;
5881 }
5882 } else { // AUTO or ALWAYS
5883 // Most TVs support AC3 even if they do not report it in the EDID.
5884 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
5885 && !supportsAC3) {
5886 formats.add(AUDIO_FORMAT_AC3);
5887 supportsAC3 = true;
5888 }
5889
5890 // If ALWAYS, add support for raw surround formats if all are missing.
5891 // This assumes that if any of these formats are reported by the HAL
5892 // then the report is valid and should not be modified.
5893 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5894 formats.add(AUDIO_FORMAT_E_AC3);
5895 formats.add(AUDIO_FORMAT_DTS);
5896 formats.add(AUDIO_FORMAT_DTS_HD);
5897 supportsOtherSurround = true;
5898 }
5899
5900 // Add support for IEC61937 if any raw surround supported.
5901 // The HAL could do this but add it here, just in case.
5902 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
5903 formats.add(AUDIO_FORMAT_IEC61937);
5904 supportsIEC61937 = true;
5905 }
5906
5907 // Add reported surround sound formats to enabled surround formats.
5908 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
Phil Burk07ac1142016-03-25 13:39:29 -07005909 audio_format_t format = formats[formatIndex];
Mikhail Naganov02743e22018-11-28 15:56:55 -08005910 if (mConfig.getSurroundFormats().count(format) != 0) {
5911 mSurroundFormats.insert(format);
Phil Burk07ac1142016-03-25 13:39:29 -07005912 }
Phil Burk09bc4612016-02-24 15:58:15 -08005913 }
Phil Burk07ac1142016-03-25 13:39:29 -07005914 }
Phil Burk09bc4612016-02-24 15:58:15 -08005915 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005916}
5917
5918// Modify the list of channel masks supported.
5919void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
5920 ChannelsVector &channelMasks = *channelMasksPtr;
5921 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5922 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5923
5924 // If NEVER, then remove support for channelMasks > stereo.
5925 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5926 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5927 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5928 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5929 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5930 channelMasks.removeAt(maskIndex);
5931 } else {
5932 maskIndex++;
5933 }
5934 }
jiabin81772902018-04-02 17:52:27 -07005935 // If ALWAYS or MANUAL, then make sure we at least support 5.1
5936 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
5937 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005938 bool supports5dot1 = false;
5939 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005940 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005941 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5942 supports5dot1 = true;
5943 break;
5944 }
5945 }
5946 // If not then add 5.1 support.
5947 if (!supports5dot1) {
5948 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
5949 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
5950 }
Phil Burk09bc4612016-02-24 15:58:15 -08005951 }
5952}
5953
Phil Burk00eeb322016-03-31 12:41:00 -07005954void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
5955 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005956 AudioProfileVector &profiles)
5957{
5958 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07005959
François Gaffie112b0af2015-11-19 16:13:25 +01005960 // Format MUST be checked first to update the list of AudioProfile
5961 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005962 reply = mpClientInterface->getParameters(
5963 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07005964 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005965 AudioParameter repliedParameters(reply);
5966 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005967 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005968 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5969 return;
5970 }
Phil Burk09bc4612016-02-24 15:58:15 -08005971 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07005972 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005973 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005974 }
Phil Burk09bc4612016-02-24 15:58:15 -08005975 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005976 }
François Gaffie112b0af2015-11-19 16:13:25 +01005977
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005978 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08005979 ChannelsVector channelMasks;
5980 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005981 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07005982 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01005983
5984 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005985 reply = mpClientInterface->getParameters(
5986 ioHandle,
5987 requestedParameters.toString() + ";" +
5988 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01005989 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005990 AudioParameter repliedParameters(reply);
5991 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005992 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005993 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005994 }
5995 }
5996 if (profiles.hasDynamicChannelsFor(format)) {
5997 reply = mpClientInterface->getParameters(ioHandle,
5998 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07005999 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01006000 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006001 AudioParameter repliedParameters(reply);
6002 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006003 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006004 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07006005 if (device == AUDIO_DEVICE_OUT_HDMI) {
6006 filterSurroundChannelMasks(&channelMasks);
6007 }
François Gaffie112b0af2015-11-19 16:13:25 +01006008 }
6009 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08006010 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006011 }
6012}
Eric Laurentd60560a2015-04-10 11:31:20 -07006013
Mikhail Naganovdc769682018-05-04 15:34:08 -07006014status_t AudioPolicyManager::installPatch(const char *caller,
6015 audio_patch_handle_t *patchHandle,
6016 AudioIODescriptorInterface *ioDescriptor,
6017 const struct audio_patch *patch,
6018 int delayMs)
6019{
6020 ssize_t index = mAudioPatches.indexOfKey(
6021 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6022 *patchHandle : ioDescriptor->getPatchHandle());
6023 sp<AudioPatch> patchDesc;
6024 status_t status = installPatch(
6025 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6026 if (status == NO_ERROR) {
6027 ioDescriptor->setPatchHandle(patchDesc->mHandle);
6028 }
6029 return status;
6030}
6031
6032status_t AudioPolicyManager::installPatch(const char *caller,
6033 ssize_t index,
6034 audio_patch_handle_t *patchHandle,
6035 const struct audio_patch *patch,
6036 int delayMs,
6037 uid_t uid,
6038 sp<AudioPatch> *patchDescPtr)
6039{
6040 sp<AudioPatch> patchDesc;
6041 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6042 if (index >= 0) {
6043 patchDesc = mAudioPatches.valueAt(index);
6044 afPatchHandle = patchDesc->mAfPatchHandle;
6045 }
6046
6047 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6048 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6049 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6050 if (status == NO_ERROR) {
6051 if (index < 0) {
6052 patchDesc = new AudioPatch(patch, uid);
6053 addAudioPatch(patchDesc->mHandle, patchDesc);
6054 } else {
6055 patchDesc->mPatch = *patch;
6056 }
6057 patchDesc->mAfPatchHandle = afPatchHandle;
6058 if (patchHandle) {
6059 *patchHandle = patchDesc->mHandle;
6060 }
6061 nextAudioPortGeneration();
6062 mpClientInterface->onAudioPatchListUpdate();
6063 }
6064 if (patchDescPtr) *patchDescPtr = patchDesc;
6065 return status;
6066}
6067
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006068} // namespace android