blob: baa5eb385bac48e4c5a0f28f5bcdfe58125d1f32 [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 Naganovd5e18052018-11-30 14:55:45 -080039#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110040#include <vector>
Eric Laurentd4692962014-05-05 18:13:44 -070041
François Gaffie2110e042015-03-24 08:41:51 +010042#include <AudioPolicyManagerInterface.h>
43#include <AudioPolicyEngineInstance.h>
Eric Laurente552edb2014-03-10 17:42:56 -070044#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070045#include <utils/Log.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070046#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080047#include <media/AudioPolicyHelper.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070048#include <private/android_filesystem_config.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070049#include <soundtrigger/SoundTrigger.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070050#include <system/audio.h>
Mikhail Naganov9ee05402016-10-13 15:58:17 -070051#include <audio_policy_conf.h>
Eric Laurentd4692962014-05-05 18:13:44 -070052#include "AudioPolicyManager.h"
François Gaffied1ab2bd2015-12-02 18:20:06 +010053#include <Serializer.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010054#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010055#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070056
Eric Laurent3b73df72014-03-11 09:06:29 -070057namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070058
Eric Laurentdc462862016-07-19 12:29:53 -070059//FIXME: workaround for truncated touch sounds
60// to be removed when the problem is handled by system UI
61#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070062
63// Largest difference in dB on earpiece in call between the voice volume and another
64// media / notification / system volume.
65constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
66
Mikhail Naganov15be9d22017-11-08 14:18:13 +110067// Compressed formats for MSD module, ordered from most preferred to least preferred.
68static const std::vector<audio_format_t> compressedFormatsOrder = {{
69 AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
70 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
71// Channel masks for MSD module, 3D > 2D > 1D ordering (most preferred to least preferred).
72static const std::vector<audio_channel_mask_t> surroundChannelMasksOrder = {{
73 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
74 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
75 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
76
Eric Laurente552edb2014-03-10 17:42:56 -070077// ----------------------------------------------------------------------------
78// AudioPolicyInterface implementation
79// ----------------------------------------------------------------------------
80
Eric Laurente0720872014-03-11 09:30:41 -070081status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -080082 audio_policy_dev_state_t state,
83 const char *device_address,
84 const char *device_name)
Eric Laurente552edb2014-03-10 17:42:56 -070085{
jiabina7b43792018-02-15 16:04:46 -080086 status_t status = setDeviceConnectionStateInt(device, state, device_address, device_name);
87 nextAudioPortGeneration();
88 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -080089}
90
François Gaffie44481e72016-04-20 07:49:57 +020091void AudioPolicyManager::broadcastDeviceConnectionState(audio_devices_t device,
92 audio_policy_dev_state_t state,
93 const String8 &device_address)
94{
95 AudioParameter param(device_address);
96 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganov388360c2016-10-17 17:09:41 -070097 AudioParameter::keyStreamConnect : AudioParameter::keyStreamDisconnect);
François Gaffie44481e72016-04-20 07:49:57 +020098 param.addInt(key, device);
99 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
100}
101
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800102status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800103 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -0800104 const char *device_address,
105 const char *device_name)
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800106{
Paul McLeane743a472015-01-28 11:07:31 -0800107 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s",
Mikhail Naganov7e22e942017-12-07 10:04:29 -0800108 device, state, device_address, device_name);
Eric Laurente552edb2014-03-10 17:42:56 -0700109
110 // connect/disconnect only 1 device at a time
111 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
112
François Gaffie53615e22015-03-19 09:24:12 +0100113 sp<DeviceDescriptor> devDesc =
114 mHwModules.getDeviceDescriptor(device, device_address, device_name);
Paul McLeane743a472015-01-28 11:07:31 -0800115
Eric Laurente552edb2014-03-10 17:42:56 -0700116 // handle output devices
117 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700118 SortedVector <audio_io_handle_t> outputs;
119
Eric Laurent3a4311c2014-03-17 12:00:47 -0700120 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
121
Eric Laurente552edb2014-03-10 17:42:56 -0700122 // save a copy of the opened output descriptors before any output is opened or closed
123 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
124 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700125 switch (state)
126 {
127 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800128 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700129 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700130 ALOGW("setDeviceConnectionState() device already connected: %x", device);
131 return INVALID_OPERATION;
132 }
133 ALOGV("setDeviceConnectionState() connecting device %x", device);
134
Eric Laurente552edb2014-03-10 17:42:56 -0700135 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700136 index = mAvailableOutputDevices.add(devDesc);
137 if (index >= 0) {
François Gaffie53615e22015-03-19 09:24:12 +0100138 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700139 if (module == 0) {
140 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
141 device);
142 mAvailableOutputDevices.remove(devDesc);
143 return INVALID_OPERATION;
144 }
Paul McLeane743a472015-01-28 11:07:31 -0800145 mAvailableOutputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700146 } else {
147 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700148 }
149
François Gaffie44481e72016-04-20 07:49:57 +0200150 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
151 // parameters on newly connected devices (instead of opening the outputs...)
François Gaffieaca677c2018-05-03 10:47:50 +0200152 broadcastDeviceConnectionState(device, state, devDesc->address());
François Gaffie44481e72016-04-20 07:49:57 +0200153
François Gaffieaca677c2018-05-03 10:47:50 +0200154 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->address()) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700155 mAvailableOutputDevices.remove(devDesc);
François Gaffie44481e72016-04-20 07:49:57 +0200156
157 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
François Gaffieaca677c2018-05-03 10:47:50 +0200158 devDesc->address());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700159 return INVALID_OPERATION;
160 }
François Gaffie2110e042015-03-24 08:41:51 +0100161 // Propagate device availability to Engine
162 mEngine->setDeviceConnectionState(devDesc, state);
163
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700164 // outputs should never be empty here
165 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
166 "checkOutputsForDevice() returned no outputs but status OK");
167 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
168 outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800169
Eric Laurent3ae5f312015-02-03 17:12:08 -0800170 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700171 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700172 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700173 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700174 ALOGW("setDeviceConnectionState() device not connected: %x", device);
175 return INVALID_OPERATION;
176 }
177
Paul McLean5c477aa2014-08-20 16:47:57 -0700178 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
179
Paul McLeane743a472015-01-28 11:07:31 -0800180 // Send Disconnect to HALs
François Gaffieaca677c2018-05-03 10:47:50 +0200181 broadcastDeviceConnectionState(device, state, devDesc->address());
Paul McLean5c477aa2014-08-20 16:47:57 -0700182
Eric Laurente552edb2014-03-10 17:42:56 -0700183 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700184 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700185
François Gaffieaca677c2018-05-03 10:47:50 +0200186 checkOutputsForDevice(devDesc, state, outputs, devDesc->address());
François Gaffie2110e042015-03-24 08:41:51 +0100187
188 // Propagate device availability to Engine
189 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700190 } break;
191
192 default:
193 ALOGE("setDeviceConnectionState() invalid state: %x", state);
194 return BAD_VALUE;
195 }
196
Mikhail Naganov37977152018-07-11 15:54:44 -0700197 checkForDeviceAndOutputChanges([&]() {
198 // outputs must be closed after checkOutputForAllStrategies() is executed
199 if (!outputs.isEmpty()) {
200 for (audio_io_handle_t output : outputs) {
201 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
202 // close unused outputs after device disconnection or direct outputs that have been
203 // opened by checkOutputsForDevice() to query dynamic parameters
204 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
205 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
206 (desc->mDirectOpenCount == 0))) {
207 closeOutput(output);
208 }
Eric Laurente552edb2014-03-10 17:42:56 -0700209 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700210 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
211 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700212 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700213 return false;
214 });
Eric Laurente552edb2014-03-10 17:42:56 -0700215
Eric Laurent87ffa392015-05-22 10:32:38 -0700216 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700217 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
218 updateCallRouting(newDevice);
219 }
Mikhail Naganov100f0122018-11-29 11:22:16 -0800220 const audio_devices_t msdOutDevice = getModuleDeviceTypes(
221 mAvailableOutputDevices, AUDIO_HARDWARE_MODULE_ID_MSD);
Eric Laurente552edb2014-03-10 17:42:56 -0700222 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700223 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
224 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
225 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700226 // do not force device change on duplicated output because if device is 0, it will
227 // also force a device 0 for the two outputs it is duplicated to which may override
228 // a valid device selection on those outputs.
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100229 bool force = (msdOutDevice == AUDIO_DEVICE_NONE || msdOutDevice != desc->device())
230 && !desc->isDuplicated()
François Gaffie53615e22015-03-19 09:24:12 +0100231 && (!device_distinguishes_on_address(device)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700232 // always force when disconnecting (a non-duplicated device)
233 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
Eric Laurentc75307b2015-03-17 15:29:32 -0700234 setOutputDevice(desc, newDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700235 }
Eric Laurente552edb2014-03-10 17:42:56 -0700236 }
237
Eric Laurentd60560a2015-04-10 11:31:20 -0700238 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
239 cleanUpForDevice(devDesc);
240 }
241
Eric Laurent72aa32f2014-05-30 18:51:48 -0700242 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700243 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700244 } // end if is output device
245
Eric Laurente552edb2014-03-10 17:42:56 -0700246 // handle input devices
247 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700248 SortedVector <audio_io_handle_t> inputs;
249
Eric Laurent3a4311c2014-03-17 12:00:47 -0700250 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700251 switch (state)
252 {
253 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700254 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700255 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700256 ALOGW("setDeviceConnectionState() device already connected: %d", device);
257 return INVALID_OPERATION;
258 }
François Gaffie53615e22015-03-19 09:24:12 +0100259 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700260 if (module == NULL) {
261 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
262 device);
263 return INVALID_OPERATION;
264 }
François Gaffie44481e72016-04-20 07:49:57 +0200265
266 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
267 // parameters on newly connected devices (instead of opening the inputs...)
François Gaffieaca677c2018-05-03 10:47:50 +0200268 broadcastDeviceConnectionState(device, state, devDesc->address());
François Gaffie44481e72016-04-20 07:49:57 +0200269
François Gaffieaca677c2018-05-03 10:47:50 +0200270 if (checkInputsForDevice(devDesc, state, inputs, devDesc->address()) != NO_ERROR) {
François Gaffie44481e72016-04-20 07:49:57 +0200271 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
François Gaffieaca677c2018-05-03 10:47:50 +0200272 devDesc->address());
Eric Laurentd4692962014-05-05 18:13:44 -0700273 return INVALID_OPERATION;
274 }
275
Eric Laurent3a4311c2014-03-17 12:00:47 -0700276 index = mAvailableInputDevices.add(devDesc);
277 if (index >= 0) {
Paul McLeane743a472015-01-28 11:07:31 -0800278 mAvailableInputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700279 } else {
280 return NO_MEMORY;
281 }
Eric Laurent3ae5f312015-02-03 17:12:08 -0800282
François Gaffie2110e042015-03-24 08:41:51 +0100283 // Propagate device availability to Engine
284 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700285 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700286
287 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700288 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700289 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700290 ALOGW("setDeviceConnectionState() device not connected: %d", device);
291 return INVALID_OPERATION;
292 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700293
294 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
295
296 // Set Disconnect to HALs
François Gaffieaca677c2018-05-03 10:47:50 +0200297 broadcastDeviceConnectionState(device, state, devDesc->address());
Paul McLean5c477aa2014-08-20 16:47:57 -0700298
François Gaffieaca677c2018-05-03 10:47:50 +0200299 checkInputsForDevice(devDesc, state, inputs, devDesc->address());
Eric Laurent3a4311c2014-03-17 12:00:47 -0700300 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700301
François Gaffie2110e042015-03-24 08:41:51 +0100302 // Propagate device availability to Engine
303 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700304 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700305
306 default:
307 ALOGE("setDeviceConnectionState() invalid state: %x", state);
308 return BAD_VALUE;
309 }
310
Eric Laurentd4692962014-05-05 18:13:44 -0700311 closeAllInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700312 // As the input device list can impact the output device selection, update
313 // getDeviceForStrategy() cache
314 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700315
Eric Laurent87ffa392015-05-22 10:32:38 -0700316 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700317 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
318 updateCallRouting(newDevice);
319 }
320
Eric Laurentd60560a2015-04-10 11:31:20 -0700321 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
322 cleanUpForDevice(devDesc);
323 }
324
Eric Laurentb52c1522014-05-20 11:27:36 -0700325 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700326 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700327 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700328
329 ALOGW("setDeviceConnectionState() invalid device: %x", device);
330 return BAD_VALUE;
331}
332
Eric Laurente0720872014-03-11 09:30:41 -0700333audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100334 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700335{
Eric Laurent634b7142016-04-20 13:48:02 -0700336 sp<DeviceDescriptor> devDesc =
337 mHwModules.getDeviceDescriptor(device, device_address, "",
338 (strlen(device_address) != 0)/*matchAddress*/);
339
340 if (devDesc == 0) {
341 ALOGW("getDeviceConnectionState() undeclared device, type %08x, address: %s",
342 device, device_address);
343 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
344 }
François Gaffie53615e22015-03-19 09:24:12 +0100345
Eric Laurent3a4311c2014-03-17 12:00:47 -0700346 DeviceVector *deviceVector;
347
Eric Laurente552edb2014-03-10 17:42:56 -0700348 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700349 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700350 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700351 deviceVector = &mAvailableInputDevices;
352 } else {
353 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
354 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700355 }
Eric Laurent634b7142016-04-20 13:48:02 -0700356
357 return (deviceVector->getDevice(device, String8(device_address)) != 0) ?
358 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800359}
360
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800361status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
362 const char *device_address,
363 const char *device_name)
364{
365 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700366 String8 reply;
367 AudioParameter param;
368 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800369
370 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s",
371 device, device_address, device_name);
372
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800373 // connect/disconnect only 1 device at a time
374 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
375
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800376 // Check if the device is currently connected
377 sp<DeviceDescriptor> devDesc =
378 mHwModules.getDeviceDescriptor(device, device_address, device_name);
379 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
380 if (index < 0) {
381 // Nothing to do: device is not connected
382 return NO_ERROR;
383 }
384
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700385 // For offloaded A2DP, Hw modules may have the capability to
386 // configure codecs. Check if any of the loaded hw modules
387 // supports this.
388 // If supported, send a set parameter to configure A2DP codecs
389 // and return. No need to toggle device state.
390 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
391 reply = mpClientInterface->getParameters(
392 AUDIO_IO_HANDLE_NONE,
393 String8(AudioParameter::keyReconfigA2dpSupported));
394 AudioParameter repliedParameters(reply);
395 repliedParameters.getInt(
396 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
397 if (isReconfigA2dpSupported) {
398 const String8 key(AudioParameter::keyReconfigA2dp);
399 param.add(key, String8("true"));
400 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
401 return NO_ERROR;
402 }
403 }
404
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800405 // Toggle the device state: UNAVAILABLE -> AVAILABLE
406 // This will force reading again the device configuration
407 status = setDeviceConnectionState(device,
408 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
409 device_address, device_name);
410 if (status != NO_ERROR) {
411 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
412 status);
413 return status;
414 }
415
416 status = setDeviceConnectionState(device,
417 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
418 device_address, device_name);
419 if (status != NO_ERROR) {
420 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
421 status);
422 return status;
423 }
424
425 return NO_ERROR;
426}
427
Eric Laurentdc462862016-07-19 12:29:53 -0700428uint32_t AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700429{
430 bool createTxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700431 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700432
Andy Hunga76c7de2016-12-13 19:14:31 -0800433 if(!hasPrimaryOutput() || mPrimaryOutput->device() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurentdc462862016-07-19 12:29:53 -0700434 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700435 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800436 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700437 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
438
439 // release existing RX patch if any
440 if (mCallRxPatch != 0) {
441 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
442 mCallRxPatch.clear();
443 }
444 // release TX patch if any
445 if (mCallTxPatch != 0) {
446 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
447 mCallTxPatch.clear();
448 }
449
450 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
451 // via setOutputDevice() on primary output.
452 // Otherwise, create two audio patches for TX and RX path.
453 if (availablePrimaryOutputDevices() & rxDevice) {
Eric Laurentdc462862016-07-19 12:29:53 -0700454 muteWaitMs = setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700455 // If the TX device is also on the primary HW module, setOutputDevice() will take care
456 // of it due to legacy implementation. If not, create a patch.
457 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
458 == AUDIO_DEVICE_NONE) {
459 createTxPatch = true;
460 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700461 } else { // create RX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800462 mCallRxPatch = createTelephonyPatch(true /*isRx*/, rxDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700463 createTxPatch = true;
464 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700465 if (createTxPatch) { // create TX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800466 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txDevice, delayMs);
467 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700468
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800469 return muteWaitMs;
470}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700471
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800472sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
473 bool isRx, audio_devices_t device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700474 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700475
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800476 sp<DeviceDescriptor> txSourceDeviceDesc;
477 if (isRx) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700478 patchBuilder.addSink(findDevice(mAvailableOutputDevices, device)).
479 addSource(findDevice(mAvailableInputDevices, AUDIO_DEVICE_IN_TELEPHONY_RX));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800480 } else {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700481 patchBuilder.addSource(txSourceDeviceDesc = findDevice(mAvailableInputDevices, device)).
482 addSink(findDevice(mAvailableOutputDevices, AUDIO_DEVICE_OUT_TELEPHONY_TX));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800483 }
484
485 audio_devices_t outputDevice = isRx ? device : AUDIO_DEVICE_OUT_TELEPHONY_TX;
486 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(outputDevice, mOutputs);
jiabin40573322018-11-08 12:08:02 -0800487 audio_io_handle_t output = selectOutput(outputs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800488 // request to reuse existing output stream if one is already opened to reach the target device
489 if (output != AUDIO_IO_HANDLE_NONE) {
490 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
491 ALOG_ASSERT(!outputDesc->isDuplicated(),
492 "%s() %#x device output %d is duplicated", __func__, outputDevice, output);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700493 patchBuilder.addSource(outputDesc, { .stream = AUDIO_STREAM_PATCH });
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800494 }
495
496 if (!isRx) {
Eric Laurentc0a889f2015-10-14 14:36:34 -0700497 // terminate active capture if on the same HW module as the call TX source device
498 // FIXME: would be better to refine to only inputs whose profile connects to the
499 // call TX device but this information is not in the audio patch and logic here must be
500 // symmetric to the one in startInput()
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800501 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800502 if (activeDesc->hasSameHwModuleAs(txSourceDeviceDesc)) {
Eric Laurent8f42ea12018-08-08 09:08:25 -0700503 closeActiveClients(activeDesc);
Eric Laurentc0a889f2015-10-14 14:36:34 -0700504 }
505 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700506 }
Eric Laurentdc462862016-07-19 12:29:53 -0700507
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800508 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Mikhail Naganovdc769682018-05-04 15:34:08 -0700509 status_t status = mpClientInterface->createAudioPatch(
510 patchBuilder.patch(), &afPatchHandle, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800511 ALOGW_IF(status != NO_ERROR,
512 "%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
513 sp<AudioPatch> audioPatch;
514 if (status == NO_ERROR) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700515 audioPatch = new AudioPatch(patchBuilder.patch(), mUidCached);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800516 audioPatch->mAfPatchHandle = afPatchHandle;
517 audioPatch->mUid = mUidCached;
518 }
519 return audioPatch;
520}
521
Mikhail Naganovdc769682018-05-04 15:34:08 -0700522sp<DeviceDescriptor> AudioPolicyManager::findDevice(
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100523 const DeviceVector& devices, audio_devices_t device) const {
Mikhail Naganov708e0382018-05-30 09:53:04 -0700524 DeviceVector deviceList = devices.getDevicesFromTypeMask(device);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800525 ALOG_ASSERT(!deviceList.isEmpty(),
526 "%s() selected device type %#x is not in devices list", __func__, device);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700527 return deviceList.itemAt(0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700528}
529
Mikhail Naganov100f0122018-11-29 11:22:16 -0800530audio_devices_t AudioPolicyManager::getModuleDeviceTypes(
531 const DeviceVector& devices, const char *moduleId) const {
532 sp<HwModule> mod = mHwModules.getModuleFromName(moduleId);
533 return mod != 0 ? devices.getDeviceTypesFromHwModule(mod->getHandle()) : AUDIO_DEVICE_NONE;
534}
535
536bool AudioPolicyManager::isDeviceOfModule(
537 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
538 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
539 if (module != 0) {
540 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
541 .indexOf(devDesc) != NAME_NOT_FOUND
542 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
543 .indexOf(devDesc) != NAME_NOT_FOUND;
544 }
545 return false;
546}
547
Eric Laurente0720872014-03-11 09:30:41 -0700548void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700549{
550 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100551 // store previous phone state for management of sonification strategy below
552 int oldState = mEngine->getPhoneState();
553
554 if (mEngine->setPhoneState(state) != NO_ERROR) {
555 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700556 return;
557 }
François Gaffie2110e042015-03-24 08:41:51 +0100558 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700559 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700560 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700561 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800562 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700563 }
564
François Gaffie2110e042015-03-24 08:41:51 +0100565 /**
566 * Switching to or from incall state or switching between telephony and VoIP lead to force
567 * routing command.
568 */
569 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
570 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700571
572 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700573 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700574
Eric Laurente552edb2014-03-10 17:42:56 -0700575 int delayMs = 0;
576 if (isStateInCall(state)) {
577 nsecs_t sysTime = systemTime();
578 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700579 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700580 // mute media and sonification strategies and delay device switch by the largest
581 // latency of any output where either strategy is active.
582 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100583 if ((isStrategyActive(desc, STRATEGY_MEDIA,
584 SONIFICATION_HEADSET_MUSIC_DELAY,
585 sysTime) ||
586 isStrategyActive(desc, STRATEGY_SONIFICATION,
587 SONIFICATION_HEADSET_MUSIC_DELAY,
588 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700589 (delayMs < (int)desc->latency()*2)) {
590 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700591 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700592 setStrategyMute(STRATEGY_MEDIA, true, desc);
593 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700594 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700595 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
596 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700597 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
598 }
599 }
600
Eric Laurent87ffa392015-05-22 10:32:38 -0700601 if (hasPrimaryOutput()) {
602 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
603 // the device returned is not necessarily reachable via this output
604 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
605 // force routing command to audio hardware when ending call
606 // even if no device change is needed
607 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
608 rxDevice = mPrimaryOutput->device();
609 }
Eric Laurente552edb2014-03-10 17:42:56 -0700610
Eric Laurent87ffa392015-05-22 10:32:38 -0700611 if (state == AUDIO_MODE_IN_CALL) {
612 updateCallRouting(rxDevice, delayMs);
613 } else if (oldState == AUDIO_MODE_IN_CALL) {
614 if (mCallRxPatch != 0) {
615 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
616 mCallRxPatch.clear();
617 }
618 if (mCallTxPatch != 0) {
619 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
620 mCallTxPatch.clear();
621 }
622 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
623 } else {
624 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700625 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700626 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700627
628 // reevaluate routing on all outputs in case tracks have been started during the call
629 for (size_t i = 0; i < mOutputs.size(); i++) {
630 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
631 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
632 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
Yung Ti Suf60c8242018-05-10 18:07:26 +0800633 setOutputDevice(desc, newDevice, (newDevice != AUDIO_DEVICE_NONE), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700634 }
635 }
636
Eric Laurente552edb2014-03-10 17:42:56 -0700637 if (isStateInCall(state)) {
638 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700639 // force reevaluating accessibility routing when call starts
640 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700641 }
642
643 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700644 if (state == AUDIO_MODE_RINGTONE &&
645 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700646 mLimitRingtoneVolume = true;
647 } else {
648 mLimitRingtoneVolume = false;
649 }
650}
651
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700652audio_mode_t AudioPolicyManager::getPhoneState() {
653 return mEngine->getPhoneState();
654}
655
Eric Laurente0720872014-03-11 09:30:41 -0700656void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700657 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700658{
François Gaffie2110e042015-03-24 08:41:51 +0100659 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700660 if (config == mEngine->getForceUse(usage)) {
661 return;
662 }
Eric Laurente552edb2014-03-10 17:42:56 -0700663
François Gaffie2110e042015-03-24 08:41:51 +0100664 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
665 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
666 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700667 }
François Gaffie2110e042015-03-24 08:41:51 +0100668 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
669 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
670 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700671
672 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700673 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800674
Eric Laurentdc462862016-07-19 12:29:53 -0700675 //FIXME: workaround for truncated touch sounds
676 // to be removed when the problem is handled by system UI
677 uint32_t delayMs = 0;
678 uint32_t waitMs = 0;
679 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
680 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
681 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700682 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700683 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
Eric Laurentdc462862016-07-19 12:29:53 -0700684 waitMs = updateCallRouting(newDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700685 }
Eric Laurente552edb2014-03-10 17:42:56 -0700686 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700687 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
688 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
689 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700690 waitMs = setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE),
691 delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700692 }
Eric Laurente552edb2014-03-10 17:42:56 -0700693 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700694 applyStreamVolumes(outputDesc, newDevice, waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700695 }
696 }
697
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800698 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800699 audio_devices_t newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700700 // Force new input selection if the new device can not be reached via current input
Eric Laurentfb66dd92016-01-28 18:32:03 -0800701 if (activeDesc->mProfile->getSupportedDevices().types() &
702 (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
703 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700704 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800705 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700706 }
Eric Laurente552edb2014-03-10 17:42:56 -0700707 }
Eric Laurente552edb2014-03-10 17:42:56 -0700708}
709
Eric Laurente0720872014-03-11 09:30:41 -0700710void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700711{
712 ALOGV("setSystemProperty() property %s, value %s", property, value);
713}
714
Michael Chana94fbb22018-04-24 14:31:19 +1000715// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
716// search to profiles for direct outputs.
717sp<IOProfile> AudioPolicyManager::getProfileForOutput(
718 audio_devices_t device,
719 uint32_t samplingRate,
720 audio_format_t format,
721 audio_channel_mask_t channelMask,
722 audio_output_flags_t flags,
723 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700724{
Michael Chana94fbb22018-04-24 14:31:19 +1000725 if (directOnly) {
726 // only retain flags that will drive the direct output profile selection
727 // if explicitly requested
728 static const uint32_t kRelevantFlags =
729 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
730 AUDIO_OUTPUT_FLAG_VOIP_RX);
731 flags =
732 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
733 }
Eric Laurent861a6282015-05-18 15:40:16 -0700734
735 sp<IOProfile> profile;
736
Mikhail Naganovd4120142017-12-06 15:49:22 -0800737 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800738 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent861a6282015-05-18 15:40:16 -0700739 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700740 samplingRate, NULL /*updatedSamplingRate*/,
741 format, NULL /*updatedFormat*/,
742 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700743 flags)) {
744 continue;
745 }
746 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100747 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700748 continue;
749 }
Michael Chana94fbb22018-04-24 14:31:19 +1000750 if (!directOnly) return curProfile;
751 // when searching for direct outputs, if several profiles are compatible, give priority
752 // to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100753 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700754 continue;
755 }
756 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100757 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700758 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700759 }
Eric Laurente552edb2014-03-10 17:42:56 -0700760 }
761 }
Eric Laurent861a6282015-05-18 15:40:16 -0700762 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700763}
764
Eric Laurentf4e63452017-11-06 19:31:46 +0000765audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700766{
Eric Laurent3b73df72014-03-11 09:06:29 -0700767 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700768 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800769
770 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
771 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
772 // format, flags, etc. This may result in some discrepancy for functions that utilize
773 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
774 // and AudioSystem::getOutputSamplingRate().
775
Eric Laurentf4e63452017-11-06 19:31:46 +0000776 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
jiabin40573322018-11-08 12:08:02 -0800777 audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -0700778
Eric Laurentf4e63452017-11-06 19:31:46 +0000779 ALOGV("getOutput() stream %d selected device %08x, output %d", stream, device, output);
780 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700781}
782
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700783status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
784 const audio_attributes_t *srcAttr,
785 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700786{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700787 if (srcAttr != NULL) {
788 if (!isValidAttributes(srcAttr)) {
789 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
790 __func__,
791 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
792 srcAttr->tags);
793 return BAD_VALUE;
794 }
795 *dstAttr = *srcAttr;
796 } else {
797 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
798 ALOGE("%s: invalid stream type", __func__);
799 return BAD_VALUE;
800 }
801 stream_type_to_audio_attributes(srcStream, dstAttr);
802 }
803 return NO_ERROR;
804}
805
806status_t AudioPolicyManager::getOutputForAttrInt(audio_attributes_t *resultAttr,
807 audio_io_handle_t *output,
808 audio_session_t session,
809 const audio_attributes_t *attr,
810 audio_stream_type_t *stream,
811 uid_t uid,
812 const audio_config_t *config,
813 audio_output_flags_t *flags,
814 audio_port_handle_t *selectedDeviceId)
815{
Eric Laurent8fc147b2018-07-22 19:13:55 -0700816 DeviceVector outputDevices;
817 routing_strategy strategy;
818 audio_devices_t device;
Eric Laurent97ac8712018-07-27 18:59:02 -0700819 const audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Mikhail Naganov100f0122018-11-29 11:22:16 -0800820 audio_devices_t msdDevice =
821 getModuleDeviceTypes(mAvailableOutputDevices, AUDIO_HARDWARE_MODULE_ID_MSD);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700822
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700823 status_t status = getAudioAttributes(resultAttr, attr, *stream);
824 if (status != NO_ERROR) {
825 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -0700826 }
827
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700828 ALOGV("%s usage=%d, content=%d, tag=%s flags=%08x"
Eric Laurent97ac8712018-07-27 18:59:02 -0700829 " session %d selectedDeviceId %d",
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700830 __func__,
831 resultAttr->usage, resultAttr->content_type, resultAttr->tags, resultAttr->flags,
Eric Laurent97ac8712018-07-27 18:59:02 -0700832 session, requestedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700833
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700834 *stream = streamTypefromAttributesInt(resultAttr);
Eric Laurent97ac8712018-07-27 18:59:02 -0700835
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700836 strategy = getStrategyForAttr(resultAttr);
Eric Laurent97ac8712018-07-27 18:59:02 -0700837
Scott Randolph7b1fd232018-06-18 15:33:03 -0700838 // First check for explicit routing (eg. setPreferredDevice)
Eric Laurent97ac8712018-07-27 18:59:02 -0700839 if (requestedDeviceId != AUDIO_PORT_HANDLE_NONE) {
840 sp<DeviceDescriptor> deviceDesc =
841 mAvailableOutputDevices.getDeviceFromId(requestedDeviceId);
842 device = deviceDesc->type();
Scott Randolph7b1fd232018-06-18 15:33:03 -0700843 } else {
844 // If no explict route, is there a matching dynamic policy that applies?
845 sp<SwAudioOutputDescriptor> desc;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700846 if (mPolicyMixes.getOutputForAttr(*resultAttr, uid, desc) == NO_ERROR) {
Scott Randolph7b1fd232018-06-18 15:33:03 -0700847 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
848 if (!audio_has_proportional_frames(config->format)) {
849 return BAD_VALUE;
850 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700851 *stream = streamTypefromAttributesInt(resultAttr);
Scott Randolph7b1fd232018-06-18 15:33:03 -0700852 *output = desc->mIoHandle;
Eric Laurent97ac8712018-07-27 18:59:02 -0700853 AudioMix *mix = desc->mPolicyMix;
854 sp<DeviceDescriptor> deviceDesc =
855 mAvailableOutputDevices.getDevice(mix->mDeviceType, mix->mDeviceAddress);
856 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700857 ALOGV("%s returns output %d", __func__, *output);
858 return NO_ERROR;
Scott Randolph7b1fd232018-06-18 15:33:03 -0700859 }
860
861 // Virtual sources must always be dynamicaly or explicitly routed
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700862 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
863 ALOGW("%s no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE", __func__);
Scott Randolph7b1fd232018-06-18 15:33:03 -0700864 return BAD_VALUE;
865 }
Eric Laurent97ac8712018-07-27 18:59:02 -0700866 device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700867 }
Scott Randolph7b1fd232018-06-18 15:33:03 -0700868
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700869 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200870 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -0700871 }
872
Nadav Barb2f18162018-07-18 13:01:53 +0300873 // Set incall music only if device was explicitly set, and fallback to the device which is
874 // chosen by the engine if not.
875 // FIXME: provide a more generic approach which is not device specific and move this back
876 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +0200877 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
Nadav Barb2f18162018-07-18 13:01:53 +0300878 if (device == AUDIO_DEVICE_OUT_TELEPHONY_TX &&
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700879 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +0300880 audio_is_linear_pcm(config->format) &&
881 isInCall()) {
Eric Laurent97ac8712018-07-27 18:59:02 -0700882 if (requestedDeviceId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +0300883 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
884 } else {
Eric Laurent97ac8712018-07-27 18:59:02 -0700885 // Get the devce type directly from the engine to bypass preferred route logic
Nadav Barb2f18162018-07-18 13:01:53 +0300886 device = mEngine->getDeviceForStrategy(strategy);
887 }
888 }
889
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700890 ALOGV("%s device 0x%x, sampling rate %d, format %#x, channel mask %#x, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -0800891 "flags %#x",
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700892 __func__, device, config->sample_rate, config->format, config->channel_mask, *flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700893
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100894 *output = AUDIO_IO_HANDLE_NONE;
895 if (msdDevice != AUDIO_DEVICE_NONE) {
896 *output = getOutputForDevice(msdDevice, session, *stream, config, flags);
897 if (*output != AUDIO_IO_HANDLE_NONE && setMsdPatch(device) == NO_ERROR) {
898 ALOGV("%s() Using MSD device 0x%x instead of device 0x%x",
899 __func__, msdDevice, device);
900 device = msdDevice;
901 } else {
902 *output = AUDIO_IO_HANDLE_NONE;
903 }
904 }
905 if (*output == AUDIO_IO_HANDLE_NONE) {
906 *output = getOutputForDevice(device, session, *stream, config, flags);
907 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800908 if (*output == AUDIO_IO_HANDLE_NONE) {
909 return INVALID_OPERATION;
910 }
Paul McLeanaa981192015-03-21 09:55:15 -0700911
Eric Laurent8fc147b2018-07-22 19:13:55 -0700912 outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
François Gaffieaca677c2018-05-03 10:47:50 +0200913 *selectedDeviceId = getFirstDeviceId(outputDevices);
Eric Laurent2ac76942017-06-22 17:17:09 -0700914
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700915 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
916
917 return NO_ERROR;
918}
919
920status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
921 audio_io_handle_t *output,
922 audio_session_t session,
923 audio_stream_type_t *stream,
924 uid_t uid,
925 const audio_config_t *config,
926 audio_output_flags_t *flags,
927 audio_port_handle_t *selectedDeviceId,
928 audio_port_handle_t *portId)
929{
930 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
931 if (*portId != AUDIO_PORT_HANDLE_NONE) {
932 return INVALID_OPERATION;
933 }
934 const audio_port_handle_t requestedDeviceId = *selectedDeviceId;
935 audio_attributes_t resultAttr;
936 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
937 config, flags, selectedDeviceId);
938 if (status != NO_ERROR) {
939 return status;
940 }
941
Eric Laurent8fc147b2018-07-22 19:13:55 -0700942 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
943 .format = config->format,
944 .channel_mask = config->channel_mask };
Eric Laurent8f42ea12018-08-08 09:08:25 -0700945 *portId = AudioPort::getNextUniqueId();
946
Eric Laurent8fc147b2018-07-22 19:13:55 -0700947 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700948 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Eric Laurent97ac8712018-07-27 18:59:02 -0700949 requestedDeviceId, *stream,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700950 getStrategyForAttr(&resultAttr),
Eric Laurent97ac8712018-07-27 18:59:02 -0700951 *flags);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700952 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Andy Hung39efb7a2018-09-26 15:39:28 -0700953 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700954
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700955 ALOGV("%s returns output %d selectedDeviceId %d for port ID %d",
956 __func__, *output, requestedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -0700957
Eric Laurente83b55d2014-11-14 10:06:21 -0800958 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700959}
960
961audio_io_handle_t AudioPolicyManager::getOutputForDevice(
962 audio_devices_t device,
Kevin Rocard169753c2017-03-06 14:18:23 -0800963 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700964 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -0800965 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200966 audio_output_flags_t *flags)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700967{
Andy Hungc88b0642018-04-27 15:42:35 -0700968 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700969 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700970
Eric Laurente552edb2014-03-10 17:42:56 -0700971 // open a direct output if required by specified parameters
972 //force direct flag if offload flag is set: offloading implies a direct output stream
973 // and all common behaviors are driven by checking only the direct flag
974 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +0200975 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
976 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700977 }
Nadav Bar766fb022018-01-07 12:18:03 +0200978 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
979 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -0700980 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800981 // only allow deep buffering for music stream type
982 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +0200983 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700984 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +0200985 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700986 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
987 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +0200988 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800989 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700990 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +0200991 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700992 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +0200993 audio_is_linear_pcm(config->format) &&
994 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200995 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700996 AUDIO_OUTPUT_FLAG_DIRECT);
997 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700998 }
Eric Laurente552edb2014-03-10 17:42:56 -0700999
Nadav Bar766fb022018-01-07 12:18:03 +02001000
Eric Laurentb732cf52014-09-24 19:08:21 -07001001 sp<IOProfile> profile;
1002
1003 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -07001004 // and not explicitly requested
Nadav Bar766fb022018-01-07 12:18:03 +02001005 if (((*flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Eric Laurentfe231122017-11-17 17:48:06 -08001006 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1007 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
Eric Laurentb732cf52014-09-24 19:08:21 -07001008 goto non_direct_output;
1009 }
1010
Andy Hung2ddee192015-12-18 17:34:44 -08001011 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1012 // This prevents creating an offloaded track and tearing it down immediately after start
1013 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -07001014 // FIXME: We should check the audio session here but we do not have it in this context.
1015 // This may prevent offloading in rare situations where effects are left active by apps
1016 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -07001017
Nadav Bar766fb022018-01-07 12:18:03 +02001018 if (((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -08001019 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Michael Chana94fbb22018-04-24 14:31:19 +10001020 profile = getProfileForOutput(device,
1021 config->sample_rate,
1022 config->format,
1023 config->channel_mask,
1024 (audio_output_flags_t)*flags,
1025 true /* directOnly */);
Eric Laurente552edb2014-03-10 17:42:56 -07001026 }
1027
Eric Laurent1c333e22014-05-20 10:48:17 -07001028 if (profile != 0) {
Andy Hungc88b0642018-04-27 15:42:35 -07001029 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1030 for (size_t i = 0; i < mOutputs.size(); i++) {
1031 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1032 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1033 // reuse direct output if currently open by the same client
1034 // and configured with same parameters
1035 if ((config->sample_rate == desc->mSamplingRate) &&
Andy Hung5659ed52018-04-30 10:31:26 -07001036 (config->format == desc->mFormat) &&
Andy Hungc88b0642018-04-27 15:42:35 -07001037 (config->channel_mask == desc->mChannelMask) &&
1038 (session == desc->mDirectClientSession)) {
1039 desc->mDirectOpenCount++;
1040 ALOGI("getOutputForDevice() reusing direct output %d for session %d",
1041 mOutputs.keyAt(i), session);
1042 return mOutputs.keyAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001043 }
1044 }
1045 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08001046
1047 if (!profile->canOpenNewIo()) {
1048 goto non_direct_output;
Eric Laurente552edb2014-03-10 17:42:56 -07001049 }
Eric Laurent861a6282015-05-18 15:40:16 -07001050
Eric Laurent3974e3b2017-12-07 17:58:43 -08001051 sp<SwAudioOutputDescriptor> outputDesc =
1052 new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurent53b810e2017-12-10 17:25:10 -08001053
Mikhail Naganov708e0382018-05-30 09:53:04 -07001054 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
François Gaffieaca677c2018-05-03 10:47:50 +02001055 String8 address = getFirstDeviceAddress(outputDevices);
Eric Laurent53b810e2017-12-10 17:25:10 -08001056
Dean Wheatley3023b382018-08-09 07:42:40 +10001057 // MSD patch may be using the only output stream that can service this request. Release
1058 // MSD patch to prioritize this request over any active output on MSD.
1059 AudioPatchCollection msdPatches = getMsdPatches();
1060 for (size_t i = 0; i < msdPatches.size(); i++) {
1061 const auto& patch = msdPatches[i];
1062 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1063 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1064 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
1065 (sink->ext.device.type & device) != AUDIO_DEVICE_NONE &&
1066 (address.isEmpty() || strncmp(sink->ext.device.address, address.string(),
1067 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
1068 releaseAudioPatch(patch->mHandle, mUidCached);
1069 break;
1070 }
1071 }
1072 }
1073
Nadav Bar766fb022018-01-07 12:18:03 +02001074 status = outputDesc->open(config, device, address, stream, *flags, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07001075
1076 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001077 if (status != NO_ERROR ||
Eric Laurentfe231122017-11-17 17:48:06 -08001078 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
Andy Hung5659ed52018-04-30 10:31:26 -07001079 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->mFormat) ||
Eric Laurentfe231122017-11-17 17:48:06 -08001080 (config->channel_mask != 0 && config->channel_mask != outputDesc->mChannelMask)) {
1081 ALOGV("getOutputForDevice() failed opening direct output: output %d sample rate %d %d,"
1082 "format %d %d, channel mask %04x %04x", output, config->sample_rate,
1083 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
1084 config->channel_mask, outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001085 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001086 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07001087 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001088 // fall back to mixer output if possible when the direct output could not be open
Eric Laurentfe231122017-11-17 17:48:06 -08001089 if (audio_is_linear_pcm(config->format) &&
1090 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -08001091 goto non_direct_output;
1092 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001093 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001094 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001095 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -08001096 outputDesc->mDirectClientSession = session;
1097
Eric Laurente552edb2014-03-10 17:42:56 -07001098 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001099 mPreviousOutputs = mOutputs;
Eric Laurentf4e63452017-11-06 19:31:46 +00001100 ALOGV("getOutputForDevice() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001101 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001102 return output;
1103 }
1104
Eric Laurentb732cf52014-09-24 19:08:21 -07001105non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001106
1107 // A request for HW A/V sync cannot fallback to a mixed output because time
1108 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001109 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001110 return AUDIO_IO_HANDLE_NONE;
1111 }
1112
Eric Laurente552edb2014-03-10 17:42:56 -07001113 // ignoring channel mask due to downmix capability in mixer
1114
1115 // open a non direct output
1116
1117 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001118 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001119 // get which output is suitable for the specified stream. The actual
1120 // routing change will happen when startOutput() will be called
1121 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1122
Eric Laurent8838a382014-09-08 16:44:28 -07001123 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001124 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabin40573322018-11-08 12:08:02 -08001125 output = selectOutput(outputs, *flags, config->format,
1126 config->channel_mask, config->sample_rate);
Eric Laurente552edb2014-03-10 17:42:56 -07001127 }
Eric Laurentf4e63452017-11-06 19:31:46 +00001128 ALOGW_IF((output == 0), "getOutputForDevice() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001129 "sampling rate %d, format %#x, channels %#x, flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +02001130 stream, config->sample_rate, config->format, config->channel_mask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001131
Eric Laurente552edb2014-03-10 17:42:56 -07001132 return output;
1133}
1134
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001135sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001136 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001137 if (msdModule != 0) {
1138 DeviceVector msdInputDevices = mAvailableInputDevices.getDevicesFromHwModule(
1139 msdModule->getHandle());
1140 if (!msdInputDevices.isEmpty()) return msdInputDevices.itemAt(0);
1141 }
1142 return 0;
1143}
1144
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001145const AudioPatchCollection AudioPolicyManager::getMsdPatches() const {
1146 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001147 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1148 if (msdModule != 0) {
1149 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1150 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1151 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1152 const struct audio_port_config *source = &patch->mPatch.sources[j];
1153 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1154 source->ext.device.hw_module == msdModule->getHandle()) {
1155 msdPatches.addAudioPatch(patch->mHandle, patch);
1156 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001157 }
1158 }
1159 }
1160 return msdPatches;
1161}
1162
1163status_t AudioPolicyManager::getBestMsdAudioProfileFor(audio_devices_t outputDevice,
1164 bool hwAvSync, audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1165{
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001166 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001167 if (msdModule == nullptr) {
1168 ALOGE("%s() unable to get MSD module", __func__);
1169 return NO_INIT;
1170 }
1171 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(outputDevice);
1172 if (deviceModule == nullptr) {
1173 ALOGE("%s() unable to get module for %#x", __func__, outputDevice);
1174 return NO_INIT;
1175 }
1176 const InputProfileCollection &inputProfiles = msdModule->getInputProfiles();
1177 if (inputProfiles.isEmpty()) {
1178 ALOGE("%s() no input profiles for MSD module", __func__);
1179 return NO_INIT;
1180 }
1181 const OutputProfileCollection &outputProfiles = deviceModule->getOutputProfiles();
1182 if (outputProfiles.isEmpty()) {
1183 ALOGE("%s() no output profiles for device %#x", __func__, outputDevice);
1184 return NO_INIT;
1185 }
1186 AudioProfileVector msdProfiles;
1187 // Each IOProfile represents a MixPort from audio_policy_configuration.xml
1188 for (const auto &inProfile : inputProfiles) {
1189 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0)) {
1190 msdProfiles.appendVector(inProfile->getAudioProfiles());
1191 }
1192 }
1193 AudioProfileVector deviceProfiles;
1194 for (const auto &outProfile : outputProfiles) {
1195 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0)) {
1196 deviceProfiles.appendVector(outProfile->getAudioProfiles());
1197 }
1198 }
1199 struct audio_config_base bestSinkConfig;
1200 status_t result = msdProfiles.findBestMatchingOutputConfig(deviceProfiles,
1201 compressedFormatsOrder, surroundChannelMasksOrder, true /*preferHigherSamplingRates*/,
1202 &bestSinkConfig);
1203 if (result != NO_ERROR) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001204 ALOGD("%s() no matching profiles found for device: %#x, hwAvSync: %d",
1205 __func__, outputDevice, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001206 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001207 }
1208 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1209 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1210 sinkConfig->format = bestSinkConfig.format;
1211 // For encoded streams force direct flag to prevent downstream mixing.
1212 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1213 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
1214 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1215 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1216 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1217 sourceConfig->format = bestSinkConfig.format;
1218 // Copy input stream directly without any processing (e.g. resampling).
1219 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1220 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1221 if (hwAvSync) {
1222 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1223 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1224 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1225 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1226 }
1227 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1228 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1229 sinkConfig->config_mask |= config_mask;
1230 sourceConfig->config_mask |= config_mask;
1231 return NO_ERROR;
1232}
1233
1234PatchBuilder AudioPolicyManager::buildMsdPatch(audio_devices_t outputDevice) const
1235{
1236 PatchBuilder patchBuilder;
1237 patchBuilder.addSource(getMsdAudioInDevice()).
1238 addSink(findDevice(mAvailableOutputDevices, outputDevice));
1239 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1240 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
1241 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1242 // For now, we just forcefully try with HwAvSync first.
1243 status_t res = getBestMsdAudioProfileFor(outputDevice, true /*hwAvSync*/,
1244 &sourceConfig, &sinkConfig) == NO_ERROR ? NO_ERROR :
1245 getBestMsdAudioProfileFor(
1246 outputDevice, false /*hwAvSync*/, &sourceConfig, &sinkConfig);
1247 if (res == NO_ERROR) {
1248 // Found a matching profile for encoded audio. Re-create PatchBuilder with this config.
1249 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1250 }
1251 ALOGV("%s() no matching profile found. Fall through to default PCM patch"
1252 " supporting PCM format conversion.", __func__);
1253 return patchBuilder;
1254}
1255
1256status_t AudioPolicyManager::setMsdPatch(audio_devices_t outputDevice) {
1257 ALOGV("%s() for outputDevice %#x", __func__, outputDevice);
1258 if (outputDevice == AUDIO_DEVICE_NONE) {
1259 // Use media strategy for unspecified output device. This should only
1260 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1261 // therefore invalidate explicit routing requests.
1262 outputDevice = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
1263 }
1264 PatchBuilder patchBuilder = buildMsdPatch(outputDevice);
1265 const struct audio_patch* patch = patchBuilder.patch();
1266 const AudioPatchCollection msdPatches = getMsdPatches();
1267 if (!msdPatches.isEmpty()) {
1268 LOG_ALWAYS_FATAL_IF(msdPatches.size() > 1,
1269 "The current MSD prototype only supports one output patch");
1270 sp<AudioPatch> currentPatch = msdPatches.valueAt(0);
1271 if (audio_patches_are_equal(&currentPatch->mPatch, patch)) {
1272 return NO_ERROR;
1273 }
1274 releaseAudioPatch(currentPatch->mHandle, mUidCached);
1275 }
1276 status_t status = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1277 patch, 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1278 ALOGE_IF(status != NO_ERROR, "%s() error %d creating MSD audio patch", __func__, status);
1279 ALOGI_IF(status == NO_ERROR, "%s() Patch created from MSD_IN to "
1280 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__, outputDevice,
1281 patch->sources[0].format, patch->sources[0].channel_mask, patch->sources[0].sample_rate);
1282 return status;
1283}
1284
Eric Laurente0720872014-03-11 09:30:41 -07001285audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001286 audio_output_flags_t flags,
jiabin40573322018-11-08 12:08:02 -08001287 audio_format_t format,
1288 audio_channel_mask_t channelMask,
1289 uint32_t samplingRate)
Eric Laurente552edb2014-03-10 17:42:56 -07001290{
1291 // select one output among several that provide a path to a particular device or set of
1292 // devices (the list was previously build by getOutputsForDevice()).
1293 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001294 // 1: the output supporting haptic playback when requesting haptic playback
1295 // 2: the output with the highest number of requested policy flags
1296 // 3: the output with the bit depth the closest to the requested one
1297 // 4: the primary output
1298 // 5: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001299
1300 if (outputs.size() == 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001301 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001302 }
1303 if (outputs.size() == 1) {
1304 return outputs[0];
1305 }
1306
1307 int maxCommonFlags = 0;
jiabin40573322018-11-08 12:08:02 -08001308 const size_t hapticChannelCount = audio_channel_count_from_out_mask(
1309 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001310 audio_io_handle_t outputForFlags = AUDIO_IO_HANDLE_NONE;
1311 audio_io_handle_t outputForPrimary = AUDIO_IO_HANDLE_NONE;
1312 audio_io_handle_t outputForFormat = AUDIO_IO_HANDLE_NONE;
Eric Laurente6930022016-02-11 10:20:40 -08001313 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1314 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001315
Eric Laurente78b6762018-12-19 16:29:01 -08001316 // Flags which must be present on both the request and the selected output
1317 static const audio_output_flags_t kMandatedFlags = (audio_output_flags_t)
1318 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1319
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001320 for (audio_io_handle_t output : outputs) {
1321 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001322 if (!outputDesc->isDuplicated()) {
chenhg1794d712018-10-09 15:20:37 -07001323 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1324 continue;
1325 }
jiabin40573322018-11-08 12:08:02 -08001326 // If haptic channel is specified, use the haptic output if present.
1327 // When using haptic output, same audio format and sample rate are required.
1328 if (hapticChannelCount > 0) {
1329 // If haptic channel is specified, use the first output that
1330 // support haptic playback.
1331 if (audio_channel_count_from_out_mask(
1332 outputDesc->mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL) >= hapticChannelCount
1333 && format == outputDesc->mFormat
1334 && samplingRate == outputDesc->mSamplingRate) {
1335 return output;
1336 }
1337 } else {
1338 // When haptic channel is not specified, skip haptic output.
1339 if (outputDesc->mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL) {
1340 continue;
1341 }
1342 }
Eric Laurente78b6762018-12-19 16:29:01 -08001343 if ((kMandatedFlags & flags) !=
1344 (kMandatedFlags & outputDesc->mProfile->getFlags())) {
1345 continue;
1346 }
jiabin40573322018-11-08 12:08:02 -08001347
Eric Laurent8838a382014-09-08 16:44:28 -07001348 // if a valid format is specified, skip output if not compatible
1349 if (format != AUDIO_FORMAT_INVALID) {
chenhg1794d712018-10-09 15:20:37 -07001350 if (!audio_is_linear_pcm(format)) {
Eric Laurent8838a382014-09-08 16:44:28 -07001351 continue;
1352 }
Eric Laurente6930022016-02-11 10:20:40 -08001353 if (AudioPort::isBetterFormatMatch(
1354 outputDesc->mFormat, bestFormat, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001355 outputForFormat = output;
Eric Laurente6930022016-02-11 10:20:40 -08001356 bestFormat = outputDesc->mFormat;
1357 }
Eric Laurent8838a382014-09-08 16:44:28 -07001358 }
1359
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001360 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001361 if (commonFlags >= maxCommonFlags) {
1362 if (commonFlags == maxCommonFlags) {
Andy Hungc9901522017-11-10 20:07:54 -08001363 if (format != AUDIO_FORMAT_INVALID
1364 && AudioPort::isBetterFormatMatch(
1365 outputDesc->mFormat, bestFormatForFlags, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001366 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001367 bestFormatForFlags = outputDesc->mFormat;
1368 }
1369 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001370 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001371 maxCommonFlags = commonFlags;
1372 bestFormatForFlags = outputDesc->mFormat;
1373 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001374 ALOGV("selectOutput() commonFlags for output %d, %04x", output, commonFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001375 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001376 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001377 outputForPrimary = output;
Eric Laurente552edb2014-03-10 17:42:56 -07001378 }
1379 }
1380 }
1381
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001382 if (outputForFlags != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001383 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001384 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001385 if (outputForFormat != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001386 return outputForFormat;
1387 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001388 if (outputForPrimary != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001389 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001390 }
1391
1392 return outputs[0];
1393}
1394
Eric Laurent8fc147b2018-07-22 19:13:55 -07001395status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001396{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001397 ALOGV("%s portId %d", __FUNCTION__, portId);
1398
1399 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1400 if (outputDesc == 0) {
1401 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001402 return BAD_VALUE;
1403 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001404 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001405
Eric Laurent8fc147b2018-07-22 19:13:55 -07001406 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001407 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001408
Eric Laurent733ce942017-12-07 12:18:25 -08001409 status_t status = outputDesc->start();
1410 if (status != NO_ERROR) {
1411 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001412 }
1413
Eric Laurent97ac8712018-07-27 18:59:02 -07001414 uint32_t delayMs;
1415 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001416
1417 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001418 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001419 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001420 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001421 if (delayMs != 0) {
1422 usleep(delayMs * 1000);
1423 }
1424
1425 return status;
1426}
1427
Eric Laurent97ac8712018-07-27 18:59:02 -07001428status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1429 const sp<TrackClientDescriptor>& client,
1430 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001431{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001432 // cannot start playback of STREAM_TTS if any other output is being used
1433 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001434
1435 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001436 audio_stream_type_t stream = client->stream();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001437 if (stream == AUDIO_STREAM_TTS) {
1438 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001439 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001440 return INVALID_OPERATION;
1441 } else {
1442 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1443 }
1444 } else {
1445 // some playback other than beacon starts
1446 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1447 }
1448
Eric Laurent77305a62016-07-25 16:39:22 -07001449 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001450 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001451 bool force = !outputDesc->isActive() &&
1452 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001453
Eric Laurent97ac8712018-07-27 18:59:02 -07001454 audio_devices_t device = AUDIO_DEVICE_NONE;
1455 AudioMix *policyMix = NULL;
1456 const char *address = NULL;
1457 if (outputDesc->mPolicyMix != NULL) {
1458 policyMix = outputDesc->mPolicyMix;
1459 address = policyMix->mDeviceAddress.string();
1460 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1461 device = policyMix->mDeviceType;
1462 } else {
1463 device = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1464 }
1465 }
1466
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001467 // requiresMuteCheck is false when we can bypass mute strategy.
1468 // It covers a common case when there is no materially active audio
1469 // and muting would result in unnecessary delay and dropped audio.
1470 const uint32_t outputLatencyMs = outputDesc->latency();
1471 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1472
Eric Laurente552edb2014-03-10 17:42:56 -07001473 // increment usage count for this stream on the requested output:
1474 // NOTE that the usage count is the same for duplicated output and hardware output which is
1475 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001476 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001477
1478 if (client->hasPreferredDevice(true)) {
1479 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
1480 if (device != outputDesc->device()) {
1481 checkStrategyRoute(getStrategy(stream), outputDesc->mIoHandle);
1482 }
1483 }
Eric Laurente552edb2014-03-10 17:42:56 -07001484
Eric Laurent36829f92017-04-07 19:04:42 -07001485 if (stream == AUDIO_STREAM_MUSIC) {
1486 selectOutputForMusicEffects();
1487 }
1488
Eric Laurent592dd7b2018-08-05 18:58:48 -07001489 if (outputDesc->streamActiveCount(stream) == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001490 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001491 if (device == AUDIO_DEVICE_NONE) {
1492 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001493 }
Eric Laurent36829f92017-04-07 19:04:42 -07001494
Eric Laurente552edb2014-03-10 17:42:56 -07001495 routing_strategy strategy = getStrategy(stream);
1496 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001497 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1498 (beaconMuteLatency > 0);
1499 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001500 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001501 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001502 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001503 // An output has a shared device if
1504 // - managed by the same hw module
1505 // - supports the currently selected device
1506 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
1507 && (desc->supportedDevices() & device) != AUDIO_DEVICE_NONE;
1508
Eric Laurent77305a62016-07-25 16:39:22 -07001509 // force a device change if any other output is:
1510 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001511 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001512 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001513 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001514 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001515 // change the device currently selected by the other output.
1516 if (sharedDevice &&
Eric Laurent77305a62016-07-25 16:39:22 -07001517 desc->device() != device &&
Eric Laurent77305a62016-07-25 16:39:22 -07001518 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001519 force = true;
1520 }
1521 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001522 // a notification so that audio focus effect can propagate, or that a mute/unmute
1523 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001524 const uint32_t latencyMs = desc->latency();
1525 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1526
1527 if (shouldWait && isActive && (waitMs < latencyMs)) {
1528 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001529 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001530
1531 // Require mute check if another output is on a shared device
1532 // and currently active to have proper drain and avoid pops.
1533 // Note restoring AudioTracks onto this output needs to invoke
1534 // a volume ramp if there is no mute.
1535 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001536 }
1537 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001538
1539 const uint32_t muteWaitMs =
1540 setOutputDevice(outputDesc, device, force, 0, NULL, address, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001541
Eric Laurente552edb2014-03-10 17:42:56 -07001542 // apply volume rules for current stream and device if necessary
1543 checkAndSetVolume(stream,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001544 mVolumeCurves->getVolumeIndex(stream, outputDesc->device()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001545 outputDesc,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001546 outputDesc->device());
Eric Laurente552edb2014-03-10 17:42:56 -07001547
1548 // update the outputs if starting an output with a stream that can affect notification
1549 // routing
1550 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001551
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001552 // force reevaluating accessibility routing when ringtone or alarm starts
1553 if (strategy == STRATEGY_SONIFICATION) {
1554 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1555 }
Eric Laurentdc462862016-07-19 12:29:53 -07001556
1557 if (waitMs > muteWaitMs) {
1558 *delayMs = waitMs - muteWaitMs;
1559 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001560
1561 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1562 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1563 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1564 // change occurs after the MixerThread starts and causes a stream volume
1565 // glitch.
1566 //
1567 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001568 }
Eric Laurentdc462862016-07-19 12:29:53 -07001569
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001570 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1571 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1572 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1573 }
1574
Eric Laurent97ac8712018-07-27 18:59:02 -07001575 // Automatically enable the remote submix input when output is started on a re routing mix
1576 // of type MIX_TYPE_RECORDERS
1577 if (audio_is_remote_submix_device(device) && policyMix != NULL &&
1578 policyMix->mMixType == MIX_TYPE_RECORDERS) {
1579 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1580 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1581 address,
1582 "remote-submix");
1583 }
1584
Eric Laurente552edb2014-03-10 17:42:56 -07001585 return NO_ERROR;
1586}
1587
Eric Laurent8fc147b2018-07-22 19:13:55 -07001588status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001589{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001590 ALOGV("%s portId %d", __FUNCTION__, portId);
1591
1592 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1593 if (outputDesc == 0) {
1594 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001595 return BAD_VALUE;
1596 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001597 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001598
Eric Laurent97ac8712018-07-27 18:59:02 -07001599 ALOGV("stopOutput() output %d, stream %d, session %d",
1600 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07001601
Eric Laurent97ac8712018-07-27 18:59:02 -07001602 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08001603
Eric Laurent733ce942017-12-07 12:18:25 -08001604 if (status == NO_ERROR ) {
1605 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001606 }
1607 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001608}
1609
Eric Laurent97ac8712018-07-27 18:59:02 -07001610status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1611 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07001612{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001613 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07001614 audio_stream_type_t stream = client->stream();
1615
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001616 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1617
Eric Laurent592dd7b2018-08-05 18:58:48 -07001618 if (outputDesc->streamActiveCount(stream) > 0) {
1619 if (outputDesc->streamActiveCount(stream) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001620 // Automatically disable the remote submix input when output is stopped on a
1621 // re routing mix of type MIX_TYPE_RECORDERS
1622 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1623 outputDesc->mPolicyMix != NULL &&
1624 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1625 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1626 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1627 outputDesc->mPolicyMix->mDeviceAddress,
1628 "remote-submix");
1629 }
1630 }
1631 bool forceDeviceUpdate = false;
1632 if (client->hasPreferredDevice(true)) {
1633 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1634 forceDeviceUpdate = true;
1635 }
1636
Eric Laurente552edb2014-03-10 17:42:56 -07001637 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07001638 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07001639
Eric Laurente552edb2014-03-10 17:42:56 -07001640 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001641 if (outputDesc->streamActiveCount(stream) == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001642 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001643 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001644 // delay the device switch by twice the latency because stopOutput() is executed when
1645 // the track stop() command is received and at that time the audio track buffer can
1646 // still contain data that needs to be drained. The latency only covers the audio HAL
1647 // and kernel buffers. Also the latency does not always include additional delay in the
1648 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001649 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001650
1651 // force restoring the device selection on other active outputs if it differs from the
1652 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001653 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001654 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001655 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001656 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001657 desc->isActive() &&
1658 outputDesc->sharesHwModuleWith(desc) &&
1659 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001660 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1661 bool force = desc->device() != newDevice2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001662
Eric Laurentc75307b2015-03-17 15:29:32 -07001663 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001664 newDevice2,
1665 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001666 delayMs);
1667 // re-apply device specific volume if not done by setOutputDevice()
1668 if (!force) {
1669 applyStreamVolumes(desc, newDevice2, delayMs);
1670 }
Eric Laurente552edb2014-03-10 17:42:56 -07001671 }
1672 }
1673 // update the outputs if stopping one with a stream that can affect notification routing
1674 handleNotificationRoutingForStream(stream);
1675 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001676
1677 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1678 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1679 setStrategyMute(STRATEGY_SONIFICATION, false, outputDesc);
1680 }
1681
Eric Laurent36829f92017-04-07 19:04:42 -07001682 if (stream == AUDIO_STREAM_MUSIC) {
1683 selectOutputForMusicEffects();
1684 }
Eric Laurente552edb2014-03-10 17:42:56 -07001685 return NO_ERROR;
1686 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001687 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001688 return INVALID_OPERATION;
1689 }
1690}
1691
Eric Laurent8fc147b2018-07-22 19:13:55 -07001692void AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001693{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001694 ALOGV("%s portId %d", __FUNCTION__, portId);
1695
1696 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1697 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07001698 // If an output descriptor is closed due to a device routing change,
1699 // then there are race conditions with releaseOutput from tracks
1700 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
1701 // destroyed shortly thereafter.
1702 //
1703 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07001704 ALOGW("releaseOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001705 return;
1706 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001707
1708 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001709
Eric Laurent8fc147b2018-07-22 19:13:55 -07001710 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1711 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001712 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07001713 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001714 return;
1715 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001716 if (--outputDesc->mDirectOpenCount == 0) {
1717 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07001718 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001719 }
1720 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001721 // stopOutput() needs to be successfully called before releaseOutput()
1722 // otherwise there may be inaccurate stream reference counts.
1723 // This is checked in outputDesc->removeClient below.
1724 outputDesc->removeClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001725}
1726
Eric Laurentcaf7f482014-11-25 17:50:47 -08001727status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1728 audio_io_handle_t *input,
1729 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001730 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001731 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001732 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001733 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001734 input_type_t *inputType,
1735 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001736{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001737 ALOGV("getInputForAttr() source %d, sampling rate %d, format %#x, channel mask %#x,"
Eric Laurentcaf7f482014-11-25 17:50:47 -08001738 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001739 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001740
Eric Laurentad2e7b92017-09-14 20:06:42 -07001741 status_t status = NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -08001742 // handle legacy remote submix case where the address was not always specified
1743 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001744 audio_source_t halInputSource;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001745 audio_source_t inputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001746 AudioMix *policyMix = NULL;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001747 DeviceVector inputDevices;
Eric Laurent8fc147b2018-07-22 19:13:55 -07001748 sp<AudioInputDescriptor> inputDesc;
1749 sp<RecordClientDescriptor> clientDesc;
1750 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001751 bool isSoundTrigger;
1752 audio_devices_t device;
1753
1754 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1755 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1756 return INVALID_OPERATION;
1757 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001758
Eric Laurentfe231122017-11-17 17:48:06 -08001759 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1760 inputSource = AUDIO_SOURCE_MIC;
1761 }
1762
Paul McLean466dc8e2015-04-17 13:15:36 -06001763 // Explicit routing?
François Gaffieaca677c2018-05-03 10:47:50 +02001764 sp<DeviceDescriptor> deviceDesc = mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001765
Eric Laurentad2e7b92017-09-14 20:06:42 -07001766 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1767 // possible
1768 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1769 *input != AUDIO_IO_HANDLE_NONE) {
1770 ssize_t index = mInputs.indexOfKey(*input);
1771 if (index < 0) {
1772 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1773 status = BAD_VALUE;
1774 goto error;
1775 }
1776 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001777 RecordClientVector clients = inputDesc->getClientsForSession(session);
1778 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001779 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1780 status = BAD_VALUE;
1781 goto error;
1782 }
1783 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1784 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001785 // corresponds to a new client and is only permitted from the same UID.
1786 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07001787 if (clients.size() > 1) {
1788 for (const auto& client : clients) {
1789 // The client map is ordered by key values (portId) and portIds are allocated
1790 // incrementaly. So the first client in this list is the one opened by audio flinger
1791 // when the mmap stream is created and should be ignored as it does not correspond
1792 // to an actual client
1793 if (client == *clients.cbegin()) {
1794 continue;
1795 }
1796 if (uid != client->uid() && !client->isSilenced()) {
1797 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
1798 uid, client->portId(), client->uid());
1799 status = INVALID_OPERATION;
1800 goto error;
1801 }
Eric Laurent331679c2018-04-16 17:03:16 -07001802 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001803 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001804 *inputType = API_INPUT_LEGACY;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001805 device = inputDesc->mDevice;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001806
Eric Laurent8f42ea12018-08-08 09:08:25 -07001807 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001808 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001809 }
1810
1811 *input = AUDIO_IO_HANDLE_NONE;
1812 *inputType = API_INPUT_INVALID;
1813
Eric Laurentad2e7b92017-09-14 20:06:42 -07001814 halInputSource = inputSource;
1815
Eric Laurentc447ded2015-01-06 08:47:05 -08001816 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001817 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001818 status = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
1819 if (status != NO_ERROR) {
1820 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001821 }
1822 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001823 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1824 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001825 } else {
Eric Laurent97ac8712018-07-27 18:59:02 -07001826 if (deviceDesc != 0) {
1827 device = deviceDesc->type();
1828 } else {
1829 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
1830 }
Eric Laurent275e8e92014-11-30 15:14:47 -08001831 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001832 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001833 status = BAD_VALUE;
1834 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001835 }
Eric Laurentc722f302014-12-10 11:21:49 -08001836 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001837 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001838 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1839 // there is an external policy, but this input is attached to a mix of recorders,
1840 // meaning it receives audio injected into the framework, so the recorder doesn't
1841 // know about it and is therefore considered "legacy"
1842 *inputType = API_INPUT_LEGACY;
1843 } else {
1844 // recording a mix of players defined by an external policy, we're rerouting for
1845 // an external policy
1846 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1847 }
Eric Laurentc722f302014-12-10 11:21:49 -08001848 } else if (audio_is_remote_submix_device(device)) {
1849 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001850 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001851 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1852 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001853 } else {
1854 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001855 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001856
Eric Laurent599c7582015-12-07 18:05:55 -08001857 }
1858
Eric Laurent8f42ea12018-08-08 09:08:25 -07001859 *input = getInputForDevice(device, address, session, inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001860 config, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001861 policyMix);
1862 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001863 status = INVALID_OPERATION;
1864 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001865 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001866
Eric Laurent8f42ea12018-08-08 09:08:25 -07001867exit:
1868
Mikhail Naganov708e0382018-05-30 09:53:04 -07001869 inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
François Gaffieaca677c2018-05-03 10:47:50 +02001870 *selectedDeviceId = getFirstDeviceId(inputDevices);
Eric Laurent2ac76942017-06-22 17:17:09 -07001871
Eric Laurent8f42ea12018-08-08 09:08:25 -07001872 isSoundTrigger = inputSource == AUDIO_SOURCE_HOTWORD &&
1873 mSoundTriggerSessions.indexOfKey(session) > 0;
1874 *portId = AudioPort::getNextUniqueId();
1875
Eric Laurent8fc147b2018-07-22 19:13:55 -07001876 clientDesc = new RecordClientDescriptor(*portId, uid, session,
Eric Laurent8f42ea12018-08-08 09:08:25 -07001877 *attr, *config, requestedDeviceId,
1878 inputSource,flags, isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001879 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07001880 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001881
1882 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
1883 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001884
Eric Laurent599c7582015-12-07 18:05:55 -08001885 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001886
1887error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07001888 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001889}
1890
1891
1892audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1893 String8 address,
1894 audio_session_t session,
Eric Laurent599c7582015-12-07 18:05:55 -08001895 audio_source_t inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001896 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08001897 audio_input_flags_t flags,
1898 AudioMix *policyMix)
1899{
1900 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1901 audio_source_t halInputSource = inputSource;
1902 bool isSoundTrigger = false;
1903
1904 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1905 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1906 if (index >= 0) {
1907 input = mSoundTriggerSessions.valueFor(session);
1908 isSoundTrigger = true;
1909 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1910 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1911 } else {
1912 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001913 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001914 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08001915 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001916 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001917 }
1918
Andy Hungf129b032015-04-07 13:45:50 -07001919 // find a compatible input profile (not necessarily identical in parameters)
1920 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08001921 // sampling rate and flags may be updated by getInputProfile
1922 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
1923 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07001924 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08001925 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07001926 audio_input_flags_t profileFlags = flags;
1927 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07001928 profileFormat = config->format; // reset each time through loop, in case it is updated
Eric Laurent275e8e92014-11-30 15:14:47 -08001929 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001930 profileSamplingRate, profileFormat, profileChannelMask,
1931 profileFlags);
1932 if (profile != 0) {
1933 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001934 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1935 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001936 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1937 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1938 } else { // fail
Glenn Kastenfaa10a62017-05-25 15:52:05 -07001939 ALOGW("getInputForDevice() could not find profile for device 0x%X, "
Eric Laurentfe231122017-11-17 17:48:06 -08001940 "sampling rate %u, format %#x, channel mask 0x%X, flags %#x",
1941 device, config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001942 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001943 }
Eric Laurente552edb2014-03-10 17:42:56 -07001944 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001945 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08001946 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08001947 if (samplingRate == 0) {
1948 samplingRate = profileSamplingRate;
1949 }
Eric Laurente552edb2014-03-10 17:42:56 -07001950
Eric Laurent322b4d22015-04-03 15:57:54 -07001951 if (profile->getModuleHandle() == 0) {
1952 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001953 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001954 }
1955
Eric Laurent3974e3b2017-12-07 17:58:43 -08001956 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001957 for (size_t i = 0; i < mInputs.size(); ) {
1958 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
1959 if (desc->mProfile != profile) {
1960 continue;
1961 }
1962 // if sound trigger, reuse input if used by other sound trigger on same session
1963 // else
1964 // reuse input if active client app is not in IDLE state
1965 //
1966 RecordClientVector clients = desc->clientsList();
1967 bool doClose = false;
1968 for (const auto& client : clients) {
1969 if (isSoundTrigger != client->isSoundTrigger()) {
1970 continue;
1971 }
1972 if (client->isSoundTrigger()) {
1973 if (session == client->session()) {
1974 return desc->mIoHandle;
1975 }
1976 continue;
1977 }
1978 if (client->active() && client->appState() != APP_STATE_IDLE) {
1979 return desc->mIoHandle;
1980 }
1981 doClose = true;
1982 }
1983 if (doClose) {
1984 closeInput(desc->mIoHandle);
1985 } else {
1986 i++;
1987 }
1988 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08001989 }
1990
Eric Laurentfe231122017-11-17 17:48:06 -08001991 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001992
Eric Laurentfe231122017-11-17 17:48:06 -08001993 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
1994 lConfig.sample_rate = profileSamplingRate;
1995 lConfig.channel_mask = profileChannelMask;
1996 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07001997
Eric Laurent53b810e2017-12-10 17:25:10 -08001998 if (address == "") {
Mikhail Naganov708e0382018-05-30 09:53:04 -07001999 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -08002000 // the inputs vector must be of size >= 1, but we don't want to crash here
François Gaffieaca677c2018-05-03 10:47:50 +02002001 address = getFirstDeviceAddress(inputDevices);
Eric Laurent53b810e2017-12-10 17:25:10 -08002002 }
2003
Eric Laurentfe231122017-11-17 17:48:06 -08002004 status_t status = inputDesc->open(&lConfig, device, address,
2005 halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002006
2007 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002008 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002009 (profileSamplingRate != lConfig.sample_rate) ||
2010 !audio_formats_match(profileFormat, lConfig.format) ||
2011 (profileChannelMask != lConfig.channel_mask)) {
2012 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002013 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002014 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002015 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002016 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002017 }
Eric Laurent599c7582015-12-07 18:05:55 -08002018 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002019 }
2020
Eric Laurentc722f302014-12-10 11:21:49 -08002021 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002022
Eric Laurent599c7582015-12-07 18:05:55 -08002023 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002024 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002025
Eric Laurent599c7582015-12-07 18:05:55 -08002026 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002027}
2028
Eric Laurent4eb58f12018-12-07 16:41:02 -08002029status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002030{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002031 ALOGV("%s portId %d", __FUNCTION__, portId);
2032
2033 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2034 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002035 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002036 return BAD_VALUE;
2037 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002038 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002039 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002040 if (client->active()) {
2041 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2042 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002043 }
2044
Eric Laurent8f42ea12018-08-08 09:08:25 -07002045 audio_session_t session = client->session();
2046
Eric Laurent4eb58f12018-12-07 16:41:02 -08002047 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002048
Eric Laurent4eb58f12018-12-07 16:41:02 -08002049 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002050
Eric Laurent4eb58f12018-12-07 16:41:02 -08002051 status_t status = inputDesc->start();
2052 if (status != NO_ERROR) {
2053 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002054 }
Eric Laurente552edb2014-03-10 17:42:56 -07002055
Eric Laurent4eb58f12018-12-07 16:41:02 -08002056 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002057 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002058 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002059
Eric Laurent8f42ea12018-08-08 09:08:25 -07002060 // indicate active capture to sound trigger service if starting capture from a mic on
2061 // primary HW module
2062 audio_devices_t device = getNewInputDevice(inputDesc);
2063 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002064
Eric Laurent8f42ea12018-08-08 09:08:25 -07002065 if (inputDesc->activeCount() == 1) {
2066 // if input maps to a dynamic policy with an activity listener, notify of state change
2067 if ((inputDesc->mPolicyMix != NULL)
2068 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2069 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2070 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002071 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002072
Eric Laurent8f42ea12018-08-08 09:08:25 -07002073 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2074 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2075 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
2076 SoundTrigger::setCaptureState(true);
2077 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002078
Eric Laurent8f42ea12018-08-08 09:08:25 -07002079 // automatically enable the remote submix output when input is started if not
2080 // used by a policy mix of type MIX_TYPE_RECORDERS
2081 // For remote submix (a virtual device), we open only one input per capture request.
2082 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2083 String8 address = String8("");
2084 if (inputDesc->mPolicyMix == NULL) {
2085 address = String8("0");
2086 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2087 address = inputDesc->mPolicyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002088 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002089 if (address != "") {
2090 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2091 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2092 address, "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08002093 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002094 }
Eric Laurente552edb2014-03-10 17:42:56 -07002095 }
2096
Eric Laurent8f42ea12018-08-08 09:08:25 -07002097 ALOGV("%s input %d source = %d exit", __FUNCTION__, input, client->source());
Eric Laurente552edb2014-03-10 17:42:56 -07002098
Eric Laurente552edb2014-03-10 17:42:56 -07002099 return NO_ERROR;
2100}
2101
Eric Laurent8fc147b2018-07-22 19:13:55 -07002102status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002103{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002104 ALOGV("%s portId %d", __FUNCTION__, portId);
2105
2106 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2107 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002108 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002109 return BAD_VALUE;
2110 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002111 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002112 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002113 if (!client->active()) {
2114 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002115 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002116 }
2117
Eric Laurent8f42ea12018-08-08 09:08:25 -07002118 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002119
Eric Laurent8f42ea12018-08-08 09:08:25 -07002120 inputDesc->stop();
2121 if (inputDesc->isActive()) {
2122 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2123 } else {
2124 // if input maps to a dynamic policy with an activity listener, notify of state change
2125 if ((inputDesc->mPolicyMix != NULL)
2126 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2127 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2128 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002129 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002130
2131 // automatically disable the remote submix output when input is stopped if not
2132 // used by a policy mix of type MIX_TYPE_RECORDERS
2133 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2134 String8 address = String8("");
2135 if (inputDesc->mPolicyMix == NULL) {
2136 address = String8("0");
2137 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2138 address = inputDesc->mPolicyMix->mDeviceAddress;
2139 }
2140 if (address != "") {
2141 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2142 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2143 address, "remote-submix");
2144 }
2145 }
2146
2147 audio_devices_t device = inputDesc->mDevice;
2148 resetInputDevice(input);
2149
2150 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2151 // primary HW module
2152 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2153 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2154 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
2155 SoundTrigger::setCaptureState(false);
2156 }
2157 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002158 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002159 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002160}
2161
Eric Laurent8fc147b2018-07-22 19:13:55 -07002162void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002163{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002164 ALOGV("%s portId %d", __FUNCTION__, portId);
2165
2166 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2167 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002168 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002169 return;
2170 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002171 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002172 audio_io_handle_t input = inputDesc->mIoHandle;
2173
Eric Laurent8f42ea12018-08-08 09:08:25 -07002174 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002175
Andy Hung39efb7a2018-09-26 15:39:28 -07002176 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002177
Andy Hung39efb7a2018-09-26 15:39:28 -07002178 if (inputDesc->getClientCount() > 0) {
2179 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002180 return;
2181 }
2182
Eric Laurent05b90f82014-08-27 15:32:29 -07002183 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002184 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002185 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002186}
2187
Eric Laurent8f42ea12018-08-08 09:08:25 -07002188void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002189{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002190 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002191
2192 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002193 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002194 }
2195}
2196
Eric Laurent8f42ea12018-08-08 09:08:25 -07002197void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2198{
2199 stopInput(portId);
2200 releaseInput(portId);
2201}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002202
Eric Laurentd4692962014-05-05 18:13:44 -07002203void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002204 bool patchRemoved = false;
2205
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002206 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002207 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002208 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002209 if (patch_index >= 0) {
2210 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002211 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002212 mAudioPatches.removeItemsAt(patch_index);
2213 patchRemoved = true;
2214 }
Eric Laurentfe231122017-11-17 17:48:06 -08002215 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002216 }
2217 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002218 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002219 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002220
2221 if (patchRemoved) {
2222 mpClientInterface->onAudioPatchListUpdate();
2223 }
Eric Laurentd4692962014-05-05 18:13:44 -07002224}
2225
Eric Laurente0720872014-03-11 09:30:41 -07002226void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002227 int indexMin,
2228 int indexMax)
2229{
2230 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002231 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002232
2233 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002234 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2235 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002236 continue;
2237 }
2238 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002239 }
Eric Laurente552edb2014-03-10 17:42:56 -07002240}
2241
Eric Laurente0720872014-03-11 09:30:41 -07002242status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002243 int index,
2244 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002245{
2246
Nadav Bar7c605f62017-12-25 00:01:52 +02002247 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2248 // app that has MODIFY_PHONE_STATE permission.
2249 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
2250 !(stream == AUDIO_STREAM_VOICE_CALL && index == 0)) ||
François Gaffied1ab2bd2015-12-02 18:20:06 +01002251 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002252 return BAD_VALUE;
2253 }
2254 if (!audio_is_output_device(device)) {
2255 return BAD_VALUE;
2256 }
2257
2258 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002259 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002260
Eric Laurent1fd372e2016-04-06 14:23:53 -07002261 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002262 stream, device, index);
2263
Eric Laurent28d09f02016-03-08 10:43:05 -08002264 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002265 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2266 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002267 continue;
2268 }
2269 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2270 }
Eric Laurente552edb2014-03-10 17:42:56 -07002271
Eric Laurent1fd372e2016-04-06 14:23:53 -07002272 // update volume on all outputs and streams matching the following:
2273 // - The requested stream (or a stream matching for volume control) is active on the output
2274 // - The device (or devices) selected by the strategy corresponding to this stream includes
2275 // the requested device
2276 // - For non default requested device, currently selected device on the output is either the
2277 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002278 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2279 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002280 status_t status = NO_ERROR;
2281 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002282 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
nobuaki tanaka985d15a2017-07-19 13:38:51 +09002283 audio_devices_t curDevice = desc->device();
Eric Laurent794fde22016-03-11 09:50:45 -08002284 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
Eric Laurent3839bc02018-07-10 18:33:34 -07002285 if (!(streamsMatchForvolume(stream, (audio_stream_type_t)curStream))) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002286 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002287 }
Eric Laurentdcd4ab12018-06-29 17:45:13 -07002288 if (!(desc->isStreamActive((audio_stream_type_t)curStream) || isInCall())) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002289 continue;
2290 }
Eric Laurent794fde22016-03-11 09:50:45 -08002291 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002292 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2293 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002294 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2295 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002296 continue;
2297 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002298 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002299 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002300 curStreamDevice |= device;
nobuaki tanaka985d15a2017-07-19 13:38:51 +09002301 applyVolume = (Volume::getDeviceForVolume(curDevice) & curStreamDevice) != 0;
Eric Laurente76f29c2016-09-14 17:17:53 -07002302 } else {
2303 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002304 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002305 }
Eric Laurent3839bc02018-07-10 18:33:34 -07002306 // rescale index before applying to curStream as ranges may be different for
2307 // stream and curStream
2308 int idx = rescaleVolumeIndex(index, stream, (audio_stream_type_t)curStream);
Eric Laurente76f29c2016-09-14 17:17:53 -07002309 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002310 //FIXME: workaround for truncated touch sounds
2311 // delayed volume change for system stream to be removed when the problem is
2312 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002313 status_t volStatus =
Eric Laurent3839bc02018-07-10 18:33:34 -07002314 checkAndSetVolume((audio_stream_type_t)curStream, idx, desc, curDevice,
Eric Laurentdc462862016-07-19 12:29:53 -07002315 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002316 if (volStatus != NO_ERROR) {
2317 status = volStatus;
2318 }
2319 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002320 }
Eric Laurente552edb2014-03-10 17:42:56 -07002321 }
2322 return status;
2323}
2324
Eric Laurente0720872014-03-11 09:30:41 -07002325status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002326 int *index,
2327 audio_devices_t device)
2328{
2329 if (index == NULL) {
2330 return BAD_VALUE;
2331 }
2332 if (!audio_is_output_device(device)) {
2333 return BAD_VALUE;
2334 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002335 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002336 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002337 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002338 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2339 }
François Gaffiedfd74092015-03-19 12:10:59 +01002340 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002341
François Gaffied1ab2bd2015-12-02 18:20:06 +01002342 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002343 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2344 return NO_ERROR;
2345}
2346
Eric Laurent36829f92017-04-07 19:04:42 -07002347audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002348{
2349 // select one output among several suitable for global effects.
2350 // The priority is as follows:
2351 // 1: An offloaded output. If the effect ends up not being offloadable,
2352 // AudioFlinger will invalidate the track and the offloaded output
2353 // will be closed causing the effect to be moved to a PCM output.
2354 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002355 // 3: The primary output
2356 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002357
Eric Laurent3b73df72014-03-11 09:06:29 -07002358 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002359 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent36829f92017-04-07 19:04:42 -07002360 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002361
Eric Laurent36829f92017-04-07 19:04:42 -07002362 if (outputs.size() == 0) {
2363 return AUDIO_IO_HANDLE_NONE;
2364 }
Eric Laurente552edb2014-03-10 17:42:56 -07002365
Eric Laurent36829f92017-04-07 19:04:42 -07002366 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2367 bool activeOnly = true;
2368
2369 while (output == AUDIO_IO_HANDLE_NONE) {
2370 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2371 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2372 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2373
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002374 for (audio_io_handle_t output : outputs) {
2375 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002376 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2377 continue;
2378 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002379 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2380 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002381 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002382 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002383 }
2384 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002385 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002386 }
2387 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002388 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002389 }
2390 }
2391 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2392 output = outputOffloaded;
2393 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2394 output = outputDeepBuffer;
2395 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2396 output = outputPrimary;
2397 } else {
2398 output = outputs[0];
2399 }
2400 activeOnly = false;
2401 }
2402
2403 if (output != mMusicEffectOutput) {
2404 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2405 mMusicEffectOutput = output;
2406 }
2407
2408 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002409 return output;
2410}
2411
Eric Laurent36829f92017-04-07 19:04:42 -07002412audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2413{
2414 return selectOutputForMusicEffects();
2415}
2416
Eric Laurente0720872014-03-11 09:30:41 -07002417status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002418 audio_io_handle_t io,
2419 uint32_t strategy,
2420 int session,
2421 int id)
2422{
2423 ssize_t index = mOutputs.indexOfKey(io);
2424 if (index < 0) {
2425 index = mInputs.indexOfKey(io);
2426 if (index < 0) {
2427 ALOGW("registerEffect() unknown io %d", io);
2428 return INVALID_OPERATION;
2429 }
2430 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002431 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002432}
2433
Eric Laurentc241b0d2018-11-28 09:08:49 -08002434status_t AudioPolicyManager::unregisterEffect(int id)
2435{
2436 if (mEffects.getEffect(id) == nullptr) {
2437 return INVALID_OPERATION;
2438 }
2439
2440 if (mEffects.isEffectEnabled(id)) {
2441 ALOGW("%s effect %d enabled", __FUNCTION__, id);
2442 setEffectEnabled(id, false);
2443 }
2444 return mEffects.unregisterEffect(id);
2445}
2446
2447status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
2448{
2449 sp<EffectDescriptor> effect = mEffects.getEffect(id);
2450 if (effect == nullptr) {
2451 return INVALID_OPERATION;
2452 }
2453
2454 status_t status = mEffects.setEffectEnabled(id, enabled);
2455 if (status == NO_ERROR) {
2456 mInputs.trackEffectEnabled(effect, enabled);
2457 }
2458 return status;
2459}
2460
Eric Laurentc75307b2015-03-17 15:29:32 -07002461bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2462{
Eric Laurent28d09f02016-03-08 10:43:05 -08002463 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002464 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2465 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002466 continue;
2467 }
2468 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2469 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002470 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002471}
2472
2473bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2474{
2475 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2476}
2477
Eric Laurente0720872014-03-11 09:30:41 -07002478bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002479{
2480 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002481 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002482 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002483 return true;
2484 }
2485 }
2486 return false;
2487}
2488
Eric Laurent275e8e92014-11-30 15:14:47 -08002489// Register a list of custom mixes with their attributes and format.
2490// When a mix is registered, corresponding input and output profiles are
2491// added to the remote submix hw module. The profile contains only the
2492// parameters (sampling rate, format...) specified by the mix.
2493// The corresponding input remote submix device is also connected.
2494//
2495// When a remote submix device is connected, the address is checked to select the
2496// appropriate profile and the corresponding input or output stream is opened.
2497//
2498// When capture starts, getInputForAttr() will:
2499// - 1 look for a mix matching the address passed in attribtutes tags if any
2500// - 2 if none found, getDeviceForInputSource() will:
2501// - 2.1 look for a mix matching the attributes source
2502// - 2.2 if none found, default to device selection by policy rules
2503// At this time, the corresponding output remote submix device is also connected
2504// and active playback use cases can be transferred to this mix if needed when reconnecting
2505// after AudioTracks are invalidated
2506//
2507// When playback starts, getOutputForAttr() will:
2508// - 1 look for a mix matching the address passed in attribtutes tags if any
2509// - 2 if none found, look for a mix matching the attributes usage
2510// - 3 if none found, default to device and output selection by policy rules.
2511
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002512status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002513{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002514 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2515 status_t res = NO_ERROR;
2516
2517 sp<HwModule> rSubmixModule;
2518 // examine each mix's route type
2519 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002520 AudioMix mix = mixes[i];
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002521 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
Eric Laurent97ac8712018-07-27 18:59:02 -07002522 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002523 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002524 break;
2525 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002526 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002527 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002528 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002529 rSubmixModule = mHwModules.getModuleFromName(
2530 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2531 if (rSubmixModule == 0) {
2532 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2533 i);
2534 res = INVALID_OPERATION;
2535 break;
2536 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002537 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002538
Eric Laurent97ac8712018-07-27 18:59:02 -07002539 String8 address = mix.mDeviceAddress;
2540 if (mix.mMixType == MIX_TYPE_PLAYERS) {
2541 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2542 } else {
2543 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
2544 }
François Gaffie036e1e92015-03-19 10:16:24 +01002545
Eric Laurent97ac8712018-07-27 18:59:02 -07002546 if (mPolicyMixes.registerMix(address, mix, 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002547 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002548 res = INVALID_OPERATION;
2549 break;
2550 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002551 audio_config_t outputConfig = mix.mFormat;
2552 audio_config_t inputConfig = mix.mFormat;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002553 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2554 // stereo and let audio flinger do the channel conversion if needed.
2555 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2556 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2557 rSubmixModule->addOutputProfile(address, &outputConfig,
2558 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2559 rSubmixModule->addInputProfile(address, &inputConfig,
2560 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002561
Eric Laurent97ac8712018-07-27 18:59:02 -07002562 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002563 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2564 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2565 address.string(), "remote-submix");
2566 } else {
2567 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2568 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2569 address.string(), "remote-submix");
2570 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002571 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2572 String8 address = mix.mDeviceAddress;
2573 audio_devices_t device = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002574 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2575 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002576
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002577 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002578 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2579 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2580 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2581 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2582 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2583 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002584 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2585 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002586 if (mPolicyMixes.registerMix(address, mix, desc) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002587 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002588 } else {
2589 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002590 }
2591 break;
2592 }
2593 }
2594
2595 if (res != NO_ERROR) {
2596 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002597 i, device, address.string());
2598 res = INVALID_OPERATION;
2599 break;
2600 } else if (!foundOutput) {
2601 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2602 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002603 res = INVALID_OPERATION;
2604 break;
2605 }
Eric Laurentc722f302014-12-10 11:21:49 -08002606 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002607 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002608 if (res != NO_ERROR) {
2609 unregisterPolicyMixes(mixes);
2610 }
2611 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002612}
2613
2614status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2615{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002616 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002617 status_t res = NO_ERROR;
2618 sp<HwModule> rSubmixModule;
2619 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002620 for (const auto& mix : mixes) {
2621 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002622
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002623 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002624 rSubmixModule = mHwModules.getModuleFromName(
2625 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2626 if (rSubmixModule == 0) {
2627 res = INVALID_OPERATION;
2628 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002629 }
2630 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002631
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002632 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002633
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002634 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2635 res = INVALID_OPERATION;
2636 continue;
2637 }
2638
2639 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2640 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2641 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2642 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2643 address.string(), "remote-submix");
2644 }
2645 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2646 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2647 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2648 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2649 address.string(), "remote-submix");
2650 }
2651 rSubmixModule->removeOutputProfile(address);
2652 rSubmixModule->removeInputProfile(address);
2653
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002654 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2655 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002656 res = INVALID_OPERATION;
2657 continue;
2658 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002659 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002660 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002661 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002662}
2663
Mikhail Naganov100f0122018-11-29 11:22:16 -08002664void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
2665{
2666 size_t i = 0;
2667 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
2668 for (const auto& fmt : mManualSurroundFormats) {
2669 if (i++ != 0) dst->append(", ");
2670 std::string sfmt;
2671 FormatConverter::toString(fmt, sfmt);
2672 dst->append(sfmt.size() >= audioFormatPrefixLen ?
2673 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
2674 }
2675}
2676
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002677status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
2678 const Vector<AudioDeviceTypeAddr>& devices) {
2679 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
2680 // uid/device affinity is only for output devices
2681 for (size_t i = 0; i < devices.size(); i++) {
2682 if (!audio_is_output_device(devices[i].mType)) {
2683 ALOGE("setUidDeviceAffinities() device=%08x is NOT an output device",
2684 devices[i].mType);
2685 return BAD_VALUE;
2686 }
2687 }
2688 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
2689 if (res == NO_ERROR) {
2690 // reevaluate outputs for all given devices
2691 for (size_t i = 0; i < devices.size(); i++) {
2692 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
2693 devices[i].mType, devices[i].mAddress, String8());
2694 SortedVector<audio_io_handle_t> outputs;
2695 if (checkOutputsForDevice(devDesc, AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2696 outputs,
2697 devDesc->address()) != NO_ERROR) {
2698 ALOGE("setUidDeviceAffinities() error in checkOutputsForDevice for device=%08x"
2699 " addr=%s", devices[i].mType, devices[i].mAddress.string());
2700 return INVALID_OPERATION;
2701 }
2702 }
2703 }
2704 return res;
2705}
2706
2707status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
2708 ALOGV("%s() uid=%d", __FUNCTION__, uid);
2709 Vector<AudioDeviceTypeAddr> devices;
2710 status_t res = mPolicyMixes.getDevicesForUid(uid, devices);
2711 if (res == NO_ERROR) {
2712 // reevaluate outputs for all found devices
2713 for (size_t i = 0; i < devices.size(); i++) {
2714 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
2715 devices[i].mType, devices[i].mAddress, String8());
2716 SortedVector<audio_io_handle_t> outputs;
2717 if (checkOutputsForDevice(devDesc, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2718 outputs,
2719 devDesc->address()) != NO_ERROR) {
2720 ALOGE("%s() error in checkOutputsForDevice for device=%08x addr=%s",
2721 __FUNCTION__, devices[i].mType, devices[i].mAddress.string());
2722 return INVALID_OPERATION;
2723 }
2724 }
2725 }
2726
2727 return res;
2728}
2729
Andy Hungc29d82b2018-10-05 12:23:17 -07002730void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07002731{
Andy Hungc29d82b2018-10-05 12:23:17 -07002732 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
2733 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07002734 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002735 std::string stateLiteral;
2736 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07002737 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002738 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
2739 "communications", "media", "record", "dock", "system",
2740 "HDMI system audio", "encoded surround output", "vibrate ringing" };
2741 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
2742 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08002743 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
2744 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
2745 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
2746 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
2747 dst->append(" (MANUAL: ");
2748 dumpManualSurroundFormats(dst);
2749 dst->append(")");
2750 }
2751 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002752 }
Andy Hungc29d82b2018-10-05 12:23:17 -07002753 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
2754 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
2755 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
2756 mAvailableOutputDevices.dump(dst, String8("Available output"));
2757 mAvailableInputDevices.dump(dst, String8("Available input"));
2758 mHwModulesAll.dump(dst);
2759 mOutputs.dump(dst);
2760 mInputs.dump(dst);
2761 mVolumeCurves->dump(dst);
2762 mEffects.dump(dst);
2763 mAudioPatches.dump(dst);
2764 mPolicyMixes.dump(dst);
2765 mAudioSources.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07002766}
2767
2768status_t AudioPolicyManager::dump(int fd)
2769{
2770 String8 result;
2771 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07002772 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002773 return NO_ERROR;
2774}
2775
2776// This function checks for the parameters which can be offloaded.
2777// This can be enhanced depending on the capability of the DSP and policy
2778// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002779bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002780{
2781 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002782 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002783 offloadInfo.sample_rate, offloadInfo.channel_mask,
2784 offloadInfo.format,
2785 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2786 offloadInfo.has_video);
2787
Andy Hung2ddee192015-12-18 17:34:44 -08002788 if (mMasterMono) {
2789 return false; // no offloading if mono is set.
2790 }
2791
Eric Laurente552edb2014-03-10 17:42:56 -07002792 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07002793 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
2794 ALOGV("offload disabled by audio.offload.disable");
2795 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002796 }
2797
2798 // Check if stream type is music, then only allow offload as of now.
2799 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2800 {
2801 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2802 return false;
2803 }
2804
2805 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002806 const bool allowOffloadWithVideo =
2807 property_get_bool("audio.offload.video", false /* default_value */);
2808 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002809 ALOGV("isOffloadSupported: has_video == true, returning false");
2810 return false;
2811 }
2812
2813 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07002814 const int min_duration_secs = property_get_int32(
2815 "audio.offload.min.duration.secs", -1 /* default_value */);
2816 if (min_duration_secs >= 0) {
2817 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
2818 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%d)",
2819 min_duration_secs);
Eric Laurente552edb2014-03-10 17:42:56 -07002820 return false;
2821 }
2822 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2823 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2824 return false;
2825 }
2826
2827 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2828 // creating an offloaded track and tearing it down immediately after start when audioflinger
2829 // detects there is an active non offloadable effect.
2830 // FIXME: We should check the audio session here but we do not have it in this context.
2831 // This may prevent offloading in rare situations where effects are left active by apps
2832 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002833 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002834 return false;
2835 }
2836
2837 // See if there is a profile to support this.
2838 // AUDIO_DEVICE_NONE
Michael Chana94fbb22018-04-24 14:31:19 +10002839 sp<IOProfile> profile = getProfileForOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002840 offloadInfo.sample_rate,
2841 offloadInfo.format,
2842 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10002843 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
2844 true /* directOnly */);
Eric Laurent1c333e22014-05-20 10:48:17 -07002845 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2846 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002847}
2848
Michael Chana94fbb22018-04-24 14:31:19 +10002849bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
2850 const audio_attributes_t& attributes) {
2851 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
2852 audio_attributes_flags_to_audio_output_flags(attributes.flags, output_flags);
2853 sp<IOProfile> profile = getProfileForOutput(AUDIO_DEVICE_NONE /*ignore device */,
2854 config.sample_rate,
2855 config.format,
2856 config.channel_mask,
2857 output_flags,
2858 true /* directOnly */);
2859 ALOGV("%s() profile %sfound with name: %s, "
2860 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
2861 __FUNCTION__, profile != 0 ? "" : "NOT ",
2862 (profile != 0 ? profile->getTagName().string() : "null"),
2863 config.sample_rate, config.format, config.channel_mask, output_flags);
2864 return (profile != 0);
2865}
2866
Eric Laurent6a94d692014-05-20 11:18:06 -07002867status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2868 audio_port_type_t type,
2869 unsigned int *num_ports,
2870 struct audio_port *ports,
2871 unsigned int *generation)
2872{
2873 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2874 generation == NULL) {
2875 return BAD_VALUE;
2876 }
2877 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2878 if (ports == NULL) {
2879 *num_ports = 0;
2880 }
2881
2882 size_t portsWritten = 0;
2883 size_t portsMax = *num_ports;
2884 *num_ports = 0;
2885 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002886 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2887 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002888 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002889 for (const auto& dev : mAvailableOutputDevices) {
2890 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002891 continue;
2892 }
2893 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002894 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002895 }
2896 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002897 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002898 }
2899 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002900 for (const auto& dev : mAvailableInputDevices) {
2901 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002902 continue;
2903 }
2904 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002905 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002906 }
2907 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002908 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002909 }
2910 }
2911 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2912 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2913 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2914 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2915 }
2916 *num_ports += mInputs.size();
2917 }
2918 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002919 size_t numOutputs = 0;
2920 for (size_t i = 0; i < mOutputs.size(); i++) {
2921 if (!mOutputs[i]->isDuplicated()) {
2922 numOutputs++;
2923 if (portsWritten < portsMax) {
2924 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2925 }
2926 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002927 }
Eric Laurent84c70242014-06-23 08:46:27 -07002928 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002929 }
2930 }
2931 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002932 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002933 return NO_ERROR;
2934}
2935
Eric Laurent99fcae42018-05-17 16:59:18 -07002936status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07002937{
Eric Laurent99fcae42018-05-17 16:59:18 -07002938 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
2939 return BAD_VALUE;
2940 }
2941 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
2942 if (dev != 0) {
2943 dev->toAudioPort(port);
2944 return NO_ERROR;
2945 }
2946 dev = mAvailableInputDevices.getDeviceFromId(port->id);
2947 if (dev != 0) {
2948 dev->toAudioPort(port);
2949 return NO_ERROR;
2950 }
2951 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
2952 if (out != 0) {
2953 out->toAudioPort(port);
2954 return NO_ERROR;
2955 }
2956 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
2957 if (in != 0) {
2958 in->toAudioPort(port);
2959 return NO_ERROR;
2960 }
2961 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002962}
2963
Eric Laurent6a94d692014-05-20 11:18:06 -07002964status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2965 audio_patch_handle_t *handle,
2966 uid_t uid)
2967{
2968 ALOGV("createAudioPatch()");
2969
2970 if (handle == NULL || patch == NULL) {
2971 return BAD_VALUE;
2972 }
2973 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2974
Mikhail Naganovac9858b2018-06-15 13:12:37 -07002975 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07002976 return BAD_VALUE;
2977 }
2978 // only one source per audio patch supported for now
2979 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002980 return INVALID_OPERATION;
2981 }
Eric Laurent874c42872014-08-08 15:13:39 -07002982
2983 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002984 return INVALID_OPERATION;
2985 }
Eric Laurent874c42872014-08-08 15:13:39 -07002986 for (size_t i = 0; i < patch->num_sinks; i++) {
2987 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2988 return INVALID_OPERATION;
2989 }
2990 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002991
2992 sp<AudioPatch> patchDesc;
2993 ssize_t index = mAudioPatches.indexOfKey(*handle);
2994
Eric Laurent6a94d692014-05-20 11:18:06 -07002995 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2996 patch->sources[0].role,
2997 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002998#if LOG_NDEBUG == 0
2999 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08003000 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07003001 patch->sinks[i].role,
3002 patch->sinks[i].type);
3003 }
3004#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07003005
3006 if (index >= 0) {
3007 patchDesc = mAudioPatches.valueAt(index);
3008 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3009 mUidCached, patchDesc->mUid, uid);
3010 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3011 return INVALID_OPERATION;
3012 }
3013 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07003014 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003015 }
3016
3017 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003018 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003019 if (outputDesc == NULL) {
3020 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
3021 return BAD_VALUE;
3022 }
Eric Laurent84c70242014-06-23 08:46:27 -07003023 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
3024 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003025 if (patchDesc != 0) {
3026 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
3027 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
3028 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
3029 return BAD_VALUE;
3030 }
3031 }
Eric Laurent874c42872014-08-08 15:13:39 -07003032 DeviceVector devices;
3033 for (size_t i = 0; i < patch->num_sinks; i++) {
3034 // Only support mix to devices connection
3035 // TODO add support for mix to mix connection
3036 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3037 ALOGV("createAudioPatch() source mix but sink is not a device");
3038 return INVALID_OPERATION;
3039 }
3040 sp<DeviceDescriptor> devDesc =
3041 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3042 if (devDesc == 0) {
3043 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
3044 return BAD_VALUE;
3045 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003046
François Gaffie53615e22015-03-19 09:24:12 +01003047 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
François Gaffieaca677c2018-05-03 10:47:50 +02003048 devDesc->address(),
Eric Laurent874c42872014-08-08 15:13:39 -07003049 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01003050 NULL, // updatedSamplingRate
3051 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003052 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01003053 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003054 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01003055 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07003056 ALOGV("createAudioPatch() profile not supported for device %08x",
3057 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07003058 return INVALID_OPERATION;
3059 }
3060 devices.add(devDesc);
3061 }
3062 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003063 return INVALID_OPERATION;
3064 }
Eric Laurent874c42872014-08-08 15:13:39 -07003065
Eric Laurent6a94d692014-05-20 11:18:06 -07003066 // TODO: reconfigure output format and channels here
3067 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07003068 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07003069 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003070 index = mAudioPatches.indexOfKey(*handle);
3071 if (index >= 0) {
3072 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3073 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
3074 }
3075 patchDesc = mAudioPatches.valueAt(index);
3076 patchDesc->mUid = uid;
3077 ALOGV("createAudioPatch() success");
3078 } else {
3079 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
3080 return INVALID_OPERATION;
3081 }
3082 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3083 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3084 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003085 // only one sink supported when connecting an input device to a mix
3086 if (patch->num_sinks > 1) {
3087 return INVALID_OPERATION;
3088 }
François Gaffie53615e22015-03-19 09:24:12 +01003089 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003090 if (inputDesc == NULL) {
3091 return BAD_VALUE;
3092 }
3093 if (patchDesc != 0) {
3094 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3095 return BAD_VALUE;
3096 }
3097 }
3098 sp<DeviceDescriptor> devDesc =
3099 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
3100 if (devDesc == 0) {
3101 return BAD_VALUE;
3102 }
3103
François Gaffie53615e22015-03-19 09:24:12 +01003104 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
François Gaffieaca677c2018-05-03 10:47:50 +02003105 devDesc->address(),
Eric Laurent275e8e92014-11-30 15:14:47 -08003106 patch->sinks[0].sample_rate,
3107 NULL, /*updatedSampleRate*/
3108 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003109 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003110 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003111 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003112 // FIXME for the parameter type,
3113 // and the NONE
3114 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003115 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003116 return INVALID_OPERATION;
3117 }
3118 // TODO: reconfigure output format and channels here
3119 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01003120 devDesc->type(), inputDesc->mIoHandle);
3121 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003122 index = mAudioPatches.indexOfKey(*handle);
3123 if (index >= 0) {
3124 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3125 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
3126 }
3127 patchDesc = mAudioPatches.valueAt(index);
3128 patchDesc->mUid = uid;
3129 ALOGV("createAudioPatch() success");
3130 } else {
3131 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
3132 return INVALID_OPERATION;
3133 }
3134 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3135 // device to device connection
3136 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003137 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003138 return BAD_VALUE;
3139 }
3140 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003141 sp<DeviceDescriptor> srcDeviceDesc =
3142 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07003143 if (srcDeviceDesc == 0) {
3144 return BAD_VALUE;
3145 }
Eric Laurent874c42872014-08-08 15:13:39 -07003146
Eric Laurent6a94d692014-05-20 11:18:06 -07003147 //update source and sink with our own data as the data passed in the patch may
3148 // be incomplete.
3149 struct audio_patch newPatch = *patch;
3150 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003151
Eric Laurent874c42872014-08-08 15:13:39 -07003152 for (size_t i = 0; i < patch->num_sinks; i++) {
3153 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3154 ALOGV("createAudioPatch() source device but one sink is not a device");
3155 return INVALID_OPERATION;
3156 }
3157
3158 sp<DeviceDescriptor> sinkDeviceDesc =
3159 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3160 if (sinkDeviceDesc == 0) {
3161 return BAD_VALUE;
3162 }
3163 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
3164
Eric Laurent3bcf8592015-04-03 12:13:24 -07003165 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003166 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003167 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02003168 // - audio HAL version is >= 3.0 but no route has been declared between devices
Eric Laurentfb66dd92016-01-28 18:32:03 -08003169 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
François Gaffieaca677c2018-05-03 10:47:50 +02003170 (srcDeviceDesc->getModuleVersionMajor() < 3) ||
3171 !srcDeviceDesc->getModule()->supportsPatch(srcDeviceDesc, sinkDeviceDesc)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003172 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003173 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003174 return INVALID_OPERATION;
3175 }
Eric Laurent874c42872014-08-08 15:13:39 -07003176 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01003177 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003178 // if the sink device is reachable via an opened output stream, request to go via
3179 // this output stream by adding a second source to the patch description
jiabin40573322018-11-08 12:08:02 -08003180 audio_io_handle_t output = selectOutput(outputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003181 if (output != AUDIO_IO_HANDLE_NONE) {
3182 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3183 if (outputDesc->isDuplicated()) {
3184 return INVALID_OPERATION;
3185 }
3186 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003187 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003188 newPatch.num_sources = 2;
3189 }
Eric Laurent83b88082014-06-20 18:31:16 -07003190 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003191 }
3192 // TODO: check from routing capabilities in config file and other conflicting patches
3193
Mikhail Naganovdc769682018-05-04 15:34:08 -07003194 status_t status = installPatch(__func__, index, handle, &newPatch, 0, uid, &patchDesc);
3195 if (status != NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003196 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3197 status);
3198 return INVALID_OPERATION;
3199 }
3200 } else {
3201 return BAD_VALUE;
3202 }
3203 } else {
3204 return BAD_VALUE;
3205 }
3206 return NO_ERROR;
3207}
3208
3209status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3210 uid_t uid)
3211{
3212 ALOGV("releaseAudioPatch() patch %d", handle);
3213
3214 ssize_t index = mAudioPatches.indexOfKey(handle);
3215
3216 if (index < 0) {
3217 return BAD_VALUE;
3218 }
3219 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3220 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3221 mUidCached, patchDesc->mUid, uid);
3222 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3223 return INVALID_OPERATION;
3224 }
3225
3226 struct audio_patch *patch = &patchDesc->mPatch;
3227 patchDesc->mUid = mUidCached;
3228 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003229 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003230 if (outputDesc == NULL) {
3231 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3232 return BAD_VALUE;
3233 }
3234
Eric Laurentc75307b2015-03-17 15:29:32 -07003235 setOutputDevice(outputDesc,
3236 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07003237 true,
3238 0,
3239 NULL);
3240 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3241 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003242 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003243 if (inputDesc == NULL) {
3244 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3245 return BAD_VALUE;
3246 }
3247 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003248 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003249 true,
3250 NULL);
3251 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003252 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3253 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3254 status, patchDesc->mAfPatchHandle);
3255 removeAudioPatch(patchDesc->mHandle);
3256 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003257 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003258 } else {
3259 return BAD_VALUE;
3260 }
3261 } else {
3262 return BAD_VALUE;
3263 }
3264 return NO_ERROR;
3265}
3266
3267status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3268 struct audio_patch *patches,
3269 unsigned int *generation)
3270{
François Gaffie53615e22015-03-19 09:24:12 +01003271 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003272 return BAD_VALUE;
3273 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003274 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003275 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003276}
3277
Eric Laurente1715a42014-05-20 11:30:42 -07003278status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003279{
Eric Laurente1715a42014-05-20 11:30:42 -07003280 ALOGV("setAudioPortConfig()");
3281
3282 if (config == NULL) {
3283 return BAD_VALUE;
3284 }
3285 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3286 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003287 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3288 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003289 }
3290
Eric Laurenta121f902014-06-03 13:32:54 -07003291 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003292 if (config->type == AUDIO_PORT_TYPE_MIX) {
3293 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003294 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003295 if (outputDesc == NULL) {
3296 return BAD_VALUE;
3297 }
Eric Laurent84c70242014-06-23 08:46:27 -07003298 ALOG_ASSERT(!outputDesc->isDuplicated(),
3299 "setAudioPortConfig() called on duplicated output %d",
3300 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003301 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003302 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003303 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003304 if (inputDesc == NULL) {
3305 return BAD_VALUE;
3306 }
Eric Laurenta121f902014-06-03 13:32:54 -07003307 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003308 } else {
3309 return BAD_VALUE;
3310 }
3311 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3312 sp<DeviceDescriptor> deviceDesc;
3313 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3314 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3315 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3316 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3317 } else {
3318 return BAD_VALUE;
3319 }
3320 if (deviceDesc == NULL) {
3321 return BAD_VALUE;
3322 }
Eric Laurenta121f902014-06-03 13:32:54 -07003323 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003324 } else {
3325 return BAD_VALUE;
3326 }
3327
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003328 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003329 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3330 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003331 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003332 audioPortConfig->toAudioPortConfig(&newConfig, config);
3333 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003334 }
Eric Laurenta121f902014-06-03 13:32:54 -07003335 if (status != NO_ERROR) {
3336 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003337 }
Eric Laurente1715a42014-05-20 11:30:42 -07003338
3339 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003340}
3341
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003342void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3343{
Eric Laurentd60560a2015-04-10 11:31:20 -07003344 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003345 clearAudioPatches(uid);
3346 clearSessionRoutes(uid);
3347}
3348
Eric Laurent6a94d692014-05-20 11:18:06 -07003349void AudioPolicyManager::clearAudioPatches(uid_t uid)
3350{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003351 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003352 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3353 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003354 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003355 }
3356 }
3357}
3358
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003359void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3360 audio_io_handle_t ouptutToSkip)
3361{
3362 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3363 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3364 for (size_t j = 0; j < mOutputs.size(); j++) {
3365 if (mOutputs.keyAt(j) == ouptutToSkip) {
3366 continue;
3367 }
3368 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3369 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3370 continue;
3371 }
3372 // If the default device for this strategy is on another output mix,
3373 // invalidate all tracks in this strategy to force re connection.
3374 // Otherwise select new device on the output mix.
3375 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003376 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003377 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3378 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3379 }
3380 }
3381 } else {
3382 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3383 setOutputDevice(outputDesc, newDevice, false);
3384 }
3385 }
3386}
3387
3388void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3389{
3390 // remove output routes associated with this uid
3391 SortedVector<routing_strategy> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07003392 for (size_t i = 0; i < mOutputs.size(); i++) {
3393 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003394 for (const auto& client : outputDesc->getClientIterable()) {
3395 if (client->hasPreferredDevice() && client->uid() == uid) {
3396 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3397 affectedStrategies.add(getStrategy(client->stream()));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003398 }
3399 }
3400 }
3401 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003402 for (const auto& strategy : affectedStrategies) {
3403 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003404 }
3405
3406 // remove input routes associated with this uid
3407 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07003408 for (size_t i = 0; i < mInputs.size(); i++) {
3409 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003410 for (const auto& client : inputDesc->getClientIterable()) {
3411 if (client->hasPreferredDevice() && client->uid() == uid) {
3412 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3413 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003414 }
3415 }
3416 }
3417 // reroute inputs if necessary
3418 SortedVector<audio_io_handle_t> inputsToClose;
3419 for (size_t i = 0; i < mInputs.size(); i++) {
3420 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08003421 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003422 inputsToClose.add(inputDesc->mIoHandle);
3423 }
3424 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003425 for (const auto& input : inputsToClose) {
3426 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003427 }
3428}
3429
Eric Laurentd60560a2015-04-10 11:31:20 -07003430void AudioPolicyManager::clearAudioSources(uid_t uid)
3431{
3432 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003433 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3434 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07003435 stopAudioSource(mAudioSources.keyAt(i));
3436 }
3437 }
3438}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003439
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003440status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3441 audio_io_handle_t *ioHandle,
3442 audio_devices_t *device)
3443{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003444 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3445 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003446 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003447
François Gaffiedf372692015-03-19 10:43:27 +01003448 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003449}
3450
Eric Laurentd60560a2015-04-10 11:31:20 -07003451status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003452 const audio_attributes_t *attributes,
3453 audio_port_handle_t *portId,
3454 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003455{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003456 ALOGV("%s", __FUNCTION__);
3457 *portId = AUDIO_PORT_HANDLE_NONE;
3458
3459 if (source == NULL || attributes == NULL || portId == NULL) {
3460 ALOGW("%s invalid argument: source %p attributes %p handle %p",
3461 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003462 return BAD_VALUE;
3463 }
3464
Eric Laurentd60560a2015-04-10 11:31:20 -07003465 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3466 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003467 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
3468 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003469 return INVALID_OPERATION;
3470 }
3471
3472 sp<DeviceDescriptor> srcDeviceDesc =
3473 mAvailableInputDevices.getDevice(source->ext.device.type,
3474 String8(source->ext.device.address));
3475 if (srcDeviceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003476 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003477 return BAD_VALUE;
3478 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003479
3480 *portId = AudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07003481
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003482 struct audio_patch dummyPatch = {};
Eric Laurentd60560a2015-04-10 11:31:20 -07003483 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003484
3485 sp<SourceClientDescriptor> sourceDesc =
3486 new SourceClientDescriptor(*portId, uid, *attributes, patchDesc, srcDeviceDesc,
Eric Laurent97ac8712018-07-27 18:59:02 -07003487 streamTypefromAttributesInt(attributes),
3488 getStrategyForAttr(attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07003489
3490 status_t status = connectAudioSource(sourceDesc);
3491 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003492 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003493 }
3494 return status;
3495}
3496
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003497status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003498{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003499 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003500
3501 // make sure we only have one patch per source.
3502 disconnectAudioSource(sourceDesc);
3503
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003504 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003505 routing_strategy strategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003506 audio_stream_type_t stream = sourceDesc->stream();
3507 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->srcDevice();
Eric Laurentd60560a2015-04-10 11:31:20 -07003508
3509 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3510 sp<DeviceDescriptor> sinkDeviceDesc =
3511 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3512
3513 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003514
François Gaffie83d789d2018-05-29 13:29:19 +02003515 if (srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) &&
François Gaffieaca677c2018-05-03 10:47:50 +02003516 srcDeviceDesc->getModuleVersionMajor() >= 3 &&
3517 sinkDeviceDesc->getModule()->supportsPatch(srcDeviceDesc, sinkDeviceDesc) &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003518 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
François Gaffie83d789d2018-05-29 13:29:19 +02003519 ALOGV("%s Device to Device route supported by >=3.0 HAL", __FUNCTION__);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07003520 // TODO: may explicitly specify whether we should use HW or SW patch
François Gaffie83d789d2018-05-29 13:29:19 +02003521 // create patch between src device and output device
3522 // create Hwoutput and add to mHwOutputs
Eric Laurentd60560a2015-04-10 11:31:20 -07003523 } else {
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07003524 audio_attributes_t resultAttr;
3525 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3526 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3527 config.sample_rate = sourceDesc->config().sample_rate;
3528 config.channel_mask = sourceDesc->config().channel_mask;
3529 config.format = sourceDesc->config().format;
3530 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
3531 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3532 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE,
3533 &attributes, &stream, sourceDesc->uid(), &config, &flags, &selectedDeviceId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003534 if (output == AUDIO_IO_HANDLE_NONE) {
3535 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3536 return INVALID_OPERATION;
3537 }
3538 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3539 if (outputDesc->isDuplicated()) {
3540 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3541 return INVALID_OPERATION;
3542 }
Eric Laurent733ce942017-12-07 12:18:25 -08003543 status_t status = outputDesc->start();
3544 if (status != NO_ERROR) {
3545 return status;
3546 }
3547
Eric Laurentd60560a2015-04-10 11:31:20 -07003548 // create a special patch with no sink and two sources:
3549 // - the second source indicates to PatchPanel through which output mix this patch should
3550 // be connected as well as the stream type for volume control
3551 // - the sink is defined by whatever output device is currently selected for the output
3552 // though which this patch is routed.
Mikhail Naganovdc769682018-05-04 15:34:08 -07003553 PatchBuilder patchBuilder;
3554 patchBuilder.addSource(srcDeviceDesc).addSource(outputDesc, { .stream = stream });
3555 status = mpClientInterface->createAudioPatch(patchBuilder.patch(),
Eric Laurentd60560a2015-04-10 11:31:20 -07003556 &afPatchHandle,
3557 0);
3558 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3559 status, afPatchHandle);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003560 sourceDesc->patchDesc()->mPatch = *patchBuilder.patch();
Eric Laurentd60560a2015-04-10 11:31:20 -07003561 if (status != NO_ERROR) {
3562 ALOGW("%s patch panel could not connect device patch, error %d",
3563 __FUNCTION__, status);
3564 return INVALID_OPERATION;
3565 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07003566
3567 if (outputDesc->getClient(sourceDesc->portId()) != nullptr) {
3568 ALOGW("%s source portId has already been attached to outputDesc", __func__);
3569 return INVALID_OPERATION;
3570 }
3571 outputDesc->addClient(sourceDesc);
3572
Eric Laurentd60560a2015-04-10 11:31:20 -07003573 uint32_t delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07003574 status = startSource(outputDesc, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003575
3576 if (status != NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003577 mpClientInterface->releaseAudioPatch(sourceDesc->patchDesc()->mAfPatchHandle, 0);
Eric Laurentd60560a2015-04-10 11:31:20 -07003578 return status;
3579 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003580 sourceDesc->setSwOutput(outputDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003581 if (delayMs != 0) {
3582 usleep(delayMs * 1000);
3583 }
3584 }
3585
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003586 sourceDesc->patchDesc()->mAfPatchHandle = afPatchHandle;
3587 addAudioPatch(sourceDesc->patchDesc()->mHandle, sourceDesc->patchDesc());
Eric Laurentd60560a2015-04-10 11:31:20 -07003588
3589 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003590}
3591
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003592status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07003593{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003594 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
3595 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003596 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003597 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003598 return BAD_VALUE;
3599 }
3600 status_t status = disconnectAudioSource(sourceDesc);
3601
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003602 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003603 return status;
3604}
3605
Andy Hung2ddee192015-12-18 17:34:44 -08003606status_t AudioPolicyManager::setMasterMono(bool mono)
3607{
3608 if (mMasterMono == mono) {
3609 return NO_ERROR;
3610 }
3611 mMasterMono = mono;
3612 // if enabling mono we close all offloaded devices, which will invalidate the
3613 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3614 // for recreating the new AudioTrack as non-offloaded PCM.
3615 //
3616 // If disabling mono, we leave all tracks as is: we don't know which clients
3617 // and tracks are able to be recreated as offloaded. The next "song" should
3618 // play back offloaded.
3619 if (mMasterMono) {
3620 Vector<audio_io_handle_t> offloaded;
3621 for (size_t i = 0; i < mOutputs.size(); ++i) {
3622 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3623 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3624 offloaded.push(desc->mIoHandle);
3625 }
3626 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003627 for (const auto& handle : offloaded) {
3628 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003629 }
3630 }
3631 // update master mono for all remaining outputs
3632 for (size_t i = 0; i < mOutputs.size(); ++i) {
3633 updateMono(mOutputs.keyAt(i));
3634 }
3635 return NO_ERROR;
3636}
3637
3638status_t AudioPolicyManager::getMasterMono(bool *mono)
3639{
3640 *mono = mMasterMono;
3641 return NO_ERROR;
3642}
3643
Eric Laurentac9cef52017-06-09 15:46:26 -07003644float AudioPolicyManager::getStreamVolumeDB(
3645 audio_stream_type_t stream, int index, audio_devices_t device)
3646{
3647 return computeVolume(stream, index, device);
3648}
3649
jiabin81772902018-04-02 17:52:27 -07003650status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3651 audio_format_t *surroundFormats,
3652 bool *surroundFormatsEnabled,
3653 bool reported)
3654{
3655 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3656 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3657 return BAD_VALUE;
3658 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003659 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p reported %d",
3660 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled, reported);
jiabin81772902018-04-02 17:52:27 -07003661
3662 size_t formatsWritten = 0;
3663 size_t formatsMax = *numSurroundFormats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08003664 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
jiabin81772902018-04-02 17:52:27 -07003665 if (reported) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003666 // Return formats from all device profiles that have already been resolved by
Mikhail Naganov2563f232018-09-27 14:48:01 -07003667 // checkOutputsForDevice().
Mikhail Naganov100f0122018-11-29 11:22:16 -08003668 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
3669 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
3670 FormatVector supportedFormats =
3671 device->getAudioPort()->getAudioProfiles().getSupportedFormats();
3672 for (size_t j = 0; j < supportedFormats.size(); j++) {
3673 if (mConfig.getSurroundFormats().count(supportedFormats[j]) != 0) {
3674 formats.insert(supportedFormats[j]);
3675 } else {
3676 for (const auto& pair : mConfig.getSurroundFormats()) {
3677 if (pair.second.count(supportedFormats[j]) != 0) {
3678 formats.insert(pair.first);
3679 break;
3680 }
3681 }
3682 }
3683 }
jiabin81772902018-04-02 17:52:27 -07003684 }
3685 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003686 for (const auto& pair : mConfig.getSurroundFormats()) {
3687 formats.insert(pair.first);
jiabin81772902018-04-02 17:52:27 -07003688 }
3689 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003690 *numSurroundFormats = formats.size();
3691 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3692 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov2563f232018-09-27 14:48:01 -07003693 for (const auto& format: formats) {
jiabin81772902018-04-02 17:52:27 -07003694 if (formatsWritten < formatsMax) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003695 surroundFormats[formatsWritten] = format;
Mikhail Naganov100f0122018-11-29 11:22:16 -08003696 bool formatEnabled = true;
3697 switch (forceUse) {
3698 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
3699 formatEnabled = mManualSurroundFormats.count(format) != 0;
3700 break;
3701 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
3702 formatEnabled = false;
3703 break;
3704 default: // AUTO or ALWAYS => true
3705 break;
jiabin81772902018-04-02 17:52:27 -07003706 }
3707 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3708 }
jiabin81772902018-04-02 17:52:27 -07003709 }
3710 return NO_ERROR;
3711}
3712
3713status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3714{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003715 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003716 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
3717 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003718 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07003719 return BAD_VALUE;
3720 }
3721
Mikhail Naganov100f0122018-11-29 11:22:16 -08003722 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
3723 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003724 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07003725 return INVALID_OPERATION;
3726 }
3727
Mikhail Naganov100f0122018-11-29 11:22:16 -08003728 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07003729 return NO_ERROR;
3730 }
3731
Mikhail Naganov100f0122018-11-29 11:22:16 -08003732 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07003733 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003734 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003735 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003736 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07003737 }
3738 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003739 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003740 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003741 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07003742 }
3743 }
3744
3745 sp<SwAudioOutputDescriptor> outputDesc;
3746 bool profileUpdated = false;
Mikhail Naganov708e0382018-05-30 09:53:04 -07003747 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003748 AUDIO_DEVICE_OUT_HDMI);
3749 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3750 // Simulate reconnection to update enabled surround sound formats.
François Gaffieaca677c2018-05-03 10:47:50 +02003751 String8 address = hdmiOutputDevices[i]->address();
jiabin81772902018-04-02 17:52:27 -07003752 String8 name = hdmiOutputDevices[i]->getName();
3753 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3754 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3755 address.c_str(),
3756 name.c_str());
3757 if (status != NO_ERROR) {
3758 continue;
3759 }
3760 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3761 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3762 address.c_str(),
3763 name.c_str());
3764 profileUpdated |= (status == NO_ERROR);
3765 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003766 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
Mikhail Naganov708e0382018-05-30 09:53:04 -07003767 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003768 AUDIO_DEVICE_IN_HDMI);
3769 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3770 // Simulate reconnection to update enabled surround sound formats.
François Gaffieaca677c2018-05-03 10:47:50 +02003771 String8 address = hdmiInputDevices[i]->address();
jiabin81772902018-04-02 17:52:27 -07003772 String8 name = hdmiInputDevices[i]->getName();
3773 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3774 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3775 address.c_str(),
3776 name.c_str());
3777 if (status != NO_ERROR) {
3778 continue;
3779 }
3780 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3781 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3782 address.c_str(),
3783 name.c_str());
3784 profileUpdated |= (status == NO_ERROR);
3785 }
3786
jiabin81772902018-04-02 17:52:27 -07003787 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003788 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08003789 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07003790 }
3791
3792 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3793}
3794
Eric Laurentf32108e2018-10-04 17:22:04 -07003795void AudioPolicyManager::setAppState(uid_t uid, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003796{
Eric Laurent4eb58f12018-12-07 16:41:02 -08003797 ALOGV("%s(uid:%d, state:%d)", __func__, uid, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003798
Eric Laurenta9f86652018-11-28 17:23:11 -08003799 for (size_t i = 0; i < mInputs.size(); i++) {
3800 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
3801 RecordClientVector clients = inputDesc->clientsList(false /*activeOnly*/);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003802 for (const auto& client : clients) {
3803 if (uid == client->uid()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003804 client->setAppState(state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003805 }
3806 }
3807 }
3808}
3809
jiabin6012f912018-11-02 17:06:30 -07003810bool AudioPolicyManager::isHapticPlaybackSupported()
3811{
3812 for (const auto& hwModule : mHwModules) {
3813 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
3814 for (const auto &outProfile : outputProfiles) {
3815 struct audio_port audioPort;
3816 outProfile->toAudioPort(&audioPort);
3817 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
3818 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
3819 return true;
3820 }
3821 }
3822 }
3823 }
3824 return false;
3825}
3826
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003827status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003828{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003829 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003830
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003831 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003832 if (patchDesc == 0) {
3833 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003834 sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003835 return BAD_VALUE;
3836 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003837 removeAudioPatch(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003838
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003839 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003840 if (swOutputDesc != 0) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003841 status_t status = stopSource(swOutputDesc, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08003842 if (status == NO_ERROR) {
3843 swOutputDesc->stop();
3844 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003845 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3846 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003847 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003848 if (hwOutputDesc != 0) {
3849 // release patch between src device and output device
3850 // close Hwoutput and remove from mHwOutputs
3851 } else {
3852 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3853 }
3854 }
3855 return NO_ERROR;
3856}
3857
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003858sp<SourceClientDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
Eric Laurentd60560a2015-04-10 11:31:20 -07003859 audio_io_handle_t output, routing_strategy strategy)
3860{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003861 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07003862 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003863 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3864 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003865 routing_strategy sourceStrategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003866 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003867 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3868 source = sourceDesc;
3869 break;
3870 }
3871 }
3872 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003873}
3874
Eric Laurente552edb2014-03-10 17:42:56 -07003875// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003876// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003877// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003878uint32_t AudioPolicyManager::nextAudioPortGeneration()
3879{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003880 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003881}
3882
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003883// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3884static const char *kConfigLocationList[] =
3885 {"/odm/etc", "/vendor/etc", "/system/etc"};
3886static const int kConfigLocationListSize =
3887 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3888
3889static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3890 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07003891 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003892 status_t ret;
3893
Petri Gyntherf497f292018-04-17 18:46:10 -07003894 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
3895 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
3896 // A2DP offload supported but disabled: try to use special XML file
3897 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
3898 }
3899 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3900
3901 for (const char* fileName : fileNames) {
3902 for (int i = 0; i < kConfigLocationListSize; i++) {
Petri Gyntherf497f292018-04-17 18:46:10 -07003903 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
3904 "%s/%s", kConfigLocationList[i], fileName);
Mikhail Naganova289aea2018-09-17 15:26:23 -07003905 ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile, &config);
Petri Gyntherf497f292018-04-17 18:46:10 -07003906 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003907 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07003908 return ret;
3909 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003910 }
3911 }
3912 return ret;
3913}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003914
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003915AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
3916 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07003917 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07003918 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003919 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07003920 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003921 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003922 mVolumeCurves(new VolumeCurvesCollection()),
3923 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08003924 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003925 mAudioPortGeneration(1),
3926 mBeaconMuteRefCount(0),
3927 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003928 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003929 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003930 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08003931 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07003932{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003933}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003934
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003935AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
3936 : AudioPolicyManager(clientInterface, false /*forTesting*/)
3937{
3938 loadConfig();
3939 initialize();
3940}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003941
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07003942// This check is to catch any legacy platform updating to Q without having
3943// switched to XML since its deprecation on O.
3944// TODO: after Q release, remove this check and flag as XML is now the only
3945// option and all legacy platform should have transitioned to XML.
3946#ifndef USE_XML_AUDIO_POLICY_CONF
3947#error Audio policy no longer supports legacy .conf configuration format
François Gaffied1ab2bd2015-12-02 18:20:06 +01003948#endif
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07003949
3950void AudioPolicyManager::loadConfig() {
3951 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003952 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003953 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01003954 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003955}
3956
3957status_t AudioPolicyManager::initialize() {
3958 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01003959
3960 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003961 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3962 if (!engineInstance) {
3963 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003964 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003965 }
3966 // Retrieve the Policy Manager Interface
3967 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3968 if (mEngine == NULL) {
3969 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003970 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003971 }
3972 mEngine->setObserver(this);
3973 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003974 if (status != NO_ERROR) {
3975 LOG_FATAL("Policy engine not initialized(err=%d)", status);
3976 return status;
3977 }
François Gaffie2110e042015-03-24 08:41:51 +01003978
Eric Laurent3a4311c2014-03-17 12:00:47 -07003979 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003980 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003981 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3982 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Mikhail Naganovd4120142017-12-06 15:49:22 -08003983 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003984 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08003985 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
3986 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003987 continue;
3988 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08003989 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07003990 // open all output streams needed to access attached devices
3991 // except for direct output streams that are only opened when they are actually
3992 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003993 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003994 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003995 if (!outProfile->canOpenNewIo()) {
3996 ALOGE("Invalid Output profile max open count %u for profile %s",
3997 outProfile->maxOpenCount, outProfile->getTagName().c_str());
3998 continue;
3999 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004000 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004001 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004002 continue;
4003 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004004 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004005 mTtsOutputAvailable = true;
4006 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004007
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004008 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07004009 continue;
4010 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004011 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01004012 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
4013 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07004014 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004015 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07004016 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004017 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07004018 }
Eric Laurentd78f1532014-09-16 16:38:20 -07004019 if ((profileType & outputDeviceTypes) == 0) {
4020 continue;
4021 }
Eric Laurentc75307b2015-03-17 15:29:32 -07004022 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
4023 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07004024 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov708e0382018-05-30 09:53:04 -07004025 const DeviceVector &devicesForType = supportedDevices.getDevicesFromTypeMask(
4026 profileType);
François Gaffieaca677c2018-05-03 10:47:50 +02004027 String8 address = getFirstDeviceAddress(devicesForType);
Eric Laurentd78f1532014-09-16 16:38:20 -07004028 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004029 status_t status = outputDesc->open(nullptr, profileType, address,
4030 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07004031
4032 if (status != NO_ERROR) {
4033 ALOGW("Cannot open output stream for device %08x on hw module %s",
4034 outputDesc->mDevice,
Mikhail Naganovd4120142017-12-06 15:49:22 -08004035 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07004036 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004037 for (const auto& dev : supportedDevices) {
4038 ssize_t index = mAvailableOutputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07004039 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08004040 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004041 mAvailableOutputDevices[index]->attach(hwModule);
Eric Laurentd78f1532014-09-16 16:38:20 -07004042 }
4043 }
4044 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004045 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004046 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07004047 }
4048 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07004049 setOutputDevice(outputDesc,
Eric Laurentfe231122017-11-17 17:48:06 -08004050 profileType,
Eric Laurentc40d9692016-04-13 19:14:13 -07004051 true,
4052 0,
4053 NULL,
Eric Laurentfe231122017-11-17 17:48:06 -08004054 address);
Eric Laurentd78f1532014-09-16 16:38:20 -07004055 }
Eric Laurente552edb2014-03-10 17:42:56 -07004056 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004057 // open input streams needed to access attached devices to validate
4058 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004059 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004060 if (!inProfile->canOpenNewIo()) {
4061 ALOGE("Invalid Input profile max open count %u for profile %s",
4062 inProfile->maxOpenCount, inProfile->getTagName().c_str());
4063 continue;
4064 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004065 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004066 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004067 continue;
4068 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004069 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07004070 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004071 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
4072
Eric Laurentd78f1532014-09-16 16:38:20 -07004073 if ((profileType & inputDeviceTypes) == 0) {
4074 continue;
4075 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08004076 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08004077 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004078
Mikhail Naganov708e0382018-05-30 09:53:04 -07004079 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(profileType);
Eric Laurent53b810e2017-12-10 17:25:10 -08004080 // the inputs vector must be of size >= 1, but we don't want to crash here
François Gaffieaca677c2018-05-03 10:47:50 +02004081 String8 address = getFirstDeviceAddress(inputDevices);
Eric Laurent53b810e2017-12-10 17:25:10 -08004082 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
4083 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
4084
Eric Laurentd78f1532014-09-16 16:38:20 -07004085 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004086 status_t status = inputDesc->open(nullptr,
4087 profileType,
Eric Laurent53b810e2017-12-10 17:25:10 -08004088 address,
Eric Laurentfe231122017-11-17 17:48:06 -08004089 AUDIO_SOURCE_MIC,
4090 AUDIO_INPUT_FLAG_NONE,
4091 &input);
Eric Laurentd78f1532014-09-16 16:38:20 -07004092
4093 if (status == NO_ERROR) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004094 for (const auto& dev : inProfile->getSupportedDevices()) {
4095 ssize_t index = mAvailableInputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07004096 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07004097 if (index >= 0) {
4098 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
4099 if (!devDesc->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004100 devDesc->attach(hwModule);
Eric Laurent83efe1c2017-07-09 16:51:08 -07004101 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07004102 }
Eric Laurentd78f1532014-09-16 16:38:20 -07004103 }
4104 }
Eric Laurentfe231122017-11-17 17:48:06 -08004105 inputDesc->close();
Eric Laurentd78f1532014-09-16 16:38:20 -07004106 } else {
4107 ALOGW("Cannot open input stream for device %08x on hw module %s",
Eric Laurentfe231122017-11-17 17:48:06 -08004108 profileType,
Mikhail Naganovd4120142017-12-06 15:49:22 -08004109 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07004110 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004111 }
4112 }
4113 // make sure all attached devices have been allocated a unique ID
4114 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004115 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004116 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004117 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
4118 continue;
4119 }
François Gaffie2110e042015-03-24 08:41:51 +01004120 // The device is now validated and can be appended to the available devices of the engine
4121 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
4122 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004123 i++;
4124 }
4125 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004126 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01004127 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004128 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
4129 continue;
4130 }
François Gaffie2110e042015-03-24 08:41:51 +01004131 // The device is now validated and can be appended to the available devices of the engine
4132 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
4133 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004134 i++;
4135 }
4136 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004137 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01004138 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004139 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004140 }
jiabin9ff780e2018-03-19 18:19:52 -07004141 // If microphones address is empty, set it according to device type
4142 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
François Gaffieaca677c2018-05-03 10:47:50 +02004143 if (mAvailableInputDevices[i]->address().isEmpty()) {
jiabin9ff780e2018-03-19 18:19:52 -07004144 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
François Gaffieaca677c2018-05-03 10:47:50 +02004145 mAvailableInputDevices[i]->address() = String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07004146 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
François Gaffieaca677c2018-05-03 10:47:50 +02004147 mAvailableInputDevices[i]->address() = String8(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07004148 }
4149 }
4150 }
Eric Laurente552edb2014-03-10 17:42:56 -07004151
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004152 if (mPrimaryOutput == 0) {
4153 ALOGE("Failed to open primary output");
4154 status = NO_INIT;
4155 }
Eric Laurente552edb2014-03-10 17:42:56 -07004156
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09004157 // Silence ALOGV statements
4158 property_set("log.tag." LOG_TAG, "D");
4159
Eric Laurente552edb2014-03-10 17:42:56 -07004160 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004161 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004162}
4163
Eric Laurente0720872014-03-11 09:30:41 -07004164AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004165{
Eric Laurente552edb2014-03-10 17:42:56 -07004166 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004167 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004168 }
4169 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004170 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004171 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004172 mAvailableOutputDevices.clear();
4173 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004174 mOutputs.clear();
4175 mInputs.clear();
4176 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004177 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004178 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004179}
4180
Eric Laurente0720872014-03-11 09:30:41 -07004181status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004182{
Eric Laurent87ffa392015-05-22 10:32:38 -07004183 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004184}
4185
Eric Laurente552edb2014-03-10 17:42:56 -07004186// ---
4187
Eric Laurent98e38192018-02-15 18:31:53 -08004188void AudioPolicyManager::addOutput(audio_io_handle_t output,
4189 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004190{
Eric Laurent1c333e22014-05-20 10:48:17 -07004191 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08004192 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004193 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004194 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004195 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004196}
4197
François Gaffie53615e22015-03-19 09:24:12 +01004198void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4199{
4200 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004201 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004202}
4203
Eric Laurent98e38192018-02-15 18:31:53 -08004204void AudioPolicyManager::addInput(audio_io_handle_t input,
4205 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004206{
Eric Laurent1c333e22014-05-20 10:48:17 -07004207 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004208 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004209}
Eric Laurente552edb2014-03-10 17:42:56 -07004210
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004211void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08004212 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004213 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004214 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08004215 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004216 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08004217 if (devDesc != 0) {
4218 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
4219 desc->mIoHandle, address.string());
4220 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004221 }
4222}
4223
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004224status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004225 audio_policy_dev_state_t state,
4226 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004227 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07004228{
François Gaffie53615e22015-03-19 09:24:12 +01004229 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07004230 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004231
4232 if (audio_device_is_digital(device)) {
4233 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004234 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004235 }
Eric Laurente552edb2014-03-10 17:42:56 -07004236
Eric Laurent3b73df72014-03-11 09:06:29 -07004237 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004238 // first list already open outputs that can be routed to this device
4239 for (size_t i = 0; i < mOutputs.size(); i++) {
4240 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07004241 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004242 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004243 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
4244 outputs.add(mOutputs.keyAt(i));
4245 } else {
4246 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08004247 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004248 }
Eric Laurente552edb2014-03-10 17:42:56 -07004249 }
4250 }
4251 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004252 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004253 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004254 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4255 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004256 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004257 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004258 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004259 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004260 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4261 j, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004262 }
Eric Laurente552edb2014-03-10 17:42:56 -07004263 }
4264 }
4265 }
4266
Eric Laurent7b279bb2015-12-14 10:18:23 -08004267 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004268
Eric Laurente552edb2014-03-10 17:42:56 -07004269 if (profiles.isEmpty() && outputs.isEmpty()) {
4270 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4271 return BAD_VALUE;
4272 }
4273
4274 // open outputs for matching profiles if needed. Direct outputs are also opened to
4275 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4276 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004277 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004278
4279 // nothing to do if one output is already opened for this profile
4280 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004281 for (j = 0; j < outputs.size(); j++) {
4282 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004283 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004284 // matching profile: save the sample rates, format and channel masks supported
4285 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07004286 if (audio_device_is_digital(device)) {
4287 devDesc->importAudioPort(profile);
4288 }
Eric Laurente552edb2014-03-10 17:42:56 -07004289 break;
4290 }
4291 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004292 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004293 continue;
4294 }
4295
Eric Laurent3974e3b2017-12-07 17:58:43 -08004296 if (!profile->canOpenNewIo()) {
4297 ALOGW("Max Output number %u already opened for this profile %s",
4298 profile->maxOpenCount, profile->getTagName().c_str());
4299 continue;
4300 }
4301
Eric Laurent83efe1c2017-07-09 16:51:08 -07004302 ALOGV("opening output for device %08x with params %s profile %p name %s",
4303 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004304 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004305 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004306 status_t status = desc->open(nullptr, device, address,
4307 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004308
Eric Laurentfe231122017-11-17 17:48:06 -08004309 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004310 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004311 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004312 char *param = audio_device_address_to_parameter(device, address);
4313 mpClientInterface->setParameters(output, String8(param));
4314 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004315 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08004316 updateAudioProfiles(devDesc, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004317 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004318 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004319 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004320 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004321 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004322 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004323 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004324 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4325 profile->pickAudioProfile(
4326 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004327 config.offload_info.sample_rate = config.sample_rate;
4328 config.offload_info.channel_mask = config.channel_mask;
4329 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004330
4331 status_t status = desc->open(&config, device, address, AUDIO_STREAM_DEFAULT,
4332 AUDIO_OUTPUT_FLAG_NONE, &output);
4333 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004334 output = AUDIO_IO_HANDLE_NONE;
4335 }
Eric Laurentd4692962014-05-05 18:13:44 -07004336 }
4337
Eric Laurentcf2c0212014-07-25 16:20:43 -07004338 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004339 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01004340 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004341 sp<AudioPolicyMix> policyMix;
4342 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004343 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
4344 address.string());
4345 }
François Gaffie036e1e92015-03-19 10:16:24 +01004346 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07004347 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01004348
Eric Laurent87ffa392015-05-22 10:32:38 -07004349 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4350 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004351 // no duplicated output for direct outputs and
4352 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004353 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004354
Eric Laurentd4692962014-05-05 18:13:44 -07004355 //TODO: configure audio effect output stage here
4356
4357 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004358 sp<SwAudioOutputDescriptor> dupOutputDesc =
4359 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4360 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4361 &duplicatedOutput);
4362 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004363 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004364 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004365 } else {
4366 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004367 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004368 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004369 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004370 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004371 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004372 }
Eric Laurente552edb2014-03-10 17:42:56 -07004373 }
4374 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004375 } else {
4376 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004377 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004378 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004379 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004380 profiles.removeAt(profile_index);
4381 profile_index--;
4382 } else {
4383 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004384 // Load digital format info only for digital devices
4385 if (audio_device_is_digital(device)) {
4386 devDesc->importAudioPort(profile);
4387 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004388
François Gaffie53615e22015-03-19 09:24:12 +01004389 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004390 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4391 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004392 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004393 NULL/*patch handle*/, address.string());
4394 }
Eric Laurente552edb2014-03-10 17:42:56 -07004395 ALOGV("checkOutputsForDevice(): adding output %d", output);
4396 }
4397 }
4398
4399 if (profiles.isEmpty()) {
4400 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4401 return BAD_VALUE;
4402 }
Eric Laurentd4692962014-05-05 18:13:44 -07004403 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004404 // check if one opened output is not needed any more after disconnecting one device
4405 for (size_t i = 0; i < mOutputs.size(); i++) {
4406 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004407 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004408 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004409 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004410 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004411 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004412 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004413 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4414 mOutputs.keyAt(i));
4415 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004416 }
Eric Laurente552edb2014-03-10 17:42:56 -07004417 }
4418 }
Eric Laurentd4692962014-05-05 18:13:44 -07004419 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004420 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004421 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4422 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004423 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004424 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004425 "clearing direct output profile %zu on module %s",
4426 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004427 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004428 }
4429 }
4430 }
4431 }
4432 return NO_ERROR;
4433}
4434
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004435status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004436 audio_policy_dev_state_t state,
4437 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004438 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004439{
Paul McLean9080a4c2015-06-18 08:24:02 -07004440 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004441 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004442
4443 if (audio_device_is_digital(device)) {
4444 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004445 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004446 }
4447
Eric Laurentd4692962014-05-05 18:13:44 -07004448 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4449 // first list already open inputs that can be routed to this device
4450 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4451 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004452 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004453 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4454 inputs.add(mInputs.keyAt(input_index));
4455 }
4456 }
4457
4458 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004459 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004460 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004461 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004462 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004463 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004464 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004465
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004466 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004467 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004468 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004469 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004470 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4471 profile_index, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004472 }
Eric Laurentd4692962014-05-05 18:13:44 -07004473 }
4474 }
4475 }
4476
4477 if (profiles.isEmpty() && inputs.isEmpty()) {
4478 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4479 return BAD_VALUE;
4480 }
4481
4482 // open inputs for matching profiles if needed. Direct inputs are also opened to
4483 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4484 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4485
Eric Laurent1c333e22014-05-20 10:48:17 -07004486 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004487
Eric Laurentd4692962014-05-05 18:13:44 -07004488 // nothing to do if one input is already opened for this profile
4489 size_t input_index;
4490 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4491 desc = mInputs.valueAt(input_index);
4492 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004493 if (audio_device_is_digital(device)) {
4494 devDesc->importAudioPort(profile);
4495 }
Eric Laurentd4692962014-05-05 18:13:44 -07004496 break;
4497 }
4498 }
4499 if (input_index != mInputs.size()) {
4500 continue;
4501 }
4502
Eric Laurent3974e3b2017-12-07 17:58:43 -08004503 if (!profile->canOpenNewIo()) {
4504 ALOGW("Max Input number %u already opened for this profile %s",
4505 profile->maxOpenCount, profile->getTagName().c_str());
4506 continue;
4507 }
4508
Eric Laurentfe231122017-11-17 17:48:06 -08004509 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004510 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004511 status_t status = desc->open(nullptr,
4512 device,
4513 address,
4514 AUDIO_SOURCE_MIC,
4515 AUDIO_INPUT_FLAG_NONE,
4516 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004517
Eric Laurentcf2c0212014-07-25 16:20:43 -07004518 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004519 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004520 char *param = audio_device_address_to_parameter(device, address);
4521 mpClientInterface->setParameters(input, String8(param));
4522 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004523 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08004524 updateAudioProfiles(devDesc, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004525 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004526 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004527 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004528 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004529 }
4530
4531 if (input != 0) {
4532 addInput(input, desc);
4533 }
4534 } // endif input != 0
4535
Eric Laurentcf2c0212014-07-25 16:20:43 -07004536 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004537 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004538 profiles.removeAt(profile_index);
4539 profile_index--;
4540 } else {
4541 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004542 if (audio_device_is_digital(device)) {
4543 devDesc->importAudioPort(profile);
4544 }
Eric Laurentd4692962014-05-05 18:13:44 -07004545 ALOGV("checkInputsForDevice(): adding input %d", input);
4546 }
4547 } // end scan profiles
4548
4549 if (profiles.isEmpty()) {
4550 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4551 return BAD_VALUE;
4552 }
4553 } else {
4554 // Disconnect
4555 // check if one opened input is not needed any more after disconnecting one device
4556 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4557 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004558 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004559 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4560 mInputs.keyAt(input_index));
4561 inputs.add(mInputs.keyAt(input_index));
4562 }
4563 }
4564 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004565 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004566 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004567 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004568 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004569 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004570 if (profile->supportDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004571 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4572 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004573 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004574 }
4575 }
4576 }
4577 } // end disconnect
4578
4579 return NO_ERROR;
4580}
4581
4582
Eric Laurente0720872014-03-11 09:30:41 -07004583void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004584{
4585 ALOGV("closeOutput(%d)", output);
4586
Eric Laurentc75307b2015-03-17 15:29:32 -07004587 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004588 if (outputDesc == NULL) {
4589 ALOGW("closeOutput() unknown output %d", output);
4590 return;
4591 }
François Gaffie036e1e92015-03-19 10:16:24 +01004592 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004593
Eric Laurente552edb2014-03-10 17:42:56 -07004594 // look for duplicated outputs connected to the output being removed.
4595 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004596 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004597 if (dupOutputDesc->isDuplicated() &&
4598 (dupOutputDesc->mOutput1 == outputDesc ||
4599 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004600 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004601 if (dupOutputDesc->mOutput1 == outputDesc) {
4602 outputDesc2 = dupOutputDesc->mOutput2;
4603 } else {
4604 outputDesc2 = dupOutputDesc->mOutput1;
4605 }
4606 // As all active tracks on duplicated output will be deleted,
4607 // and as they were also referenced on the other output, the reference
4608 // count for their stream type must be adjusted accordingly on
4609 // the other output.
Andy Hungaf036da2018-09-21 10:46:21 -07004610 const bool wasActive = outputDesc2->isActive();
4611 for (const auto &clientPair : dupOutputDesc->getActiveClients()) {
4612 outputDesc2->changeStreamActiveCount(clientPair.first, -clientPair.second);
Eric Laurente552edb2014-03-10 17:42:56 -07004613 }
Eric Laurent733ce942017-12-07 12:18:25 -08004614 // stop() will be a no op if the output is still active but is needed in case all
4615 // active streams refcounts where cleared above
4616 if (wasActive) {
4617 outputDesc2->stop();
4618 }
Eric Laurente552edb2014-03-10 17:42:56 -07004619 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4620 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4621
4622 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004623 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004624 }
4625 }
4626
Eric Laurent05b90f82014-08-27 15:32:29 -07004627 nextAudioPortGeneration();
4628
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004629 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004630 if (index >= 0) {
4631 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004632 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004633 mAudioPatches.removeItemsAt(index);
4634 mpClientInterface->onAudioPatchListUpdate();
4635 }
4636
Eric Laurentfe231122017-11-17 17:48:06 -08004637 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004638
François Gaffie53615e22015-03-19 09:24:12 +01004639 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004640 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10004641
4642 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
4643 // no direct outputs are open.
Mikhail Naganov100f0122018-11-29 11:22:16 -08004644 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Dean Wheatley3023b382018-08-09 07:42:40 +10004645 bool directOutputOpen = false;
4646 for (size_t i = 0; i < mOutputs.size(); i++) {
4647 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
4648 directOutputOpen = true;
4649 break;
4650 }
4651 }
4652 if (!directOutputOpen) {
4653 ALOGV("no direct outputs open, reset MSD patch");
4654 setMsdPatch();
4655 }
4656 }
Eric Laurent05b90f82014-08-27 15:32:29 -07004657}
4658
4659void AudioPolicyManager::closeInput(audio_io_handle_t input)
4660{
4661 ALOGV("closeInput(%d)", input);
4662
4663 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4664 if (inputDesc == NULL) {
4665 ALOGW("closeInput() unknown input %d", input);
4666 return;
4667 }
4668
Eric Laurent6a94d692014-05-20 11:18:06 -07004669 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004670
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004671 audio_devices_t device = inputDesc->mDevice;
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004672 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004673 if (index >= 0) {
4674 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004675 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004676 mAudioPatches.removeItemsAt(index);
4677 mpClientInterface->onAudioPatchListUpdate();
4678 }
4679
Eric Laurentfe231122017-11-17 17:48:06 -08004680 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004681 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004682
4683 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
4684 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
4685 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
4686 SoundTrigger::setCaptureState(false);
4687 }
Eric Laurente552edb2014-03-10 17:42:56 -07004688}
4689
Eric Laurentc75307b2015-03-17 15:29:32 -07004690SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4691 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004692 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004693{
4694 SortedVector<audio_io_handle_t> outputs;
4695
4696 ALOGVV("getOutputsForDevice() device %04x", device);
4697 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004698 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004699 i, openOutputs.valueAt(i)->isDuplicated(),
4700 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004701 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4702 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4703 outputs.add(openOutputs.keyAt(i));
4704 }
4705 }
4706 return outputs;
4707}
4708
Mikhail Naganov37977152018-07-11 15:54:44 -07004709void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
4710{
4711 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
4712 // output is suspended before any tracks are moved to it
4713 checkA2dpSuspend();
4714 checkOutputForAllStrategies();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004715 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07004716 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00004717 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004718 setMsdPatch();
4719 }
Mikhail Naganov37977152018-07-11 15:54:44 -07004720}
4721
Eric Laurente0720872014-03-11 09:30:41 -07004722void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004723{
4724 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4725 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4726 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4727 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4728
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004729 // also take into account external policy-related changes: add all outputs which are
4730 // associated with policies in the "before" and "after" output vectors
4731 ALOGVV("checkOutputForStrategy(): policy related outputs");
4732 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004733 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004734 if (desc != 0 && desc->mPolicyMix != NULL) {
4735 srcOutputs.add(desc->mIoHandle);
4736 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4737 }
4738 }
4739 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004740 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004741 if (desc != 0 && desc->mPolicyMix != NULL) {
4742 dstOutputs.add(desc->mIoHandle);
4743 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4744 }
4745 }
4746
Mikhail Naganov9de8bd12018-07-23 16:41:31 -07004747 if (srcOutputs != dstOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004748 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4749 // audio from invalidated tracks will be rendered when unmuting
4750 uint32_t maxLatency = 0;
4751 for (audio_io_handle_t srcOut : srcOutputs) {
4752 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4753 if (desc != 0 && maxLatency < desc->latency()) {
4754 maxLatency = desc->latency();
4755 }
4756 }
Eric Laurente552edb2014-03-10 17:42:56 -07004757 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4758 strategy, srcOutputs[0], dstOutputs[0]);
4759 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004760 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004761 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4762 if (desc != 0 && isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004763 setStrategyMute(strategy, true, desc);
Eric Laurentac3a6902018-05-11 16:39:10 -07004764 setStrategyMute(strategy, false, desc, maxLatency * LATENCY_MUTE_FACTOR, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004765 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004766 sp<SourceClientDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004767 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004768 if (source != 0){
4769 connectAudioSource(source);
4770 }
Eric Laurente552edb2014-03-10 17:42:56 -07004771 }
4772
4773 // Move effects associated to this strategy from previous output to new output
4774 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004775 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004776 }
4777 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004778 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004779 if (getStrategy((audio_stream_type_t)i) == strategy) {
4780 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004781 }
4782 }
4783 }
4784}
4785
Eric Laurente0720872014-03-11 09:30:41 -07004786void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004787{
François Gaffie2110e042015-03-24 08:41:51 +01004788 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004789 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004790 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004791 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004792 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004793 checkOutputForStrategy(STRATEGY_SONIFICATION);
4794 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004795 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004796 checkOutputForStrategy(STRATEGY_MEDIA);
4797 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004798 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004799}
4800
Eric Laurente0720872014-03-11 09:30:41 -07004801void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004802{
François Gaffie53615e22015-03-19 09:24:12 +01004803 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004804 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004805 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004806 return;
4807 }
4808
Eric Laurent3a4311c2014-03-17 12:00:47 -07004809 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004810 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4811 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4812 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004813
4814 // if suspended, restore A2DP output if:
4815 // ((SCO device is NOT connected) ||
4816 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4817 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004818 //
Eric Laurentf732e072016-08-03 19:30:28 -07004819 // if not suspended, suspend A2DP output if:
4820 // (SCO device is connected) &&
4821 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4822 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004823 //
4824 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004825 if (!isScoConnected ||
4826 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4827 AUDIO_POLICY_FORCE_BT_SCO) &&
4828 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4829 AUDIO_POLICY_FORCE_BT_SCO) &&
4830 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004831 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004832
4833 mpClientInterface->restoreOutput(a2dpOutput);
4834 mA2dpSuspended = false;
4835 }
4836 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004837 if (isScoConnected &&
4838 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4839 AUDIO_POLICY_FORCE_BT_SCO) ||
4840 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4841 AUDIO_POLICY_FORCE_BT_SCO) ||
4842 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004843 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004844
4845 mpClientInterface->suspendOutput(a2dpOutput);
4846 mA2dpSuspended = true;
4847 }
4848 }
4849}
4850
Eric Laurent97ac8712018-07-27 18:59:02 -07004851template <class IoDescriptor, class Filter>
4852sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4853 IoDescriptor& desc, Filter filter, bool& active, const DeviceVector& devices)
4854{
4855 auto activeClients = desc->clientsList(true /*activeOnly*/);
4856 auto activeClientsWithRoute =
4857 desc->clientsList(true /*activeOnly*/, filter, true /*preferredDevice*/);
4858 active = activeClients.size() > 0;
4859 if (active && activeClients.size() == activeClientsWithRoute.size()) {
4860 return devices.getDeviceFromId(activeClientsWithRoute[0]->preferredDeviceId());
4861 }
4862 return nullptr;
4863}
4864
4865template <class IoCollection, class Filter>
4866sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4867 IoCollection& ioCollection, Filter filter, const DeviceVector& devices)
4868{
4869 sp<DeviceDescriptor> device;
4870 for (size_t i = 0; i < ioCollection.size(); i++) {
4871 auto desc = ioCollection.valueAt(i);
4872 bool active;
4873 sp<DeviceDescriptor> curDevice = findPreferredDevice(desc, filter, active, devices);
4874 if (active && curDevice == nullptr) {
4875 return nullptr;
4876 } else if (curDevice != nullptr) {
4877 device = curDevice;
4878 }
4879 }
4880 return device;
4881}
4882
Eric Laurentc75307b2015-03-17 15:29:32 -07004883audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4884 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004885{
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004886 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004887 if (index >= 0) {
4888 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4889 if (patchDesc->mUid != mUidCached) {
4890 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004891 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004892 return outputDesc->device();
4893 }
4894 }
4895
Eric Laurent97ac8712018-07-27 18:59:02 -07004896 // Honor explicit routing requests only if no client using default routing is active on this
4897 // input: a specific app can not force routing for other apps by setting a preferred device.
4898 bool active; // unused
4899 sp<DeviceDescriptor> deviceDesc =
4900 findPreferredDevice(outputDesc, STRATEGY_NONE, active, mAvailableOutputDevices);
4901 if (deviceDesc != nullptr) {
4902 return deviceDesc->type();
Eric Laurentf3a5a602018-05-22 18:42:55 -07004903 }
4904
Eric Laurente552edb2014-03-10 17:42:56 -07004905 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004906 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004907 // use device for strategy enforced audible
4908 // 2: we are in call or the strategy phone is active on the output:
4909 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004910 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004911 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004912 // 4: the strategy for enforced audible is active but not enforced on the output:
4913 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004914 // 5: the strategy accessibility is active on the output:
4915 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004916 // 6: the strategy "respectful" sonification is active on the output:
4917 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004918 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004919 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004920 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004921 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004922 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004923 // use device for strategy t-t-s
Eric Laurent484e9272018-06-07 17:29:23 -07004924
4925 // FIXME: extend use of isStrategyActiveOnSameModule() to all strategies
4926 // with a refined rule considering mutually exclusive devices (using same backend)
4927 // as opposed to all streams on the same audio HAL module.
Eric Laurent97ac8712018-07-27 18:59:02 -07004928 audio_devices_t device = AUDIO_DEVICE_NONE;
François Gaffiead3183e2015-03-18 16:55:35 +01004929 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004930 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004931 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4932 } else if (isInCall() ||
Eric Laurent484e9272018-06-07 17:29:23 -07004933 isStrategyActiveOnSameModule(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004934 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
Yung Ti Su3e7eb5e2018-06-13 11:48:42 +08004935 } else if (isStrategyActiveOnSameModule(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004936 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004937 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
4938 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004939 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4940 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004941 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004942 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004943 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004944 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004945 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004946 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004947 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004948 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004949 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004950 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004951 }
4952
Eric Laurent1c333e22014-05-20 10:48:17 -07004953 ALOGV("getNewOutputDevice() selected device %x", device);
4954 return device;
4955}
4956
Eric Laurentfb66dd92016-01-28 18:32:03 -08004957audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004958{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004959 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004960
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004961 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004962 if (index >= 0) {
4963 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4964 if (patchDesc->mUid != mUidCached) {
4965 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004966 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004967 return inputDesc->mDevice;
4968 }
4969 }
4970
Eric Laurent97ac8712018-07-27 18:59:02 -07004971 // Honor explicit routing requests only if no client using default routing is active on this
4972 // input: a specific app can not force routing for other apps by setting a preferred device.
4973 bool active;
4974 sp<DeviceDescriptor> deviceDesc =
4975 findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
4976 if (deviceDesc != nullptr) {
4977 return deviceDesc->type();
4978 }
4979
Eric Laurentdc95a252018-04-12 12:46:56 -07004980 // If we are not in call and no client is active on this input, this methods returns
4981 // AUDIO_DEVICE_NONE, causing the patch on the input stream to be released.
Eric Laurent4eb58f12018-12-07 16:41:02 -08004982 audio_source_t source = inputDesc->source();
Eric Laurentdc95a252018-04-12 12:46:56 -07004983 if (source == AUDIO_SOURCE_DEFAULT && isInCall()) {
4984 source = AUDIO_SOURCE_VOICE_COMMUNICATION;
4985 }
4986 if (source != AUDIO_SOURCE_DEFAULT) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08004987 device = getDeviceAndMixForInputSource(source);
4988 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004989
Eric Laurente552edb2014-03-10 17:42:56 -07004990 return device;
4991}
4992
Eric Laurent794fde22016-03-11 09:50:45 -08004993bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4994 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004995 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004996}
4997
Eric Laurente0720872014-03-11 09:30:41 -07004998uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004999 return (uint32_t)getStrategy(stream);
5000}
5001
Eric Laurente0720872014-03-11 09:30:41 -07005002audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005003 // By checking the range of stream before calling getStrategy, we avoid
5004 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
5005 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08005006 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005007 return AUDIO_DEVICE_NONE;
5008 }
Eric Laurentb0688d62018-08-14 15:49:18 -07005009 audio_devices_t activeDevices = AUDIO_DEVICE_NONE;
Eric Laurent28d09f02016-03-08 10:43:05 -08005010 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08005011 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
5012 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08005013 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07005014 }
Eric Laurent794fde22016-03-11 09:50:45 -08005015 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08005016 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07005017 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Eric Laurentb0688d62018-08-14 15:49:18 -07005018 devices |= curDevices;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005019 for (audio_io_handle_t output : getOutputsForDevice(curDevices, mOutputs)) {
5020 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08005021 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurentb0688d62018-08-14 15:49:18 -07005022 activeDevices |= outputDesc->device();
Eric Laurent28d09f02016-03-08 10:43:05 -08005023 }
5024 }
Eric Laurente552edb2014-03-10 17:42:56 -07005025 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005026
Eric Laurentb0688d62018-08-14 15:49:18 -07005027 // Favor devices selected on active streams if any to report correct device in case of
5028 // explicit device selection
5029 if (activeDevices != AUDIO_DEVICE_NONE) {
5030 devices = activeDevices;
5031 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005032 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
5033 and doesn't really need to.*/
5034 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
5035 devices |= AUDIO_DEVICE_OUT_SPEAKER;
5036 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
5037 }
Eric Laurente552edb2014-03-10 17:42:56 -07005038 return devices;
5039}
5040
François Gaffie2110e042015-03-24 08:41:51 +01005041routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
5042{
Eric Laurent223fd5c2014-11-11 13:43:36 -08005043 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01005044 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005045}
5046
Eric Laurent97ac8712018-07-27 18:59:02 -07005047routing_strategy AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005048 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005049 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
Eric Laurent97ac8712018-07-27 18:59:02 -07005050 return STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005051 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005052 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
Eric Laurent97ac8712018-07-27 18:59:02 -07005053 return STRATEGY_ENFORCED_AUDIBLE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005054 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005055 // usage to strategy mapping
Eric Laurent97ac8712018-07-27 18:59:02 -07005056 return mEngine->getStrategyForUsage(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005057}
5058
Eric Laurente0720872014-03-11 09:30:41 -07005059void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005060 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005061 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07005062 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
5063 updateDevicesAndOutputs();
5064 break;
5065 default:
5066 break;
5067 }
5068}
5069
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005070uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07005071
5072 // skip beacon mute management if a dedicated TTS output is available
5073 if (mTtsOutputAvailable) {
5074 return 0;
5075 }
5076
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005077 switch(event) {
5078 case STARTING_OUTPUT:
5079 mBeaconMuteRefCount++;
5080 break;
5081 case STOPPING_OUTPUT:
5082 if (mBeaconMuteRefCount > 0) {
5083 mBeaconMuteRefCount--;
5084 }
5085 break;
5086 case STARTING_BEACON:
5087 mBeaconPlayingRefCount++;
5088 break;
5089 case STOPPING_BEACON:
5090 if (mBeaconPlayingRefCount > 0) {
5091 mBeaconPlayingRefCount--;
5092 }
5093 break;
5094 }
5095
5096 if (mBeaconMuteRefCount > 0) {
5097 // any playback causes beacon to be muted
5098 return setBeaconMute(true);
5099 } else {
5100 // no other playback: unmute when beacon starts playing, mute when it stops
5101 return setBeaconMute(mBeaconPlayingRefCount == 0);
5102 }
5103}
5104
5105uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5106 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5107 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5108 // keep track of muted state to avoid repeating mute/unmute operations
5109 if (mBeaconMuted != mute) {
5110 // mute/unmute AUDIO_STREAM_TTS on all outputs
5111 ALOGV("\t muting %d", mute);
5112 uint32_t maxLatency = 0;
5113 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005114 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005115 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07005116 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005117 0 /*delay*/, AUDIO_DEVICE_NONE);
5118 const uint32_t latency = desc->latency() * 2;
5119 if (latency > maxLatency) {
5120 maxLatency = latency;
5121 }
5122 }
5123 mBeaconMuted = mute;
5124 return maxLatency;
5125 }
5126 return 0;
5127}
5128
Eric Laurente0720872014-03-11 09:30:41 -07005129audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01005130 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005131{
Eric Laurent97ac8712018-07-27 18:59:02 -07005132 // Honor explicit routing requests only if all active clients have a preferred route in which
5133 // case the last active client route is used
5134 sp<DeviceDescriptor> deviceDesc = findPreferredDevice(mOutputs, strategy, mAvailableOutputDevices);
5135 if (deviceDesc != nullptr) {
5136 return deviceDesc->type();
Paul McLeanaa981192015-03-21 09:55:15 -07005137 }
5138
Eric Laurente552edb2014-03-10 17:42:56 -07005139 if (fromCache) {
5140 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
5141 strategy, mDeviceForStrategy[strategy]);
5142 return mDeviceForStrategy[strategy];
5143 }
François Gaffie2110e042015-03-24 08:41:51 +01005144 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07005145}
5146
Eric Laurente0720872014-03-11 09:30:41 -07005147void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005148{
5149 for (int i = 0; i < NUM_STRATEGIES; i++) {
5150 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
5151 }
5152 mPreviousOutputs = mOutputs;
5153}
5154
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005155uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005156 audio_devices_t prevDevice,
5157 uint32_t delayMs)
5158{
5159 // mute/unmute strategies using an incompatible device combination
5160 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5161 // if unmuting, unmute only after the specified delay
5162 if (outputDesc->isDuplicated()) {
5163 return 0;
5164 }
5165
5166 uint32_t muteWaitMs = 0;
5167 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07005168 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005169
5170 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
5171 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07005172 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07005173 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
5174 bool doMute = false;
5175
5176 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
5177 doMute = true;
5178 outputDesc->mStrategyMutedByDevice[i] = true;
5179 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
5180 doMute = true;
5181 outputDesc->mStrategyMutedByDevice[i] = false;
5182 }
Eric Laurent99401132014-05-07 19:48:15 -07005183 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005184 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005185 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005186 // skip output if it does not share any device with current output
5187 if ((desc->supportedDevices() & outputDesc->supportedDevices())
5188 == AUDIO_DEVICE_NONE) {
5189 continue;
5190 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005191 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07005192 mute ? "muting" : "unmuting", i, curDevice);
5193 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005194 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005195 if (mute) {
5196 // FIXME: should not need to double latency if volume could be applied
5197 // immediately by the audioflinger mixer. We must account for the delay
5198 // between now and the next time the audioflinger thread for this output
5199 // will process a buffer (which corresponds to one buffer size,
5200 // usually 1/2 or 1/4 of the latency).
5201 if (muteWaitMs < desc->latency() * 2) {
5202 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005203 }
5204 }
5205 }
5206 }
5207 }
5208 }
5209
Eric Laurent99401132014-05-07 19:48:15 -07005210 // temporary mute output if device selection changes to avoid volume bursts due to
5211 // different per device volumes
5212 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005213 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5214 // temporary mute duration is conservatively set to 4 times the reported latency
5215 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5216 if (muteWaitMs < tempMuteWaitMs) {
5217 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005218 }
Eric Laurentdc462862016-07-19 12:29:53 -07005219
Eric Laurent99401132014-05-07 19:48:15 -07005220 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005221 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005222 // make sure that we do not start the temporary mute period too early in case of
5223 // delayed device change
5224 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005225 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07005226 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07005227 }
5228 }
5229 }
5230
Eric Laurente552edb2014-03-10 17:42:56 -07005231 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5232 if (muteWaitMs > delayMs) {
5233 muteWaitMs -= delayMs;
5234 usleep(muteWaitMs * 1000);
5235 return muteWaitMs;
5236 }
5237 return 0;
5238}
5239
Eric Laurentc75307b2015-03-17 15:29:32 -07005240uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005241 audio_devices_t device,
5242 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07005243 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005244 audio_patch_handle_t *patchHandle,
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005245 const char *address,
5246 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005247{
Eric Laurentc75307b2015-03-17 15:29:32 -07005248 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005249 AudioParameter param;
5250 uint32_t muteWaitMs;
5251
5252 if (outputDesc->isDuplicated()) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005253 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs,
5254 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
5255 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs,
5256 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005257 return muteWaitMs;
5258 }
5259 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5260 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07005261 if ((device != AUDIO_DEVICE_NONE) &&
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005262 ((device & outputDesc->supportedDevices()) == AUDIO_DEVICE_NONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005263 return 0;
5264 }
5265
5266 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07005267 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07005268
5269 audio_devices_t prevDevice = outputDesc->mDevice;
5270
Paul McLeanaa981192015-03-21 09:55:15 -07005271 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005272
5273 if (device != AUDIO_DEVICE_NONE) {
5274 outputDesc->mDevice = device;
5275 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005276
5277 // if the outputs are not materially active, there is no need to mute.
5278 if (requiresMuteCheck) {
5279 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
5280 } else {
5281 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5282 muteWaitMs = 0;
5283 }
Eric Laurente552edb2014-03-10 17:42:56 -07005284
5285 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005286 // the requested device is AUDIO_DEVICE_NONE
5287 // OR the requested device is the same as current device
5288 // AND force is not specified
5289 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07005290 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07005291 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
5292 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005293 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005294 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005295 return muteWaitMs;
5296 }
5297
5298 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07005299
Eric Laurente552edb2014-03-10 17:42:56 -07005300 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07005301 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005302 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005303 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07005304 DeviceVector deviceList;
5305 if ((address == NULL) || (strlen(address) == 0)) {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005306 deviceList = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurentc40d9692016-04-13 19:14:13 -07005307 } else {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005308 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
5309 device, String8(address));
5310 if (deviceDesc) deviceList.add(deviceDesc);
Eric Laurentc40d9692016-04-13 19:14:13 -07005311 }
5312
Eric Laurent1c333e22014-05-20 10:48:17 -07005313 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005314 PatchBuilder patchBuilder;
5315 patchBuilder.addSource(outputDesc);
François Gaffieaca677c2018-05-03 10:47:50 +02005316 ALOG_ASSERT(deviceList.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
5317 for (const auto &device : deviceList) {
5318 patchBuilder.addSink(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005319 }
Mikhail Naganovdc769682018-05-04 15:34:08 -07005320 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005321 }
5322 }
Eric Laurente552edb2014-03-10 17:42:56 -07005323
5324 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07005325 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005326
5327 return muteWaitMs;
5328}
5329
Eric Laurentc75307b2015-03-17 15:29:32 -07005330status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005331 int delayMs,
5332 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005333{
Eric Laurent6a94d692014-05-20 11:18:06 -07005334 ssize_t index;
5335 if (patchHandle) {
5336 index = mAudioPatches.indexOfKey(*patchHandle);
5337 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005338 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005339 }
5340 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005341 return INVALID_OPERATION;
5342 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005343 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5344 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005345 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005346 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005347 removeAudioPatch(patchDesc->mHandle);
5348 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005349 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005350 return status;
5351}
5352
5353status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5354 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005355 bool force,
5356 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005357{
5358 status_t status = NO_ERROR;
5359
Eric Laurent1f2f2232014-06-02 12:01:23 -07005360 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005361 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5362 inputDesc->mDevice = device;
5363
Mikhail Naganov708e0382018-05-30 09:53:04 -07005364 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005365 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005366 PatchBuilder patchBuilder;
5367 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005368 // AUDIO_SOURCE_HOTWORD is for internal use only:
5369 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07005370 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5371 auto result = usecase;
5372 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5373 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5374 }
5375 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07005376 //only one input device for now
Mikhail Naganovdc769682018-05-04 15:34:08 -07005377 addSource(deviceList.itemAt(0));
5378 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005379 }
5380 }
5381 return status;
5382}
5383
Eric Laurent6a94d692014-05-20 11:18:06 -07005384status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5385 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005386{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005387 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005388 ssize_t index;
5389 if (patchHandle) {
5390 index = mAudioPatches.indexOfKey(*patchHandle);
5391 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005392 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005393 }
5394 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005395 return INVALID_OPERATION;
5396 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005397 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5398 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005399 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005400 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005401 removeAudioPatch(patchDesc->mHandle);
5402 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005403 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005404 return status;
5405}
5406
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005407sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005408 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005409 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005410 audio_format_t& format,
5411 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005412 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005413{
5414 // Choose an input profile based on the requested capture parameters: select the first available
5415 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005416 //
5417 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5418 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005419
Glenn Kasten730b9262018-03-29 15:01:26 -07005420 sp<IOProfile> firstInexact;
5421 uint32_t updatedSamplingRate = 0;
5422 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5423 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005424 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005425 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005426 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005427 //updatedFormat = format;
Eric Laurent275e8e92014-11-30 15:14:47 -08005428 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005429 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005430 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005431 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005432 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005433 &channelMask /*updatedChannelMask*/,
5434 // FIXME ugly cast
5435 (audio_output_flags_t) flags,
5436 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005437 return profile;
5438 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005439 if (firstInexact == nullptr && profile->isCompatibleProfile(device, address,
5440 samplingRate,
5441 &updatedSamplingRate,
5442 format,
5443 &updatedFormat,
5444 channelMask,
5445 &updatedChannelMask,
5446 // FIXME ugly cast
5447 (audio_output_flags_t) flags,
5448 false /*exactMatchRequiredForInputFlags*/)) {
5449 firstInexact = profile;
5450 }
5451
Eric Laurente552edb2014-03-10 17:42:56 -07005452 }
5453 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005454 if (firstInexact != nullptr) {
5455 samplingRate = updatedSamplingRate;
5456 format = updatedFormat;
5457 channelMask = updatedChannelMask;
5458 return firstInexact;
5459 }
Eric Laurente552edb2014-03-10 17:42:56 -07005460 return NULL;
5461}
5462
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005463
5464audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005465 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005466{
Eric Laurent97ac8712018-07-27 18:59:02 -07005467 // Honor explicit routing requests only if all active clients have a preferred route in which
5468 // case the last active client route is used
5469 sp<DeviceDescriptor> deviceDesc =
5470 findPreferredDevice(mInputs, inputSource, mAvailableInputDevices);
5471 if (deviceDesc != nullptr) {
5472 return deviceDesc->type();
5473 }
5474
5475
François Gaffie036e1e92015-03-19 10:16:24 +01005476 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5477 audio_devices_t selectedDeviceFromMix =
5478 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005479
François Gaffie036e1e92015-03-19 10:16:24 +01005480 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5481 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005482 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005483 return getDeviceForInputSource(inputSource);
5484}
5485
5486audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5487{
Eric Laurent97ac8712018-07-27 18:59:02 -07005488 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005489}
5490
Eric Laurente0720872014-03-11 09:30:41 -07005491float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005492 int index,
5493 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005494{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005495 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005496
5497 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5498 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5499 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5500 // the ringtone volume
5501 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5502 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5503 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5504 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5505 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5506 }
5507
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005508 // in-call: always cap volume by voice volume + some low headroom
5509 if ((stream != AUDIO_STREAM_VOICE_CALL) &&
Eric Laurent7731b5a2018-04-06 15:47:22 -07005510 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005511 switch (stream) {
5512 case AUDIO_STREAM_SYSTEM:
5513 case AUDIO_STREAM_RING:
5514 case AUDIO_STREAM_MUSIC:
5515 case AUDIO_STREAM_ALARM:
5516 case AUDIO_STREAM_NOTIFICATION:
5517 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5518 case AUDIO_STREAM_DTMF:
5519 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005520 int voiceVolumeIndex =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005521 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, device);
Eric Laurent7731b5a2018-04-06 15:47:22 -07005522 const float maxVoiceVolDb =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005523 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, device)
Eric Laurent7731b5a2018-04-06 15:47:22 -07005524 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005525 if (volumeDB > maxVoiceVolDb) {
5526 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5527 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5528 volumeDB = maxVoiceVolDb;
5529 }
5530 } break;
5531 default:
5532 break;
5533 }
5534 }
5535
Eric Laurente552edb2014-03-10 17:42:56 -07005536 // if a headset is connected, apply the following rules to ring tones and notifications
5537 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005538 // - always attenuate notifications volume by 6dB
5539 // - attenuate ring tones volume by 6dB unless music is not playing and
5540 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005541 // - if music is playing, always limit the volume to current music volume,
5542 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005543 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005544 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5545 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5546 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005547 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005548 AUDIO_DEVICE_OUT_USB_HEADSET |
5549 AUDIO_DEVICE_OUT_HEARING_AID)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005550 ((stream_strategy == STRATEGY_SONIFICATION)
5551 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005552 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005553 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005554 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005555 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005556 // when the phone is ringing we must consider that music could have been paused just before
5557 // by the music application and behave as if music was active if the last music track was
5558 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005559 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005560 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005561 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005562 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005563 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005564 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5565 musicDevice),
5566 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005567 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5568 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005569 if (volumeDB > minVolDB) {
5570 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005571 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005572 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005573 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5574 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5575 // on A2DP, also ensure notification volume is not too low compared to media when
5576 // intended to be played
5577 if ((volumeDB > -96.0f) &&
5578 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5579 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5580 stream, device,
5581 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5582 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5583 }
5584 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005585 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5586 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005587 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005588 }
5589 }
5590
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005591 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005592}
5593
Eric Laurent3839bc02018-07-10 18:33:34 -07005594int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
5595 audio_stream_type_t srcStream,
5596 audio_stream_type_t dstStream)
5597{
5598 if (srcStream == dstStream) {
5599 return srcIndex;
5600 }
5601 float minSrc = (float)mVolumeCurves->getVolumeIndexMin(srcStream);
5602 float maxSrc = (float)mVolumeCurves->getVolumeIndexMax(srcStream);
5603 float minDst = (float)mVolumeCurves->getVolumeIndexMin(dstStream);
5604 float maxDst = (float)mVolumeCurves->getVolumeIndexMax(dstStream);
5605
5606 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
5607}
5608
Eric Laurente0720872014-03-11 09:30:41 -07005609status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005610 int index,
5611 const sp<AudioOutputDescriptor>& outputDesc,
5612 audio_devices_t device,
5613 int delayMs,
5614 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005615{
Eric Laurente552edb2014-03-10 17:42:56 -07005616 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005617 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005618 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005619 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005620 return NO_ERROR;
5621 }
François Gaffie2110e042015-03-24 08:41:51 +01005622 audio_policy_forced_cfg_t forceUseForComm =
5623 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005624 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005625 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5626 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005627 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005628 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005629 return INVALID_OPERATION;
5630 }
5631
Eric Laurentc75307b2015-03-17 15:29:32 -07005632 if (device == AUDIO_DEVICE_NONE) {
5633 device = outputDesc->device();
5634 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005635
Eric Laurentffbc80f2015-03-18 18:30:19 -07005636 float volumeDb = computeVolume(stream, index, device);
HW Leeda7581e2018-05-22 18:31:34 +08005637 if (outputDesc->isFixedVolume(device) ||
5638 // Force VoIP volume to max for bluetooth SCO
5639 ((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
5640 (device & AUDIO_DEVICE_OUT_ALL_SCO) != 0)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005641 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005642 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005643
Eric Laurentffbc80f2015-03-18 18:30:19 -07005644 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005645
Eric Laurent3b73df72014-03-11 09:06:29 -07005646 if (stream == AUDIO_STREAM_VOICE_CALL ||
5647 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005648 float voiceVolume;
5649 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005650 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurent3839bc02018-07-10 18:33:34 -07005651 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005652 } else {
5653 voiceVolume = 1.0;
5654 }
5655
Eric Laurent18fba842016-03-31 14:41:26 -07005656 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005657 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5658 mLastVoiceVolume = voiceVolume;
5659 }
5660 }
5661
5662 return NO_ERROR;
5663}
5664
Eric Laurentc75307b2015-03-17 15:29:32 -07005665void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5666 audio_devices_t device,
5667 int delayMs,
5668 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005669{
Eric Laurentc75307b2015-03-17 15:29:32 -07005670 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005671
Eric Laurent794fde22016-03-11 09:50:45 -08005672 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005673 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005674 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005675 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005676 device,
5677 delayMs,
5678 force);
5679 }
5680}
5681
Eric Laurente0720872014-03-11 09:30:41 -07005682void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005683 bool on,
5684 const sp<AudioOutputDescriptor>& outputDesc,
5685 int delayMs,
5686 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005687{
Eric Laurent72249d52015-06-08 11:12:15 -07005688 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5689 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005690 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005691 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005692 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005693 }
5694 }
5695}
5696
Eric Laurente0720872014-03-11 09:30:41 -07005697void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005698 bool on,
5699 const sp<AudioOutputDescriptor>& outputDesc,
5700 int delayMs,
5701 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005702{
Eric Laurente552edb2014-03-10 17:42:56 -07005703 if (device == AUDIO_DEVICE_NONE) {
5704 device = outputDesc->device();
5705 }
5706
Eric Laurentc75307b2015-03-17 15:29:32 -07005707 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5708 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005709
5710 if (on) {
5711 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005712 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005713 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005714 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005715 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005716 }
5717 }
5718 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5719 outputDesc->mMuteCount[stream]++;
5720 } else {
5721 if (outputDesc->mMuteCount[stream] == 0) {
5722 ALOGV("setStreamMute() unmuting non muted stream!");
5723 return;
5724 }
5725 if (--outputDesc->mMuteCount[stream] == 0) {
5726 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005727 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005728 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005729 device,
5730 delayMs);
5731 }
5732 }
5733}
5734
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005735audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5736{
5737 // flags to stream type mapping
5738 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5739 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5740 }
5741 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5742 return AUDIO_STREAM_BLUETOOTH_SCO;
5743 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005744 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5745 return AUDIO_STREAM_TTS;
5746 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005747
Ari Hausman-Cohen5c00d012018-06-26 17:09:11 -07005748 return audio_usage_to_stream_type(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005749}
Eric Laurente83b55d2014-11-14 10:06:21 -08005750
François Gaffie53615e22015-03-19 09:24:12 +01005751bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5752{
Eric Laurente83b55d2014-11-14 10:06:21 -08005753 // has flags that map to a strategy?
5754 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5755 return true;
5756 }
5757
5758 // has known usage?
5759 switch (paa->usage) {
5760 case AUDIO_USAGE_UNKNOWN:
5761 case AUDIO_USAGE_MEDIA:
5762 case AUDIO_USAGE_VOICE_COMMUNICATION:
5763 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5764 case AUDIO_USAGE_ALARM:
5765 case AUDIO_USAGE_NOTIFICATION:
5766 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5767 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5768 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5769 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5770 case AUDIO_USAGE_NOTIFICATION_EVENT:
5771 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5772 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5773 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5774 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005775 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005776 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005777 break;
5778 default:
5779 return false;
5780 }
5781 return true;
5782}
5783
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005784bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005785 routing_strategy strategy, uint32_t inPastMs,
5786 nsecs_t sysTime) const
5787{
5788 if ((sysTime == 0) && (inPastMs != 0)) {
5789 sysTime = systemTime();
5790 }
Eric Laurent794fde22016-03-11 09:50:45 -08005791 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005792 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurent97ac8712018-07-27 18:59:02 -07005793 (STRATEGY_NONE == strategy)) &&
François Gaffiead3183e2015-03-18 16:55:35 +01005794 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5795 return true;
5796 }
5797 }
5798 return false;
5799}
5800
Eric Laurent484e9272018-06-07 17:29:23 -07005801bool AudioPolicyManager::isStrategyActiveOnSameModule(const sp<AudioOutputDescriptor>& outputDesc,
5802 routing_strategy strategy, uint32_t inPastMs,
5803 nsecs_t sysTime) const
5804{
5805 for (size_t i = 0; i < mOutputs.size(); i++) {
5806 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5807 if (outputDesc->sharesHwModuleWith(desc)
5808 && isStrategyActive(desc, strategy, inPastMs, sysTime)) {
5809 return true;
5810 }
5811 }
5812 return false;
5813}
5814
François Gaffie2110e042015-03-24 08:41:51 +01005815audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5816{
5817 return mEngine->getForceUse(usage);
5818}
5819
5820bool AudioPolicyManager::isInCall()
5821{
5822 return isStateInCall(mEngine->getPhoneState());
5823}
5824
5825bool AudioPolicyManager::isStateInCall(int state)
5826{
5827 return is_state_in_call(state);
5828}
5829
Eric Laurentd60560a2015-04-10 11:31:20 -07005830void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5831{
5832 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005833 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5834 if (sourceDesc->srcDevice()->equals(deviceDesc)) {
5835 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->portId());
5836 stopAudioSource(sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005837 }
5838 }
5839
5840 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5841 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5842 bool release = false;
5843 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5844 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5845 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5846 source->ext.device.type == deviceDesc->type()) {
5847 release = true;
5848 }
5849 }
5850 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5851 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5852 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5853 sink->ext.device.type == deviceDesc->type()) {
5854 release = true;
5855 }
5856 }
5857 if (release) {
5858 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5859 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5860 }
5861 }
5862}
5863
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005864void AudioPolicyManager::modifySurroundFormats(
5865 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005866 std::unordered_set<audio_format_t> enforcedSurround(
5867 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08005868 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
5869 for (const auto& pair : mConfig.getSurroundFormats()) {
5870 allSurround.insert(pair.first);
5871 for (const auto& subformat : pair.second) allSurround.insert(subformat);
5872 }
Phil Burk09bc4612016-02-24 15:58:15 -08005873
5874 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5875 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005876 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005877 // This is the resulting set of formats depending on the surround mode:
5878 // 'all surround' = allSurround
5879 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
5880 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
5881 // 'manual surround' = mManualSurroundFormats
5882 // AUTO: formats v 'enforced surround'
5883 // ALWAYS: formats v 'all surround' v 'enforced surround'
5884 // NEVER: formats ^ 'non-surround'
5885 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08005886
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005887 std::unordered_set<audio_format_t> formatSet;
5888 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
5889 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005890 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005891 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005892 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005893 formatSet.insert(*formatIter);
5894 }
5895 }
5896 } else {
5897 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
5898 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005899 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005900
jiabin81772902018-04-02 17:52:27 -07005901 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005902 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005903 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
5904 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
5905 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08005906 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005907 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
5908 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5909 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07005910 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005911 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08005912 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005913 for (const auto& format : formatSet) {
5914 formatsPtr->push(format);
5915 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005916}
5917
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005918void AudioPolicyManager::modifySurroundChannelMasks(ChannelsVector *channelMasksPtr) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005919 ChannelsVector &channelMasks = *channelMasksPtr;
5920 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5921 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5922
5923 // If NEVER, then remove support for channelMasks > stereo.
5924 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5925 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5926 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5927 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5928 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5929 channelMasks.removeAt(maskIndex);
5930 } else {
5931 maskIndex++;
5932 }
5933 }
jiabin81772902018-04-02 17:52:27 -07005934 // If ALWAYS or MANUAL, then make sure we at least support 5.1
5935 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
5936 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005937 bool supports5dot1 = false;
5938 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005939 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005940 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5941 supports5dot1 = true;
5942 break;
5943 }
5944 }
5945 // If not then add 5.1 support.
5946 if (!supports5dot1) {
5947 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005948 ALOGI("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07005949 }
Phil Burk09bc4612016-02-24 15:58:15 -08005950 }
5951}
5952
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005953void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07005954 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005955 AudioProfileVector &profiles)
5956{
5957 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005958 audio_devices_t device = devDesc->type();
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());
Mikhail Naganov100f0122018-11-29 11:22:16 -08005972 if (device == AUDIO_DEVICE_OUT_HDMI
5973 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005974 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005975 }
Phil Burk09bc4612016-02-24 15:58:15 -08005976 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005977 }
François Gaffie112b0af2015-11-19 16:13:25 +01005978
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005979 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08005980 ChannelsVector channelMasks;
5981 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005982 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07005983 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01005984
5985 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005986 reply = mpClientInterface->getParameters(
5987 ioHandle,
5988 requestedParameters.toString() + ";" +
5989 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01005990 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005991 AudioParameter repliedParameters(reply);
5992 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005993 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005994 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005995 }
5996 }
5997 if (profiles.hasDynamicChannelsFor(format)) {
5998 reply = mpClientInterface->getParameters(ioHandle,
5999 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07006000 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01006001 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006002 AudioParameter repliedParameters(reply);
6003 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006004 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006005 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006006 if (device == AUDIO_DEVICE_OUT_HDMI
6007 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006008 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07006009 }
François Gaffie112b0af2015-11-19 16:13:25 +01006010 }
6011 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08006012 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006013 }
6014}
Eric Laurentd60560a2015-04-10 11:31:20 -07006015
Mikhail Naganovdc769682018-05-04 15:34:08 -07006016status_t AudioPolicyManager::installPatch(const char *caller,
6017 audio_patch_handle_t *patchHandle,
6018 AudioIODescriptorInterface *ioDescriptor,
6019 const struct audio_patch *patch,
6020 int delayMs)
6021{
6022 ssize_t index = mAudioPatches.indexOfKey(
6023 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6024 *patchHandle : ioDescriptor->getPatchHandle());
6025 sp<AudioPatch> patchDesc;
6026 status_t status = installPatch(
6027 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6028 if (status == NO_ERROR) {
6029 ioDescriptor->setPatchHandle(patchDesc->mHandle);
6030 }
6031 return status;
6032}
6033
6034status_t AudioPolicyManager::installPatch(const char *caller,
6035 ssize_t index,
6036 audio_patch_handle_t *patchHandle,
6037 const struct audio_patch *patch,
6038 int delayMs,
6039 uid_t uid,
6040 sp<AudioPatch> *patchDescPtr)
6041{
6042 sp<AudioPatch> patchDesc;
6043 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6044 if (index >= 0) {
6045 patchDesc = mAudioPatches.valueAt(index);
6046 afPatchHandle = patchDesc->mAfPatchHandle;
6047 }
6048
6049 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6050 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6051 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6052 if (status == NO_ERROR) {
6053 if (index < 0) {
6054 patchDesc = new AudioPatch(patch, uid);
6055 addAudioPatch(patchDesc->mHandle, patchDesc);
6056 } else {
6057 patchDesc->mPatch = *patch;
6058 }
6059 patchDesc->mAfPatchHandle = afPatchHandle;
6060 if (patchHandle) {
6061 *patchHandle = patchDesc->mHandle;
6062 }
6063 nextAudioPortGeneration();
6064 mpClientInterface->onAudioPatchListUpdate();
6065 }
6066 if (patchDescPtr) *patchDescPtr = patchDesc;
6067 return status;
6068}
6069
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006070} // namespace android