blob: d13253dc12dc5f0f2ce094dca47b516fe5c2c4cf [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...)
152 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
153
Eric Laurenta1d525f2015-01-29 13:36:45 -0800154 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != 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,
158 devDesc->mAddress);
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 Gaffie44481e72016-04-20 07:49:57 +0200181 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
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
Eric Laurenta1d525f2015-01-29 13:36:45 -0800186 checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress);
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...)
268 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
269
Paul McLean9080a4c2015-06-18 08:24:02 -0700270 if (checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress) != NO_ERROR) {
François Gaffie44481e72016-04-20 07:49:57 +0200271 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
272 devDesc->mAddress);
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 Gaffie44481e72016-04-20 07:49:57 +0200297 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700298
Paul McLean9080a4c2015-06-18 08:24:02 -0700299 checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress);
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);
Eric Laurent2ac76942017-06-22 17:17:09 -0700913 *selectedDeviceId = outputDevices.size() > 0 ? outputDevices.itemAt(0)->getId()
914 : AUDIO_PORT_HANDLE_NONE;
915
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700916 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
917
918 return NO_ERROR;
919}
920
921status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
922 audio_io_handle_t *output,
923 audio_session_t session,
924 audio_stream_type_t *stream,
925 uid_t uid,
926 const audio_config_t *config,
927 audio_output_flags_t *flags,
928 audio_port_handle_t *selectedDeviceId,
929 audio_port_handle_t *portId)
930{
931 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
932 if (*portId != AUDIO_PORT_HANDLE_NONE) {
933 return INVALID_OPERATION;
934 }
935 const audio_port_handle_t requestedDeviceId = *selectedDeviceId;
936 audio_attributes_t resultAttr;
937 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
938 config, flags, selectedDeviceId);
939 if (status != NO_ERROR) {
940 return status;
941 }
942
Eric Laurent8fc147b2018-07-22 19:13:55 -0700943 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
944 .format = config->format,
945 .channel_mask = config->channel_mask };
Eric Laurent8f42ea12018-08-08 09:08:25 -0700946 *portId = AudioPort::getNextUniqueId();
947
Eric Laurent8fc147b2018-07-22 19:13:55 -0700948 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700949 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Eric Laurent97ac8712018-07-27 18:59:02 -0700950 requestedDeviceId, *stream,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700951 getStrategyForAttr(&resultAttr),
Eric Laurent97ac8712018-07-27 18:59:02 -0700952 *flags);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700953 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Andy Hung39efb7a2018-09-26 15:39:28 -0700954 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700955
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700956 ALOGV("%s returns output %d selectedDeviceId %d for port ID %d",
957 __func__, *output, requestedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -0700958
Eric Laurente83b55d2014-11-14 10:06:21 -0800959 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700960}
961
962audio_io_handle_t AudioPolicyManager::getOutputForDevice(
963 audio_devices_t device,
Kevin Rocard169753c2017-03-06 14:18:23 -0800964 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700965 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -0800966 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200967 audio_output_flags_t *flags)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700968{
Andy Hungc88b0642018-04-27 15:42:35 -0700969 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700970 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700971
Eric Laurente552edb2014-03-10 17:42:56 -0700972 // open a direct output if required by specified parameters
973 //force direct flag if offload flag is set: offloading implies a direct output stream
974 // and all common behaviors are driven by checking only the direct flag
975 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +0200976 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
977 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700978 }
Nadav Bar766fb022018-01-07 12:18:03 +0200979 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
980 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -0700981 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800982 // only allow deep buffering for music stream type
983 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +0200984 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700985 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +0200986 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700987 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
988 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +0200989 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800990 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700991 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +0200992 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700993 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +0200994 audio_is_linear_pcm(config->format) &&
995 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200996 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700997 AUDIO_OUTPUT_FLAG_DIRECT);
998 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700999 }
Eric Laurente552edb2014-03-10 17:42:56 -07001000
Nadav Bar766fb022018-01-07 12:18:03 +02001001
Eric Laurentb732cf52014-09-24 19:08:21 -07001002 sp<IOProfile> profile;
1003
1004 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -07001005 // and not explicitly requested
Nadav Bar766fb022018-01-07 12:18:03 +02001006 if (((*flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Eric Laurentfe231122017-11-17 17:48:06 -08001007 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1008 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
Eric Laurentb732cf52014-09-24 19:08:21 -07001009 goto non_direct_output;
1010 }
1011
Andy Hung2ddee192015-12-18 17:34:44 -08001012 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1013 // This prevents creating an offloaded track and tearing it down immediately after start
1014 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -07001015 // FIXME: We should check the audio session here but we do not have it in this context.
1016 // This may prevent offloading in rare situations where effects are left active by apps
1017 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -07001018
Nadav Bar766fb022018-01-07 12:18:03 +02001019 if (((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -08001020 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Michael Chana94fbb22018-04-24 14:31:19 +10001021 profile = getProfileForOutput(device,
1022 config->sample_rate,
1023 config->format,
1024 config->channel_mask,
1025 (audio_output_flags_t)*flags,
1026 true /* directOnly */);
Eric Laurente552edb2014-03-10 17:42:56 -07001027 }
1028
Eric Laurent1c333e22014-05-20 10:48:17 -07001029 if (profile != 0) {
Andy Hungc88b0642018-04-27 15:42:35 -07001030 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1031 for (size_t i = 0; i < mOutputs.size(); i++) {
1032 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1033 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1034 // reuse direct output if currently open by the same client
1035 // and configured with same parameters
1036 if ((config->sample_rate == desc->mSamplingRate) &&
Andy Hung5659ed52018-04-30 10:31:26 -07001037 (config->format == desc->mFormat) &&
Andy Hungc88b0642018-04-27 15:42:35 -07001038 (config->channel_mask == desc->mChannelMask) &&
1039 (session == desc->mDirectClientSession)) {
1040 desc->mDirectOpenCount++;
1041 ALOGI("getOutputForDevice() reusing direct output %d for session %d",
1042 mOutputs.keyAt(i), session);
1043 return mOutputs.keyAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001044 }
1045 }
1046 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08001047
1048 if (!profile->canOpenNewIo()) {
1049 goto non_direct_output;
Eric Laurente552edb2014-03-10 17:42:56 -07001050 }
Eric Laurent861a6282015-05-18 15:40:16 -07001051
Eric Laurent3974e3b2017-12-07 17:58:43 -08001052 sp<SwAudioOutputDescriptor> outputDesc =
1053 new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurent53b810e2017-12-10 17:25:10 -08001054
Mikhail Naganov708e0382018-05-30 09:53:04 -07001055 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -08001056 String8 address = outputDevices.size() > 0 ? outputDevices.itemAt(0)->mAddress
1057 : String8("");
1058
Dean Wheatley3023b382018-08-09 07:42:40 +10001059 // MSD patch may be using the only output stream that can service this request. Release
1060 // MSD patch to prioritize this request over any active output on MSD.
1061 AudioPatchCollection msdPatches = getMsdPatches();
1062 for (size_t i = 0; i < msdPatches.size(); i++) {
1063 const auto& patch = msdPatches[i];
1064 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1065 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1066 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
1067 (sink->ext.device.type & device) != AUDIO_DEVICE_NONE &&
1068 (address.isEmpty() || strncmp(sink->ext.device.address, address.string(),
1069 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
1070 releaseAudioPatch(patch->mHandle, mUidCached);
1071 break;
1072 }
1073 }
1074 }
1075
Nadav Bar766fb022018-01-07 12:18:03 +02001076 status = outputDesc->open(config, device, address, stream, *flags, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07001077
1078 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001079 if (status != NO_ERROR ||
Eric Laurentfe231122017-11-17 17:48:06 -08001080 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
Andy Hung5659ed52018-04-30 10:31:26 -07001081 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->mFormat) ||
Eric Laurentfe231122017-11-17 17:48:06 -08001082 (config->channel_mask != 0 && config->channel_mask != outputDesc->mChannelMask)) {
1083 ALOGV("getOutputForDevice() failed opening direct output: output %d sample rate %d %d,"
1084 "format %d %d, channel mask %04x %04x", output, config->sample_rate,
1085 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
1086 config->channel_mask, outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001087 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001088 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07001089 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001090 // fall back to mixer output if possible when the direct output could not be open
Eric Laurentfe231122017-11-17 17:48:06 -08001091 if (audio_is_linear_pcm(config->format) &&
1092 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -08001093 goto non_direct_output;
1094 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001095 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001096 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001097 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -08001098 outputDesc->mDirectClientSession = session;
1099
Eric Laurente552edb2014-03-10 17:42:56 -07001100 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001101 mPreviousOutputs = mOutputs;
Eric Laurentf4e63452017-11-06 19:31:46 +00001102 ALOGV("getOutputForDevice() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001103 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001104 return output;
1105 }
1106
Eric Laurentb732cf52014-09-24 19:08:21 -07001107non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001108
1109 // A request for HW A/V sync cannot fallback to a mixed output because time
1110 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001111 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001112 return AUDIO_IO_HANDLE_NONE;
1113 }
1114
Eric Laurente552edb2014-03-10 17:42:56 -07001115 // ignoring channel mask due to downmix capability in mixer
1116
1117 // open a non direct output
1118
1119 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001120 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001121 // get which output is suitable for the specified stream. The actual
1122 // routing change will happen when startOutput() will be called
1123 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1124
Eric Laurent8838a382014-09-08 16:44:28 -07001125 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001126 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabin40573322018-11-08 12:08:02 -08001127 output = selectOutput(outputs, *flags, config->format,
1128 config->channel_mask, config->sample_rate);
Eric Laurente552edb2014-03-10 17:42:56 -07001129 }
Eric Laurentf4e63452017-11-06 19:31:46 +00001130 ALOGW_IF((output == 0), "getOutputForDevice() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001131 "sampling rate %d, format %#x, channels %#x, flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +02001132 stream, config->sample_rate, config->format, config->channel_mask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001133
Eric Laurente552edb2014-03-10 17:42:56 -07001134 return output;
1135}
1136
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001137sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001138 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001139 if (msdModule != 0) {
1140 DeviceVector msdInputDevices = mAvailableInputDevices.getDevicesFromHwModule(
1141 msdModule->getHandle());
1142 if (!msdInputDevices.isEmpty()) return msdInputDevices.itemAt(0);
1143 }
1144 return 0;
1145}
1146
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001147const AudioPatchCollection AudioPolicyManager::getMsdPatches() const {
1148 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001149 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1150 if (msdModule != 0) {
1151 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1152 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1153 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1154 const struct audio_port_config *source = &patch->mPatch.sources[j];
1155 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1156 source->ext.device.hw_module == msdModule->getHandle()) {
1157 msdPatches.addAudioPatch(patch->mHandle, patch);
1158 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001159 }
1160 }
1161 }
1162 return msdPatches;
1163}
1164
1165status_t AudioPolicyManager::getBestMsdAudioProfileFor(audio_devices_t outputDevice,
1166 bool hwAvSync, audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1167{
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001168 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001169 if (msdModule == nullptr) {
1170 ALOGE("%s() unable to get MSD module", __func__);
1171 return NO_INIT;
1172 }
1173 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(outputDevice);
1174 if (deviceModule == nullptr) {
1175 ALOGE("%s() unable to get module for %#x", __func__, outputDevice);
1176 return NO_INIT;
1177 }
1178 const InputProfileCollection &inputProfiles = msdModule->getInputProfiles();
1179 if (inputProfiles.isEmpty()) {
1180 ALOGE("%s() no input profiles for MSD module", __func__);
1181 return NO_INIT;
1182 }
1183 const OutputProfileCollection &outputProfiles = deviceModule->getOutputProfiles();
1184 if (outputProfiles.isEmpty()) {
1185 ALOGE("%s() no output profiles for device %#x", __func__, outputDevice);
1186 return NO_INIT;
1187 }
1188 AudioProfileVector msdProfiles;
1189 // Each IOProfile represents a MixPort from audio_policy_configuration.xml
1190 for (const auto &inProfile : inputProfiles) {
1191 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0)) {
1192 msdProfiles.appendVector(inProfile->getAudioProfiles());
1193 }
1194 }
1195 AudioProfileVector deviceProfiles;
1196 for (const auto &outProfile : outputProfiles) {
1197 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0)) {
1198 deviceProfiles.appendVector(outProfile->getAudioProfiles());
1199 }
1200 }
1201 struct audio_config_base bestSinkConfig;
1202 status_t result = msdProfiles.findBestMatchingOutputConfig(deviceProfiles,
1203 compressedFormatsOrder, surroundChannelMasksOrder, true /*preferHigherSamplingRates*/,
1204 &bestSinkConfig);
1205 if (result != NO_ERROR) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001206 ALOGD("%s() no matching profiles found for device: %#x, hwAvSync: %d",
1207 __func__, outputDevice, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001208 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001209 }
1210 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1211 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1212 sinkConfig->format = bestSinkConfig.format;
1213 // For encoded streams force direct flag to prevent downstream mixing.
1214 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1215 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
1216 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1217 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1218 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1219 sourceConfig->format = bestSinkConfig.format;
1220 // Copy input stream directly without any processing (e.g. resampling).
1221 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1222 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1223 if (hwAvSync) {
1224 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1225 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1226 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1227 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1228 }
1229 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1230 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1231 sinkConfig->config_mask |= config_mask;
1232 sourceConfig->config_mask |= config_mask;
1233 return NO_ERROR;
1234}
1235
1236PatchBuilder AudioPolicyManager::buildMsdPatch(audio_devices_t outputDevice) const
1237{
1238 PatchBuilder patchBuilder;
1239 patchBuilder.addSource(getMsdAudioInDevice()).
1240 addSink(findDevice(mAvailableOutputDevices, outputDevice));
1241 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1242 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
1243 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1244 // For now, we just forcefully try with HwAvSync first.
1245 status_t res = getBestMsdAudioProfileFor(outputDevice, true /*hwAvSync*/,
1246 &sourceConfig, &sinkConfig) == NO_ERROR ? NO_ERROR :
1247 getBestMsdAudioProfileFor(
1248 outputDevice, false /*hwAvSync*/, &sourceConfig, &sinkConfig);
1249 if (res == NO_ERROR) {
1250 // Found a matching profile for encoded audio. Re-create PatchBuilder with this config.
1251 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1252 }
1253 ALOGV("%s() no matching profile found. Fall through to default PCM patch"
1254 " supporting PCM format conversion.", __func__);
1255 return patchBuilder;
1256}
1257
1258status_t AudioPolicyManager::setMsdPatch(audio_devices_t outputDevice) {
1259 ALOGV("%s() for outputDevice %#x", __func__, outputDevice);
1260 if (outputDevice == AUDIO_DEVICE_NONE) {
1261 // Use media strategy for unspecified output device. This should only
1262 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1263 // therefore invalidate explicit routing requests.
1264 outputDevice = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
1265 }
1266 PatchBuilder patchBuilder = buildMsdPatch(outputDevice);
1267 const struct audio_patch* patch = patchBuilder.patch();
1268 const AudioPatchCollection msdPatches = getMsdPatches();
1269 if (!msdPatches.isEmpty()) {
1270 LOG_ALWAYS_FATAL_IF(msdPatches.size() > 1,
1271 "The current MSD prototype only supports one output patch");
1272 sp<AudioPatch> currentPatch = msdPatches.valueAt(0);
1273 if (audio_patches_are_equal(&currentPatch->mPatch, patch)) {
1274 return NO_ERROR;
1275 }
1276 releaseAudioPatch(currentPatch->mHandle, mUidCached);
1277 }
1278 status_t status = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1279 patch, 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1280 ALOGE_IF(status != NO_ERROR, "%s() error %d creating MSD audio patch", __func__, status);
1281 ALOGI_IF(status == NO_ERROR, "%s() Patch created from MSD_IN to "
1282 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__, outputDevice,
1283 patch->sources[0].format, patch->sources[0].channel_mask, patch->sources[0].sample_rate);
1284 return status;
1285}
1286
Eric Laurente0720872014-03-11 09:30:41 -07001287audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001288 audio_output_flags_t flags,
jiabin40573322018-11-08 12:08:02 -08001289 audio_format_t format,
1290 audio_channel_mask_t channelMask,
1291 uint32_t samplingRate)
Eric Laurente552edb2014-03-10 17:42:56 -07001292{
1293 // select one output among several that provide a path to a particular device or set of
1294 // devices (the list was previously build by getOutputsForDevice()).
1295 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001296 // 1: the output supporting haptic playback when requesting haptic playback
1297 // 2: the output with the highest number of requested policy flags
1298 // 3: the output with the bit depth the closest to the requested one
1299 // 4: the primary output
1300 // 5: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001301
1302 if (outputs.size() == 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001303 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001304 }
1305 if (outputs.size() == 1) {
1306 return outputs[0];
1307 }
1308
1309 int maxCommonFlags = 0;
jiabin40573322018-11-08 12:08:02 -08001310 const size_t hapticChannelCount = audio_channel_count_from_out_mask(
1311 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001312 audio_io_handle_t outputForFlags = AUDIO_IO_HANDLE_NONE;
1313 audio_io_handle_t outputForPrimary = AUDIO_IO_HANDLE_NONE;
1314 audio_io_handle_t outputForFormat = AUDIO_IO_HANDLE_NONE;
Eric Laurente6930022016-02-11 10:20:40 -08001315 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1316 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001317
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001318 for (audio_io_handle_t output : outputs) {
1319 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001320 if (!outputDesc->isDuplicated()) {
chenhg1794d712018-10-09 15:20:37 -07001321 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1322 continue;
1323 }
jiabin40573322018-11-08 12:08:02 -08001324 // If haptic channel is specified, use the haptic output if present.
1325 // When using haptic output, same audio format and sample rate are required.
1326 if (hapticChannelCount > 0) {
1327 // If haptic channel is specified, use the first output that
1328 // support haptic playback.
1329 if (audio_channel_count_from_out_mask(
1330 outputDesc->mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL) >= hapticChannelCount
1331 && format == outputDesc->mFormat
1332 && samplingRate == outputDesc->mSamplingRate) {
1333 return output;
1334 }
1335 } else {
1336 // When haptic channel is not specified, skip haptic output.
1337 if (outputDesc->mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL) {
1338 continue;
1339 }
1340 }
1341
Eric Laurent8838a382014-09-08 16:44:28 -07001342 // if a valid format is specified, skip output if not compatible
1343 if (format != AUDIO_FORMAT_INVALID) {
chenhg1794d712018-10-09 15:20:37 -07001344 if (!audio_is_linear_pcm(format)) {
Eric Laurent8838a382014-09-08 16:44:28 -07001345 continue;
1346 }
Eric Laurente6930022016-02-11 10:20:40 -08001347 if (AudioPort::isBetterFormatMatch(
1348 outputDesc->mFormat, bestFormat, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001349 outputForFormat = output;
Eric Laurente6930022016-02-11 10:20:40 -08001350 bestFormat = outputDesc->mFormat;
1351 }
Eric Laurent8838a382014-09-08 16:44:28 -07001352 }
1353
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001354 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001355 if (commonFlags >= maxCommonFlags) {
1356 if (commonFlags == maxCommonFlags) {
Andy Hungc9901522017-11-10 20:07:54 -08001357 if (format != AUDIO_FORMAT_INVALID
1358 && AudioPort::isBetterFormatMatch(
1359 outputDesc->mFormat, bestFormatForFlags, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001360 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001361 bestFormatForFlags = outputDesc->mFormat;
1362 }
1363 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001364 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001365 maxCommonFlags = commonFlags;
1366 bestFormatForFlags = outputDesc->mFormat;
1367 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001368 ALOGV("selectOutput() commonFlags for output %d, %04x", output, commonFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001369 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001370 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001371 outputForPrimary = output;
Eric Laurente552edb2014-03-10 17:42:56 -07001372 }
1373 }
1374 }
1375
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001376 if (outputForFlags != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001377 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001378 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001379 if (outputForFormat != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001380 return outputForFormat;
1381 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001382 if (outputForPrimary != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001383 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001384 }
1385
1386 return outputs[0];
1387}
1388
Eric Laurent8fc147b2018-07-22 19:13:55 -07001389status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001390{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001391 ALOGV("%s portId %d", __FUNCTION__, portId);
1392
1393 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1394 if (outputDesc == 0) {
1395 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001396 return BAD_VALUE;
1397 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001398 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001399
Eric Laurent8fc147b2018-07-22 19:13:55 -07001400 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001401 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001402
Eric Laurent733ce942017-12-07 12:18:25 -08001403 status_t status = outputDesc->start();
1404 if (status != NO_ERROR) {
1405 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001406 }
1407
Eric Laurent97ac8712018-07-27 18:59:02 -07001408 uint32_t delayMs;
1409 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001410
1411 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001412 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001413 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001414 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001415 if (delayMs != 0) {
1416 usleep(delayMs * 1000);
1417 }
1418
1419 return status;
1420}
1421
Eric Laurent97ac8712018-07-27 18:59:02 -07001422status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1423 const sp<TrackClientDescriptor>& client,
1424 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001425{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001426 // cannot start playback of STREAM_TTS if any other output is being used
1427 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001428
1429 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001430 audio_stream_type_t stream = client->stream();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001431 if (stream == AUDIO_STREAM_TTS) {
1432 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001433 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001434 return INVALID_OPERATION;
1435 } else {
1436 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1437 }
1438 } else {
1439 // some playback other than beacon starts
1440 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1441 }
1442
Eric Laurent77305a62016-07-25 16:39:22 -07001443 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001444 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001445 bool force = !outputDesc->isActive() &&
1446 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001447
Eric Laurent97ac8712018-07-27 18:59:02 -07001448 audio_devices_t device = AUDIO_DEVICE_NONE;
1449 AudioMix *policyMix = NULL;
1450 const char *address = NULL;
1451 if (outputDesc->mPolicyMix != NULL) {
1452 policyMix = outputDesc->mPolicyMix;
1453 address = policyMix->mDeviceAddress.string();
1454 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1455 device = policyMix->mDeviceType;
1456 } else {
1457 device = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1458 }
1459 }
1460
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001461 // requiresMuteCheck is false when we can bypass mute strategy.
1462 // It covers a common case when there is no materially active audio
1463 // and muting would result in unnecessary delay and dropped audio.
1464 const uint32_t outputLatencyMs = outputDesc->latency();
1465 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1466
Eric Laurente552edb2014-03-10 17:42:56 -07001467 // increment usage count for this stream on the requested output:
1468 // NOTE that the usage count is the same for duplicated output and hardware output which is
1469 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001470 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001471
1472 if (client->hasPreferredDevice(true)) {
1473 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
1474 if (device != outputDesc->device()) {
1475 checkStrategyRoute(getStrategy(stream), outputDesc->mIoHandle);
1476 }
1477 }
Eric Laurente552edb2014-03-10 17:42:56 -07001478
Eric Laurent36829f92017-04-07 19:04:42 -07001479 if (stream == AUDIO_STREAM_MUSIC) {
1480 selectOutputForMusicEffects();
1481 }
1482
Eric Laurent592dd7b2018-08-05 18:58:48 -07001483 if (outputDesc->streamActiveCount(stream) == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001484 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001485 if (device == AUDIO_DEVICE_NONE) {
1486 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001487 }
Eric Laurent36829f92017-04-07 19:04:42 -07001488
Eric Laurente552edb2014-03-10 17:42:56 -07001489 routing_strategy strategy = getStrategy(stream);
1490 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001491 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1492 (beaconMuteLatency > 0);
1493 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001494 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001495 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001496 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001497 // An output has a shared device if
1498 // - managed by the same hw module
1499 // - supports the currently selected device
1500 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
1501 && (desc->supportedDevices() & device) != AUDIO_DEVICE_NONE;
1502
Eric Laurent77305a62016-07-25 16:39:22 -07001503 // force a device change if any other output is:
1504 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001505 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001506 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001507 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001508 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001509 // change the device currently selected by the other output.
1510 if (sharedDevice &&
Eric Laurent77305a62016-07-25 16:39:22 -07001511 desc->device() != device &&
Eric Laurent77305a62016-07-25 16:39:22 -07001512 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001513 force = true;
1514 }
1515 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001516 // a notification so that audio focus effect can propagate, or that a mute/unmute
1517 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001518 const uint32_t latencyMs = desc->latency();
1519 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1520
1521 if (shouldWait && isActive && (waitMs < latencyMs)) {
1522 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001523 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001524
1525 // Require mute check if another output is on a shared device
1526 // and currently active to have proper drain and avoid pops.
1527 // Note restoring AudioTracks onto this output needs to invoke
1528 // a volume ramp if there is no mute.
1529 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001530 }
1531 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001532
1533 const uint32_t muteWaitMs =
1534 setOutputDevice(outputDesc, device, force, 0, NULL, address, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001535
Eric Laurente552edb2014-03-10 17:42:56 -07001536 // apply volume rules for current stream and device if necessary
1537 checkAndSetVolume(stream,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001538 mVolumeCurves->getVolumeIndex(stream, outputDesc->device()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001539 outputDesc,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001540 outputDesc->device());
Eric Laurente552edb2014-03-10 17:42:56 -07001541
1542 // update the outputs if starting an output with a stream that can affect notification
1543 // routing
1544 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001545
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001546 // force reevaluating accessibility routing when ringtone or alarm starts
1547 if (strategy == STRATEGY_SONIFICATION) {
1548 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1549 }
Eric Laurentdc462862016-07-19 12:29:53 -07001550
1551 if (waitMs > muteWaitMs) {
1552 *delayMs = waitMs - muteWaitMs;
1553 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001554
1555 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1556 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1557 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1558 // change occurs after the MixerThread starts and causes a stream volume
1559 // glitch.
1560 //
1561 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001562 }
Eric Laurentdc462862016-07-19 12:29:53 -07001563
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001564 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1565 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1566 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1567 }
1568
Eric Laurent97ac8712018-07-27 18:59:02 -07001569 // Automatically enable the remote submix input when output is started on a re routing mix
1570 // of type MIX_TYPE_RECORDERS
1571 if (audio_is_remote_submix_device(device) && policyMix != NULL &&
1572 policyMix->mMixType == MIX_TYPE_RECORDERS) {
1573 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1574 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1575 address,
1576 "remote-submix");
1577 }
1578
Eric Laurente552edb2014-03-10 17:42:56 -07001579 return NO_ERROR;
1580}
1581
Eric Laurent8fc147b2018-07-22 19:13:55 -07001582status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001583{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001584 ALOGV("%s portId %d", __FUNCTION__, portId);
1585
1586 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1587 if (outputDesc == 0) {
1588 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001589 return BAD_VALUE;
1590 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001591 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001592
Eric Laurent97ac8712018-07-27 18:59:02 -07001593 ALOGV("stopOutput() output %d, stream %d, session %d",
1594 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07001595
Eric Laurent97ac8712018-07-27 18:59:02 -07001596 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08001597
Eric Laurent733ce942017-12-07 12:18:25 -08001598 if (status == NO_ERROR ) {
1599 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001600 }
1601 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001602}
1603
Eric Laurent97ac8712018-07-27 18:59:02 -07001604status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1605 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07001606{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001607 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07001608 audio_stream_type_t stream = client->stream();
1609
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001610 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1611
Eric Laurent592dd7b2018-08-05 18:58:48 -07001612 if (outputDesc->streamActiveCount(stream) > 0) {
1613 if (outputDesc->streamActiveCount(stream) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001614 // Automatically disable the remote submix input when output is stopped on a
1615 // re routing mix of type MIX_TYPE_RECORDERS
1616 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1617 outputDesc->mPolicyMix != NULL &&
1618 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1619 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1620 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1621 outputDesc->mPolicyMix->mDeviceAddress,
1622 "remote-submix");
1623 }
1624 }
1625 bool forceDeviceUpdate = false;
1626 if (client->hasPreferredDevice(true)) {
1627 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1628 forceDeviceUpdate = true;
1629 }
1630
Eric Laurente552edb2014-03-10 17:42:56 -07001631 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07001632 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07001633
Eric Laurente552edb2014-03-10 17:42:56 -07001634 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001635 if (outputDesc->streamActiveCount(stream) == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001636 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001637 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001638 // delay the device switch by twice the latency because stopOutput() is executed when
1639 // the track stop() command is received and at that time the audio track buffer can
1640 // still contain data that needs to be drained. The latency only covers the audio HAL
1641 // and kernel buffers. Also the latency does not always include additional delay in the
1642 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001643 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001644
1645 // force restoring the device selection on other active outputs if it differs from the
1646 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001647 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001648 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001649 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001650 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001651 desc->isActive() &&
1652 outputDesc->sharesHwModuleWith(desc) &&
1653 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001654 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1655 bool force = desc->device() != newDevice2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001656
Eric Laurentc75307b2015-03-17 15:29:32 -07001657 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001658 newDevice2,
1659 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001660 delayMs);
1661 // re-apply device specific volume if not done by setOutputDevice()
1662 if (!force) {
1663 applyStreamVolumes(desc, newDevice2, delayMs);
1664 }
Eric Laurente552edb2014-03-10 17:42:56 -07001665 }
1666 }
1667 // update the outputs if stopping one with a stream that can affect notification routing
1668 handleNotificationRoutingForStream(stream);
1669 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001670
1671 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1672 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1673 setStrategyMute(STRATEGY_SONIFICATION, false, outputDesc);
1674 }
1675
Eric Laurent36829f92017-04-07 19:04:42 -07001676 if (stream == AUDIO_STREAM_MUSIC) {
1677 selectOutputForMusicEffects();
1678 }
Eric Laurente552edb2014-03-10 17:42:56 -07001679 return NO_ERROR;
1680 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001681 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001682 return INVALID_OPERATION;
1683 }
1684}
1685
Eric Laurent8fc147b2018-07-22 19:13:55 -07001686void AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001687{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001688 ALOGV("%s portId %d", __FUNCTION__, portId);
1689
1690 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1691 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07001692 // If an output descriptor is closed due to a device routing change,
1693 // then there are race conditions with releaseOutput from tracks
1694 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
1695 // destroyed shortly thereafter.
1696 //
1697 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07001698 ALOGW("releaseOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001699 return;
1700 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001701
1702 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001703
Eric Laurent8fc147b2018-07-22 19:13:55 -07001704 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1705 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001706 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07001707 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001708 return;
1709 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001710 if (--outputDesc->mDirectOpenCount == 0) {
1711 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07001712 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001713 }
1714 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001715 // stopOutput() needs to be successfully called before releaseOutput()
1716 // otherwise there may be inaccurate stream reference counts.
1717 // This is checked in outputDesc->removeClient below.
1718 outputDesc->removeClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001719}
1720
Eric Laurentcaf7f482014-11-25 17:50:47 -08001721status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1722 audio_io_handle_t *input,
1723 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001724 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001725 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001726 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001727 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001728 input_type_t *inputType,
1729 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001730{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001731 ALOGV("getInputForAttr() source %d, sampling rate %d, format %#x, channel mask %#x,"
Eric Laurentcaf7f482014-11-25 17:50:47 -08001732 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001733 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001734
Eric Laurentad2e7b92017-09-14 20:06:42 -07001735 status_t status = NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -08001736 // handle legacy remote submix case where the address was not always specified
1737 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001738 audio_source_t halInputSource;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001739 audio_source_t inputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001740 AudioMix *policyMix = NULL;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001741 DeviceVector inputDevices;
Eric Laurent8fc147b2018-07-22 19:13:55 -07001742 sp<AudioInputDescriptor> inputDesc;
1743 sp<RecordClientDescriptor> clientDesc;
1744 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001745 bool isSoundTrigger;
1746 audio_devices_t device;
1747
1748 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1749 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1750 return INVALID_OPERATION;
1751 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001752
Eric Laurentfe231122017-11-17 17:48:06 -08001753 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1754 inputSource = AUDIO_SOURCE_MIC;
1755 }
1756
Paul McLean466dc8e2015-04-17 13:15:36 -06001757 // Explicit routing?
1758 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -07001759 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
jiabinc0c831a2018-01-29 17:55:15 -08001760 deviceDesc = mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001761 }
Paul McLean466dc8e2015-04-17 13:15:36 -06001762
Eric Laurentad2e7b92017-09-14 20:06:42 -07001763 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1764 // possible
1765 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1766 *input != AUDIO_IO_HANDLE_NONE) {
1767 ssize_t index = mInputs.indexOfKey(*input);
1768 if (index < 0) {
1769 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1770 status = BAD_VALUE;
1771 goto error;
1772 }
1773 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001774 RecordClientVector clients = inputDesc->getClientsForSession(session);
1775 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001776 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1777 status = BAD_VALUE;
1778 goto error;
1779 }
1780 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1781 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001782 // corresponds to a new client and is only permitted from the same UID.
1783 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07001784 if (clients.size() > 1) {
1785 for (const auto& client : clients) {
1786 // The client map is ordered by key values (portId) and portIds are allocated
1787 // incrementaly. So the first client in this list is the one opened by audio flinger
1788 // when the mmap stream is created and should be ignored as it does not correspond
1789 // to an actual client
1790 if (client == *clients.cbegin()) {
1791 continue;
1792 }
1793 if (uid != client->uid() && !client->isSilenced()) {
1794 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
1795 uid, client->portId(), client->uid());
1796 status = INVALID_OPERATION;
1797 goto error;
1798 }
Eric Laurent331679c2018-04-16 17:03:16 -07001799 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001800 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001801 *inputType = API_INPUT_LEGACY;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001802 device = inputDesc->mDevice;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001803
Eric Laurent8f42ea12018-08-08 09:08:25 -07001804 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001805 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001806 }
1807
1808 *input = AUDIO_IO_HANDLE_NONE;
1809 *inputType = API_INPUT_INVALID;
1810
Eric Laurentad2e7b92017-09-14 20:06:42 -07001811 halInputSource = inputSource;
1812
Eric Laurentc447ded2015-01-06 08:47:05 -08001813 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001814 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001815 status = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
1816 if (status != NO_ERROR) {
1817 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001818 }
1819 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001820 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1821 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001822 } else {
Eric Laurent97ac8712018-07-27 18:59:02 -07001823 if (deviceDesc != 0) {
1824 device = deviceDesc->type();
1825 } else {
1826 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
1827 }
Eric Laurent275e8e92014-11-30 15:14:47 -08001828 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001829 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001830 status = BAD_VALUE;
1831 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001832 }
Eric Laurentc722f302014-12-10 11:21:49 -08001833 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001834 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001835 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1836 // there is an external policy, but this input is attached to a mix of recorders,
1837 // meaning it receives audio injected into the framework, so the recorder doesn't
1838 // know about it and is therefore considered "legacy"
1839 *inputType = API_INPUT_LEGACY;
1840 } else {
1841 // recording a mix of players defined by an external policy, we're rerouting for
1842 // an external policy
1843 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1844 }
Eric Laurentc722f302014-12-10 11:21:49 -08001845 } else if (audio_is_remote_submix_device(device)) {
1846 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001847 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001848 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1849 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001850 } else {
1851 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001852 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001853
Eric Laurent599c7582015-12-07 18:05:55 -08001854 }
1855
Eric Laurent8f42ea12018-08-08 09:08:25 -07001856 *input = getInputForDevice(device, address, session, inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001857 config, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001858 policyMix);
1859 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001860 status = INVALID_OPERATION;
1861 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001862 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001863
Eric Laurent8f42ea12018-08-08 09:08:25 -07001864exit:
1865
Mikhail Naganov708e0382018-05-30 09:53:04 -07001866 inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -07001867 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
Eric Laurent8f42ea12018-08-08 09:08:25 -07001868 : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07001869
Eric Laurent8f42ea12018-08-08 09:08:25 -07001870 isSoundTrigger = inputSource == AUDIO_SOURCE_HOTWORD &&
1871 mSoundTriggerSessions.indexOfKey(session) > 0;
1872 *portId = AudioPort::getNextUniqueId();
1873
Eric Laurent8fc147b2018-07-22 19:13:55 -07001874 clientDesc = new RecordClientDescriptor(*portId, uid, session,
Eric Laurent8f42ea12018-08-08 09:08:25 -07001875 *attr, *config, requestedDeviceId,
1876 inputSource,flags, isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001877 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07001878 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001879
1880 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
1881 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001882
Eric Laurent599c7582015-12-07 18:05:55 -08001883 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001884
1885error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07001886 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001887}
1888
1889
1890audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1891 String8 address,
1892 audio_session_t session,
Eric Laurent599c7582015-12-07 18:05:55 -08001893 audio_source_t inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001894 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08001895 audio_input_flags_t flags,
1896 AudioMix *policyMix)
1897{
1898 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1899 audio_source_t halInputSource = inputSource;
1900 bool isSoundTrigger = false;
1901
1902 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1903 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1904 if (index >= 0) {
1905 input = mSoundTriggerSessions.valueFor(session);
1906 isSoundTrigger = true;
1907 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1908 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1909 } else {
1910 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001911 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001912 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08001913 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001914 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001915 }
1916
Andy Hungf129b032015-04-07 13:45:50 -07001917 // find a compatible input profile (not necessarily identical in parameters)
1918 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08001919 // sampling rate and flags may be updated by getInputProfile
1920 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
1921 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07001922 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08001923 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07001924 audio_input_flags_t profileFlags = flags;
1925 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07001926 profileFormat = config->format; // reset each time through loop, in case it is updated
Eric Laurent275e8e92014-11-30 15:14:47 -08001927 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001928 profileSamplingRate, profileFormat, profileChannelMask,
1929 profileFlags);
1930 if (profile != 0) {
1931 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001932 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1933 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001934 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1935 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1936 } else { // fail
Glenn Kastenfaa10a62017-05-25 15:52:05 -07001937 ALOGW("getInputForDevice() could not find profile for device 0x%X, "
Eric Laurentfe231122017-11-17 17:48:06 -08001938 "sampling rate %u, format %#x, channel mask 0x%X, flags %#x",
1939 device, config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001940 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001941 }
Eric Laurente552edb2014-03-10 17:42:56 -07001942 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001943 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08001944 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08001945 if (samplingRate == 0) {
1946 samplingRate = profileSamplingRate;
1947 }
Eric Laurente552edb2014-03-10 17:42:56 -07001948
Eric Laurent322b4d22015-04-03 15:57:54 -07001949 if (profile->getModuleHandle() == 0) {
1950 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001951 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001952 }
1953
Eric Laurent3974e3b2017-12-07 17:58:43 -08001954 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001955 for (size_t i = 0; i < mInputs.size(); ) {
1956 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
1957 if (desc->mProfile != profile) {
1958 continue;
1959 }
1960 // if sound trigger, reuse input if used by other sound trigger on same session
1961 // else
1962 // reuse input if active client app is not in IDLE state
1963 //
1964 RecordClientVector clients = desc->clientsList();
1965 bool doClose = false;
1966 for (const auto& client : clients) {
1967 if (isSoundTrigger != client->isSoundTrigger()) {
1968 continue;
1969 }
1970 if (client->isSoundTrigger()) {
1971 if (session == client->session()) {
1972 return desc->mIoHandle;
1973 }
1974 continue;
1975 }
1976 if (client->active() && client->appState() != APP_STATE_IDLE) {
1977 return desc->mIoHandle;
1978 }
1979 doClose = true;
1980 }
1981 if (doClose) {
1982 closeInput(desc->mIoHandle);
1983 } else {
1984 i++;
1985 }
1986 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08001987 }
1988
Eric Laurentfe231122017-11-17 17:48:06 -08001989 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001990
Eric Laurentfe231122017-11-17 17:48:06 -08001991 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
1992 lConfig.sample_rate = profileSamplingRate;
1993 lConfig.channel_mask = profileChannelMask;
1994 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07001995
Eric Laurent53b810e2017-12-10 17:25:10 -08001996 if (address == "") {
Mikhail Naganov708e0382018-05-30 09:53:04 -07001997 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -08001998 // the inputs vector must be of size >= 1, but we don't want to crash here
1999 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress : String8("");
2000 }
2001
Eric Laurentfe231122017-11-17 17:48:06 -08002002 status_t status = inputDesc->open(&lConfig, device, address,
2003 halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002004
2005 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002006 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002007 (profileSamplingRate != lConfig.sample_rate) ||
2008 !audio_formats_match(profileFormat, lConfig.format) ||
2009 (profileChannelMask != lConfig.channel_mask)) {
2010 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002011 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002012 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002013 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002014 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002015 }
Eric Laurent599c7582015-12-07 18:05:55 -08002016 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002017 }
2018
Eric Laurentc722f302014-12-10 11:21:49 -08002019 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002020
Eric Laurent599c7582015-12-07 18:05:55 -08002021 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002022 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002023
Eric Laurent599c7582015-12-07 18:05:55 -08002024 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002025}
2026
Eric Laurent4eb58f12018-12-07 16:41:02 -08002027status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002028{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002029 ALOGV("%s portId %d", __FUNCTION__, portId);
2030
2031 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2032 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002033 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002034 return BAD_VALUE;
2035 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002036 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002037 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002038 if (client->active()) {
2039 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2040 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002041 }
2042
Eric Laurent8f42ea12018-08-08 09:08:25 -07002043 audio_session_t session = client->session();
2044
Eric Laurent4eb58f12018-12-07 16:41:02 -08002045 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002046
Eric Laurent4eb58f12018-12-07 16:41:02 -08002047 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002048
Eric Laurent4eb58f12018-12-07 16:41:02 -08002049 status_t status = inputDesc->start();
2050 if (status != NO_ERROR) {
2051 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002052 }
Eric Laurente552edb2014-03-10 17:42:56 -07002053
Eric Laurent4eb58f12018-12-07 16:41:02 -08002054 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002055 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002056 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002057
Eric Laurent8f42ea12018-08-08 09:08:25 -07002058 // indicate active capture to sound trigger service if starting capture from a mic on
2059 // primary HW module
2060 audio_devices_t device = getNewInputDevice(inputDesc);
2061 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002062
Eric Laurent8f42ea12018-08-08 09:08:25 -07002063 if (inputDesc->activeCount() == 1) {
2064 // if input maps to a dynamic policy with an activity listener, notify of state change
2065 if ((inputDesc->mPolicyMix != NULL)
2066 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2067 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2068 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002069 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002070
Eric Laurent8f42ea12018-08-08 09:08:25 -07002071 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2072 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2073 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
2074 SoundTrigger::setCaptureState(true);
2075 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002076
Eric Laurent8f42ea12018-08-08 09:08:25 -07002077 // automatically enable the remote submix output when input is started if not
2078 // used by a policy mix of type MIX_TYPE_RECORDERS
2079 // For remote submix (a virtual device), we open only one input per capture request.
2080 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2081 String8 address = String8("");
2082 if (inputDesc->mPolicyMix == NULL) {
2083 address = String8("0");
2084 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2085 address = inputDesc->mPolicyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002086 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002087 if (address != "") {
2088 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2089 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2090 address, "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08002091 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002092 }
Eric Laurente552edb2014-03-10 17:42:56 -07002093 }
2094
Eric Laurent8f42ea12018-08-08 09:08:25 -07002095 ALOGV("%s input %d source = %d exit", __FUNCTION__, input, client->source());
Eric Laurente552edb2014-03-10 17:42:56 -07002096
Eric Laurente552edb2014-03-10 17:42:56 -07002097 return NO_ERROR;
2098}
2099
Eric Laurent8fc147b2018-07-22 19:13:55 -07002100status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002101{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002102 ALOGV("%s portId %d", __FUNCTION__, portId);
2103
2104 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2105 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002106 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002107 return BAD_VALUE;
2108 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002109 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002110 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002111 if (!client->active()) {
2112 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002113 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002114 }
2115
Eric Laurent8f42ea12018-08-08 09:08:25 -07002116 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002117
Eric Laurent8f42ea12018-08-08 09:08:25 -07002118 inputDesc->stop();
2119 if (inputDesc->isActive()) {
2120 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2121 } else {
2122 // if input maps to a dynamic policy with an activity listener, notify of state change
2123 if ((inputDesc->mPolicyMix != NULL)
2124 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2125 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2126 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002127 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002128
2129 // automatically disable the remote submix output when input is stopped if not
2130 // used by a policy mix of type MIX_TYPE_RECORDERS
2131 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2132 String8 address = String8("");
2133 if (inputDesc->mPolicyMix == NULL) {
2134 address = String8("0");
2135 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2136 address = inputDesc->mPolicyMix->mDeviceAddress;
2137 }
2138 if (address != "") {
2139 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2140 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2141 address, "remote-submix");
2142 }
2143 }
2144
2145 audio_devices_t device = inputDesc->mDevice;
2146 resetInputDevice(input);
2147
2148 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2149 // primary HW module
2150 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2151 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2152 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
2153 SoundTrigger::setCaptureState(false);
2154 }
2155 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002156 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002157 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002158}
2159
Eric Laurent8fc147b2018-07-22 19:13:55 -07002160void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002161{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002162 ALOGV("%s portId %d", __FUNCTION__, portId);
2163
2164 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2165 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002166 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002167 return;
2168 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002169 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002170 audio_io_handle_t input = inputDesc->mIoHandle;
2171
Eric Laurent8f42ea12018-08-08 09:08:25 -07002172 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002173
Andy Hung39efb7a2018-09-26 15:39:28 -07002174 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002175
Andy Hung39efb7a2018-09-26 15:39:28 -07002176 if (inputDesc->getClientCount() > 0) {
2177 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002178 return;
2179 }
2180
Eric Laurent05b90f82014-08-27 15:32:29 -07002181 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002182 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002183 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002184}
2185
Eric Laurent8f42ea12018-08-08 09:08:25 -07002186void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002187{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002188 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002189
2190 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002191 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002192 }
2193}
2194
Eric Laurent8f42ea12018-08-08 09:08:25 -07002195void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2196{
2197 stopInput(portId);
2198 releaseInput(portId);
2199}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002200
Eric Laurentd4692962014-05-05 18:13:44 -07002201void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002202 bool patchRemoved = false;
2203
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002204 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002205 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002206 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002207 if (patch_index >= 0) {
2208 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002209 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002210 mAudioPatches.removeItemsAt(patch_index);
2211 patchRemoved = true;
2212 }
Eric Laurentfe231122017-11-17 17:48:06 -08002213 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002214 }
2215 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002216 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002217 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002218
2219 if (patchRemoved) {
2220 mpClientInterface->onAudioPatchListUpdate();
2221 }
Eric Laurentd4692962014-05-05 18:13:44 -07002222}
2223
Eric Laurente0720872014-03-11 09:30:41 -07002224void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002225 int indexMin,
2226 int indexMax)
2227{
2228 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002229 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002230
2231 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002232 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2233 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002234 continue;
2235 }
2236 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002237 }
Eric Laurente552edb2014-03-10 17:42:56 -07002238}
2239
Eric Laurente0720872014-03-11 09:30:41 -07002240status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002241 int index,
2242 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002243{
2244
Nadav Bar7c605f62017-12-25 00:01:52 +02002245 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2246 // app that has MODIFY_PHONE_STATE permission.
2247 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
2248 !(stream == AUDIO_STREAM_VOICE_CALL && index == 0)) ||
François Gaffied1ab2bd2015-12-02 18:20:06 +01002249 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002250 return BAD_VALUE;
2251 }
2252 if (!audio_is_output_device(device)) {
2253 return BAD_VALUE;
2254 }
2255
2256 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002257 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002258
Eric Laurent1fd372e2016-04-06 14:23:53 -07002259 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002260 stream, device, index);
2261
Eric Laurent28d09f02016-03-08 10:43:05 -08002262 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002263 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2264 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002265 continue;
2266 }
2267 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2268 }
Eric Laurente552edb2014-03-10 17:42:56 -07002269
Eric Laurent1fd372e2016-04-06 14:23:53 -07002270 // update volume on all outputs and streams matching the following:
2271 // - The requested stream (or a stream matching for volume control) is active on the output
2272 // - The device (or devices) selected by the strategy corresponding to this stream includes
2273 // the requested device
2274 // - For non default requested device, currently selected device on the output is either the
2275 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002276 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2277 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002278 status_t status = NO_ERROR;
2279 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002280 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
nobuaki tanaka985d15a2017-07-19 13:38:51 +09002281 audio_devices_t curDevice = desc->device();
Eric Laurent794fde22016-03-11 09:50:45 -08002282 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
Eric Laurent3839bc02018-07-10 18:33:34 -07002283 if (!(streamsMatchForvolume(stream, (audio_stream_type_t)curStream))) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002284 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002285 }
Eric Laurentdcd4ab12018-06-29 17:45:13 -07002286 if (!(desc->isStreamActive((audio_stream_type_t)curStream) || isInCall())) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002287 continue;
2288 }
Eric Laurent794fde22016-03-11 09:50:45 -08002289 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002290 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2291 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002292 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2293 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002294 continue;
2295 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002296 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002297 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002298 curStreamDevice |= device;
nobuaki tanaka985d15a2017-07-19 13:38:51 +09002299 applyVolume = (Volume::getDeviceForVolume(curDevice) & curStreamDevice) != 0;
Eric Laurente76f29c2016-09-14 17:17:53 -07002300 } else {
2301 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002302 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002303 }
Eric Laurent3839bc02018-07-10 18:33:34 -07002304 // rescale index before applying to curStream as ranges may be different for
2305 // stream and curStream
2306 int idx = rescaleVolumeIndex(index, stream, (audio_stream_type_t)curStream);
Eric Laurente76f29c2016-09-14 17:17:53 -07002307 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002308 //FIXME: workaround for truncated touch sounds
2309 // delayed volume change for system stream to be removed when the problem is
2310 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002311 status_t volStatus =
Eric Laurent3839bc02018-07-10 18:33:34 -07002312 checkAndSetVolume((audio_stream_type_t)curStream, idx, desc, curDevice,
Eric Laurentdc462862016-07-19 12:29:53 -07002313 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002314 if (volStatus != NO_ERROR) {
2315 status = volStatus;
2316 }
2317 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002318 }
Eric Laurente552edb2014-03-10 17:42:56 -07002319 }
2320 return status;
2321}
2322
Eric Laurente0720872014-03-11 09:30:41 -07002323status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002324 int *index,
2325 audio_devices_t device)
2326{
2327 if (index == NULL) {
2328 return BAD_VALUE;
2329 }
2330 if (!audio_is_output_device(device)) {
2331 return BAD_VALUE;
2332 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002333 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002334 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002335 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002336 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2337 }
François Gaffiedfd74092015-03-19 12:10:59 +01002338 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002339
François Gaffied1ab2bd2015-12-02 18:20:06 +01002340 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002341 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2342 return NO_ERROR;
2343}
2344
Eric Laurent36829f92017-04-07 19:04:42 -07002345audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002346{
2347 // select one output among several suitable for global effects.
2348 // The priority is as follows:
2349 // 1: An offloaded output. If the effect ends up not being offloadable,
2350 // AudioFlinger will invalidate the track and the offloaded output
2351 // will be closed causing the effect to be moved to a PCM output.
2352 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002353 // 3: The primary output
2354 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002355
Eric Laurent3b73df72014-03-11 09:06:29 -07002356 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002357 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent36829f92017-04-07 19:04:42 -07002358 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002359
Eric Laurent36829f92017-04-07 19:04:42 -07002360 if (outputs.size() == 0) {
2361 return AUDIO_IO_HANDLE_NONE;
2362 }
Eric Laurente552edb2014-03-10 17:42:56 -07002363
Eric Laurent36829f92017-04-07 19:04:42 -07002364 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2365 bool activeOnly = true;
2366
2367 while (output == AUDIO_IO_HANDLE_NONE) {
2368 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2369 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2370 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2371
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002372 for (audio_io_handle_t output : outputs) {
2373 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002374 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2375 continue;
2376 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002377 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2378 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002379 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002380 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002381 }
2382 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002383 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002384 }
2385 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002386 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002387 }
2388 }
2389 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2390 output = outputOffloaded;
2391 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2392 output = outputDeepBuffer;
2393 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2394 output = outputPrimary;
2395 } else {
2396 output = outputs[0];
2397 }
2398 activeOnly = false;
2399 }
2400
2401 if (output != mMusicEffectOutput) {
2402 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2403 mMusicEffectOutput = output;
2404 }
2405
2406 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002407 return output;
2408}
2409
Eric Laurent36829f92017-04-07 19:04:42 -07002410audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2411{
2412 return selectOutputForMusicEffects();
2413}
2414
Eric Laurente0720872014-03-11 09:30:41 -07002415status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002416 audio_io_handle_t io,
2417 uint32_t strategy,
2418 int session,
2419 int id)
2420{
2421 ssize_t index = mOutputs.indexOfKey(io);
2422 if (index < 0) {
2423 index = mInputs.indexOfKey(io);
2424 if (index < 0) {
2425 ALOGW("registerEffect() unknown io %d", io);
2426 return INVALID_OPERATION;
2427 }
2428 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002429 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002430}
2431
Eric Laurentc75307b2015-03-17 15:29:32 -07002432bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2433{
Eric Laurent28d09f02016-03-08 10:43:05 -08002434 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002435 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2436 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002437 continue;
2438 }
2439 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2440 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002441 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002442}
2443
2444bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2445{
2446 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2447}
2448
Eric Laurente0720872014-03-11 09:30:41 -07002449bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002450{
2451 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002452 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002453 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002454 return true;
2455 }
2456 }
2457 return false;
2458}
2459
Eric Laurent275e8e92014-11-30 15:14:47 -08002460// Register a list of custom mixes with their attributes and format.
2461// When a mix is registered, corresponding input and output profiles are
2462// added to the remote submix hw module. The profile contains only the
2463// parameters (sampling rate, format...) specified by the mix.
2464// The corresponding input remote submix device is also connected.
2465//
2466// When a remote submix device is connected, the address is checked to select the
2467// appropriate profile and the corresponding input or output stream is opened.
2468//
2469// When capture starts, getInputForAttr() will:
2470// - 1 look for a mix matching the address passed in attribtutes tags if any
2471// - 2 if none found, getDeviceForInputSource() will:
2472// - 2.1 look for a mix matching the attributes source
2473// - 2.2 if none found, default to device selection by policy rules
2474// At this time, the corresponding output remote submix device is also connected
2475// and active playback use cases can be transferred to this mix if needed when reconnecting
2476// after AudioTracks are invalidated
2477//
2478// When playback starts, getOutputForAttr() will:
2479// - 1 look for a mix matching the address passed in attribtutes tags if any
2480// - 2 if none found, look for a mix matching the attributes usage
2481// - 3 if none found, default to device and output selection by policy rules.
2482
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002483status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002484{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002485 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2486 status_t res = NO_ERROR;
2487
2488 sp<HwModule> rSubmixModule;
2489 // examine each mix's route type
2490 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002491 AudioMix mix = mixes[i];
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002492 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
Eric Laurent97ac8712018-07-27 18:59:02 -07002493 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002494 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002495 break;
2496 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002497 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002498 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002499 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002500 rSubmixModule = mHwModules.getModuleFromName(
2501 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2502 if (rSubmixModule == 0) {
2503 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2504 i);
2505 res = INVALID_OPERATION;
2506 break;
2507 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002508 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002509
Eric Laurent97ac8712018-07-27 18:59:02 -07002510 String8 address = mix.mDeviceAddress;
2511 if (mix.mMixType == MIX_TYPE_PLAYERS) {
2512 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2513 } else {
2514 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
2515 }
François Gaffie036e1e92015-03-19 10:16:24 +01002516
Eric Laurent97ac8712018-07-27 18:59:02 -07002517 if (mPolicyMixes.registerMix(address, mix, 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002518 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002519 res = INVALID_OPERATION;
2520 break;
2521 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002522 audio_config_t outputConfig = mix.mFormat;
2523 audio_config_t inputConfig = mix.mFormat;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002524 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2525 // stereo and let audio flinger do the channel conversion if needed.
2526 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2527 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2528 rSubmixModule->addOutputProfile(address, &outputConfig,
2529 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2530 rSubmixModule->addInputProfile(address, &inputConfig,
2531 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002532
Eric Laurent97ac8712018-07-27 18:59:02 -07002533 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002534 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2535 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2536 address.string(), "remote-submix");
2537 } else {
2538 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2539 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2540 address.string(), "remote-submix");
2541 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002542 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2543 String8 address = mix.mDeviceAddress;
2544 audio_devices_t device = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002545 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2546 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002547
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002548 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002549 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2550 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2551 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2552 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2553 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2554 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002555 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2556 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002557 if (mPolicyMixes.registerMix(address, mix, desc) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002558 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002559 } else {
2560 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002561 }
2562 break;
2563 }
2564 }
2565
2566 if (res != NO_ERROR) {
2567 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002568 i, device, address.string());
2569 res = INVALID_OPERATION;
2570 break;
2571 } else if (!foundOutput) {
2572 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2573 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002574 res = INVALID_OPERATION;
2575 break;
2576 }
Eric Laurentc722f302014-12-10 11:21:49 -08002577 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002578 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002579 if (res != NO_ERROR) {
2580 unregisterPolicyMixes(mixes);
2581 }
2582 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002583}
2584
2585status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2586{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002587 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002588 status_t res = NO_ERROR;
2589 sp<HwModule> rSubmixModule;
2590 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002591 for (const auto& mix : mixes) {
2592 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002593
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002594 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002595 rSubmixModule = mHwModules.getModuleFromName(
2596 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2597 if (rSubmixModule == 0) {
2598 res = INVALID_OPERATION;
2599 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002600 }
2601 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002602
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002603 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002604
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002605 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2606 res = INVALID_OPERATION;
2607 continue;
2608 }
2609
2610 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2611 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2612 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2613 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2614 address.string(), "remote-submix");
2615 }
2616 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2617 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2618 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2619 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2620 address.string(), "remote-submix");
2621 }
2622 rSubmixModule->removeOutputProfile(address);
2623 rSubmixModule->removeInputProfile(address);
2624
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002625 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2626 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002627 res = INVALID_OPERATION;
2628 continue;
2629 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002630 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002631 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002632 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002633}
2634
Mikhail Naganov100f0122018-11-29 11:22:16 -08002635void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
2636{
2637 size_t i = 0;
2638 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
2639 for (const auto& fmt : mManualSurroundFormats) {
2640 if (i++ != 0) dst->append(", ");
2641 std::string sfmt;
2642 FormatConverter::toString(fmt, sfmt);
2643 dst->append(sfmt.size() >= audioFormatPrefixLen ?
2644 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
2645 }
2646}
2647
Andy Hungc29d82b2018-10-05 12:23:17 -07002648void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07002649{
Andy Hungc29d82b2018-10-05 12:23:17 -07002650 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
2651 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07002652 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002653 std::string stateLiteral;
2654 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07002655 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002656 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
2657 "communications", "media", "record", "dock", "system",
2658 "HDMI system audio", "encoded surround output", "vibrate ringing" };
2659 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
2660 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08002661 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
2662 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
2663 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
2664 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
2665 dst->append(" (MANUAL: ");
2666 dumpManualSurroundFormats(dst);
2667 dst->append(")");
2668 }
2669 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002670 }
Andy Hungc29d82b2018-10-05 12:23:17 -07002671 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
2672 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
2673 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
2674 mAvailableOutputDevices.dump(dst, String8("Available output"));
2675 mAvailableInputDevices.dump(dst, String8("Available input"));
2676 mHwModulesAll.dump(dst);
2677 mOutputs.dump(dst);
2678 mInputs.dump(dst);
2679 mVolumeCurves->dump(dst);
2680 mEffects.dump(dst);
2681 mAudioPatches.dump(dst);
2682 mPolicyMixes.dump(dst);
2683 mAudioSources.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07002684}
2685
2686status_t AudioPolicyManager::dump(int fd)
2687{
2688 String8 result;
2689 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07002690 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002691 return NO_ERROR;
2692}
2693
2694// This function checks for the parameters which can be offloaded.
2695// This can be enhanced depending on the capability of the DSP and policy
2696// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002697bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002698{
2699 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002700 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002701 offloadInfo.sample_rate, offloadInfo.channel_mask,
2702 offloadInfo.format,
2703 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2704 offloadInfo.has_video);
2705
Andy Hung2ddee192015-12-18 17:34:44 -08002706 if (mMasterMono) {
2707 return false; // no offloading if mono is set.
2708 }
2709
Eric Laurente552edb2014-03-10 17:42:56 -07002710 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07002711 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
2712 ALOGV("offload disabled by audio.offload.disable");
2713 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002714 }
2715
2716 // Check if stream type is music, then only allow offload as of now.
2717 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2718 {
2719 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2720 return false;
2721 }
2722
2723 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002724 const bool allowOffloadWithVideo =
2725 property_get_bool("audio.offload.video", false /* default_value */);
2726 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002727 ALOGV("isOffloadSupported: has_video == true, returning false");
2728 return false;
2729 }
2730
2731 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07002732 const int min_duration_secs = property_get_int32(
2733 "audio.offload.min.duration.secs", -1 /* default_value */);
2734 if (min_duration_secs >= 0) {
2735 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
2736 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%d)",
2737 min_duration_secs);
Eric Laurente552edb2014-03-10 17:42:56 -07002738 return false;
2739 }
2740 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2741 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2742 return false;
2743 }
2744
2745 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2746 // creating an offloaded track and tearing it down immediately after start when audioflinger
2747 // detects there is an active non offloadable effect.
2748 // FIXME: We should check the audio session here but we do not have it in this context.
2749 // This may prevent offloading in rare situations where effects are left active by apps
2750 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002751 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002752 return false;
2753 }
2754
2755 // See if there is a profile to support this.
2756 // AUDIO_DEVICE_NONE
Michael Chana94fbb22018-04-24 14:31:19 +10002757 sp<IOProfile> profile = getProfileForOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002758 offloadInfo.sample_rate,
2759 offloadInfo.format,
2760 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10002761 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
2762 true /* directOnly */);
Eric Laurent1c333e22014-05-20 10:48:17 -07002763 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2764 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002765}
2766
Michael Chana94fbb22018-04-24 14:31:19 +10002767bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
2768 const audio_attributes_t& attributes) {
2769 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
2770 audio_attributes_flags_to_audio_output_flags(attributes.flags, output_flags);
2771 sp<IOProfile> profile = getProfileForOutput(AUDIO_DEVICE_NONE /*ignore device */,
2772 config.sample_rate,
2773 config.format,
2774 config.channel_mask,
2775 output_flags,
2776 true /* directOnly */);
2777 ALOGV("%s() profile %sfound with name: %s, "
2778 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
2779 __FUNCTION__, profile != 0 ? "" : "NOT ",
2780 (profile != 0 ? profile->getTagName().string() : "null"),
2781 config.sample_rate, config.format, config.channel_mask, output_flags);
2782 return (profile != 0);
2783}
2784
Eric Laurent6a94d692014-05-20 11:18:06 -07002785status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2786 audio_port_type_t type,
2787 unsigned int *num_ports,
2788 struct audio_port *ports,
2789 unsigned int *generation)
2790{
2791 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2792 generation == NULL) {
2793 return BAD_VALUE;
2794 }
2795 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2796 if (ports == NULL) {
2797 *num_ports = 0;
2798 }
2799
2800 size_t portsWritten = 0;
2801 size_t portsMax = *num_ports;
2802 *num_ports = 0;
2803 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002804 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2805 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002806 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002807 for (const auto& dev : mAvailableOutputDevices) {
2808 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002809 continue;
2810 }
2811 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002812 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002813 }
2814 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002815 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002816 }
2817 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002818 for (const auto& dev : mAvailableInputDevices) {
2819 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002820 continue;
2821 }
2822 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002823 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002824 }
2825 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002826 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002827 }
2828 }
2829 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2830 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2831 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2832 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2833 }
2834 *num_ports += mInputs.size();
2835 }
2836 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002837 size_t numOutputs = 0;
2838 for (size_t i = 0; i < mOutputs.size(); i++) {
2839 if (!mOutputs[i]->isDuplicated()) {
2840 numOutputs++;
2841 if (portsWritten < portsMax) {
2842 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2843 }
2844 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002845 }
Eric Laurent84c70242014-06-23 08:46:27 -07002846 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002847 }
2848 }
2849 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002850 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002851 return NO_ERROR;
2852}
2853
Eric Laurent99fcae42018-05-17 16:59:18 -07002854status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07002855{
Eric Laurent99fcae42018-05-17 16:59:18 -07002856 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
2857 return BAD_VALUE;
2858 }
2859 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
2860 if (dev != 0) {
2861 dev->toAudioPort(port);
2862 return NO_ERROR;
2863 }
2864 dev = mAvailableInputDevices.getDeviceFromId(port->id);
2865 if (dev != 0) {
2866 dev->toAudioPort(port);
2867 return NO_ERROR;
2868 }
2869 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
2870 if (out != 0) {
2871 out->toAudioPort(port);
2872 return NO_ERROR;
2873 }
2874 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
2875 if (in != 0) {
2876 in->toAudioPort(port);
2877 return NO_ERROR;
2878 }
2879 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002880}
2881
Eric Laurent6a94d692014-05-20 11:18:06 -07002882status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2883 audio_patch_handle_t *handle,
2884 uid_t uid)
2885{
2886 ALOGV("createAudioPatch()");
2887
2888 if (handle == NULL || patch == NULL) {
2889 return BAD_VALUE;
2890 }
2891 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2892
Mikhail Naganovac9858b2018-06-15 13:12:37 -07002893 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07002894 return BAD_VALUE;
2895 }
2896 // only one source per audio patch supported for now
2897 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002898 return INVALID_OPERATION;
2899 }
Eric Laurent874c42872014-08-08 15:13:39 -07002900
2901 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002902 return INVALID_OPERATION;
2903 }
Eric Laurent874c42872014-08-08 15:13:39 -07002904 for (size_t i = 0; i < patch->num_sinks; i++) {
2905 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2906 return INVALID_OPERATION;
2907 }
2908 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002909
2910 sp<AudioPatch> patchDesc;
2911 ssize_t index = mAudioPatches.indexOfKey(*handle);
2912
Eric Laurent6a94d692014-05-20 11:18:06 -07002913 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2914 patch->sources[0].role,
2915 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002916#if LOG_NDEBUG == 0
2917 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002918 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002919 patch->sinks[i].role,
2920 patch->sinks[i].type);
2921 }
2922#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002923
2924 if (index >= 0) {
2925 patchDesc = mAudioPatches.valueAt(index);
2926 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2927 mUidCached, patchDesc->mUid, uid);
2928 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2929 return INVALID_OPERATION;
2930 }
2931 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002932 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002933 }
2934
2935 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002936 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002937 if (outputDesc == NULL) {
2938 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2939 return BAD_VALUE;
2940 }
Eric Laurent84c70242014-06-23 08:46:27 -07002941 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2942 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002943 if (patchDesc != 0) {
2944 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2945 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2946 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2947 return BAD_VALUE;
2948 }
2949 }
Eric Laurent874c42872014-08-08 15:13:39 -07002950 DeviceVector devices;
2951 for (size_t i = 0; i < patch->num_sinks; i++) {
2952 // Only support mix to devices connection
2953 // TODO add support for mix to mix connection
2954 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2955 ALOGV("createAudioPatch() source mix but sink is not a device");
2956 return INVALID_OPERATION;
2957 }
2958 sp<DeviceDescriptor> devDesc =
2959 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2960 if (devDesc == 0) {
2961 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2962 return BAD_VALUE;
2963 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002964
François Gaffie53615e22015-03-19 09:24:12 +01002965 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002966 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002967 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002968 NULL, // updatedSamplingRate
2969 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002970 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002971 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002972 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002973 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002974 ALOGV("createAudioPatch() profile not supported for device %08x",
2975 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002976 return INVALID_OPERATION;
2977 }
2978 devices.add(devDesc);
2979 }
2980 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002981 return INVALID_OPERATION;
2982 }
Eric Laurent874c42872014-08-08 15:13:39 -07002983
Eric Laurent6a94d692014-05-20 11:18:06 -07002984 // TODO: reconfigure output format and channels here
2985 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002986 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002987 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002988 index = mAudioPatches.indexOfKey(*handle);
2989 if (index >= 0) {
2990 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2991 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2992 }
2993 patchDesc = mAudioPatches.valueAt(index);
2994 patchDesc->mUid = uid;
2995 ALOGV("createAudioPatch() success");
2996 } else {
2997 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2998 return INVALID_OPERATION;
2999 }
3000 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3001 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3002 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003003 // only one sink supported when connecting an input device to a mix
3004 if (patch->num_sinks > 1) {
3005 return INVALID_OPERATION;
3006 }
François Gaffie53615e22015-03-19 09:24:12 +01003007 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003008 if (inputDesc == NULL) {
3009 return BAD_VALUE;
3010 }
3011 if (patchDesc != 0) {
3012 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3013 return BAD_VALUE;
3014 }
3015 }
3016 sp<DeviceDescriptor> devDesc =
3017 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
3018 if (devDesc == 0) {
3019 return BAD_VALUE;
3020 }
3021
François Gaffie53615e22015-03-19 09:24:12 +01003022 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08003023 devDesc->mAddress,
3024 patch->sinks[0].sample_rate,
3025 NULL, /*updatedSampleRate*/
3026 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003027 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003028 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003029 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003030 // FIXME for the parameter type,
3031 // and the NONE
3032 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003033 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003034 return INVALID_OPERATION;
3035 }
3036 // TODO: reconfigure output format and channels here
3037 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01003038 devDesc->type(), inputDesc->mIoHandle);
3039 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003040 index = mAudioPatches.indexOfKey(*handle);
3041 if (index >= 0) {
3042 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3043 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
3044 }
3045 patchDesc = mAudioPatches.valueAt(index);
3046 patchDesc->mUid = uid;
3047 ALOGV("createAudioPatch() success");
3048 } else {
3049 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
3050 return INVALID_OPERATION;
3051 }
3052 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3053 // device to device connection
3054 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003055 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003056 return BAD_VALUE;
3057 }
3058 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003059 sp<DeviceDescriptor> srcDeviceDesc =
3060 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07003061 if (srcDeviceDesc == 0) {
3062 return BAD_VALUE;
3063 }
Eric Laurent874c42872014-08-08 15:13:39 -07003064
Eric Laurent6a94d692014-05-20 11:18:06 -07003065 //update source and sink with our own data as the data passed in the patch may
3066 // be incomplete.
3067 struct audio_patch newPatch = *patch;
3068 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003069
Eric Laurent874c42872014-08-08 15:13:39 -07003070 for (size_t i = 0; i < patch->num_sinks; i++) {
3071 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3072 ALOGV("createAudioPatch() source device but one sink is not a device");
3073 return INVALID_OPERATION;
3074 }
3075
3076 sp<DeviceDescriptor> sinkDeviceDesc =
3077 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3078 if (sinkDeviceDesc == 0) {
3079 return BAD_VALUE;
3080 }
3081 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
3082
Eric Laurent3bcf8592015-04-03 12:13:24 -07003083 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003084 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003085 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02003086 // - audio HAL version is >= 3.0 but no route has been declared between devices
Eric Laurentfb66dd92016-01-28 18:32:03 -08003087 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Francois Gaffie99896da2018-04-09 11:05:33 +02003088 (srcDeviceDesc->mModule->getHalVersionMajor() < 3) ||
3089 !srcDeviceDesc->mModule->supportsPatch(srcDeviceDesc, sinkDeviceDesc)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003090 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003091 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003092 return INVALID_OPERATION;
3093 }
Eric Laurent874c42872014-08-08 15:13:39 -07003094 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01003095 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003096 // if the sink device is reachable via an opened output stream, request to go via
3097 // this output stream by adding a second source to the patch description
jiabin40573322018-11-08 12:08:02 -08003098 audio_io_handle_t output = selectOutput(outputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003099 if (output != AUDIO_IO_HANDLE_NONE) {
3100 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3101 if (outputDesc->isDuplicated()) {
3102 return INVALID_OPERATION;
3103 }
3104 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003105 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003106 newPatch.num_sources = 2;
3107 }
Eric Laurent83b88082014-06-20 18:31:16 -07003108 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003109 }
3110 // TODO: check from routing capabilities in config file and other conflicting patches
3111
Mikhail Naganovdc769682018-05-04 15:34:08 -07003112 status_t status = installPatch(__func__, index, handle, &newPatch, 0, uid, &patchDesc);
3113 if (status != NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003114 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3115 status);
3116 return INVALID_OPERATION;
3117 }
3118 } else {
3119 return BAD_VALUE;
3120 }
3121 } else {
3122 return BAD_VALUE;
3123 }
3124 return NO_ERROR;
3125}
3126
3127status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3128 uid_t uid)
3129{
3130 ALOGV("releaseAudioPatch() patch %d", handle);
3131
3132 ssize_t index = mAudioPatches.indexOfKey(handle);
3133
3134 if (index < 0) {
3135 return BAD_VALUE;
3136 }
3137 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3138 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3139 mUidCached, patchDesc->mUid, uid);
3140 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3141 return INVALID_OPERATION;
3142 }
3143
3144 struct audio_patch *patch = &patchDesc->mPatch;
3145 patchDesc->mUid = mUidCached;
3146 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003147 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003148 if (outputDesc == NULL) {
3149 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3150 return BAD_VALUE;
3151 }
3152
Eric Laurentc75307b2015-03-17 15:29:32 -07003153 setOutputDevice(outputDesc,
3154 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07003155 true,
3156 0,
3157 NULL);
3158 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3159 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003160 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003161 if (inputDesc == NULL) {
3162 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3163 return BAD_VALUE;
3164 }
3165 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003166 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003167 true,
3168 NULL);
3169 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003170 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3171 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3172 status, patchDesc->mAfPatchHandle);
3173 removeAudioPatch(patchDesc->mHandle);
3174 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003175 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003176 } else {
3177 return BAD_VALUE;
3178 }
3179 } else {
3180 return BAD_VALUE;
3181 }
3182 return NO_ERROR;
3183}
3184
3185status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3186 struct audio_patch *patches,
3187 unsigned int *generation)
3188{
François Gaffie53615e22015-03-19 09:24:12 +01003189 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003190 return BAD_VALUE;
3191 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003192 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003193 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003194}
3195
Eric Laurente1715a42014-05-20 11:30:42 -07003196status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003197{
Eric Laurente1715a42014-05-20 11:30:42 -07003198 ALOGV("setAudioPortConfig()");
3199
3200 if (config == NULL) {
3201 return BAD_VALUE;
3202 }
3203 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3204 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003205 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3206 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003207 }
3208
Eric Laurenta121f902014-06-03 13:32:54 -07003209 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003210 if (config->type == AUDIO_PORT_TYPE_MIX) {
3211 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003212 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003213 if (outputDesc == NULL) {
3214 return BAD_VALUE;
3215 }
Eric Laurent84c70242014-06-23 08:46:27 -07003216 ALOG_ASSERT(!outputDesc->isDuplicated(),
3217 "setAudioPortConfig() called on duplicated output %d",
3218 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003219 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003220 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003221 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003222 if (inputDesc == NULL) {
3223 return BAD_VALUE;
3224 }
Eric Laurenta121f902014-06-03 13:32:54 -07003225 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003226 } else {
3227 return BAD_VALUE;
3228 }
3229 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3230 sp<DeviceDescriptor> deviceDesc;
3231 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3232 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3233 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3234 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3235 } else {
3236 return BAD_VALUE;
3237 }
3238 if (deviceDesc == NULL) {
3239 return BAD_VALUE;
3240 }
Eric Laurenta121f902014-06-03 13:32:54 -07003241 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003242 } else {
3243 return BAD_VALUE;
3244 }
3245
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003246 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003247 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3248 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003249 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003250 audioPortConfig->toAudioPortConfig(&newConfig, config);
3251 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003252 }
Eric Laurenta121f902014-06-03 13:32:54 -07003253 if (status != NO_ERROR) {
3254 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003255 }
Eric Laurente1715a42014-05-20 11:30:42 -07003256
3257 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003258}
3259
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003260void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3261{
Eric Laurentd60560a2015-04-10 11:31:20 -07003262 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003263 clearAudioPatches(uid);
3264 clearSessionRoutes(uid);
3265}
3266
Eric Laurent6a94d692014-05-20 11:18:06 -07003267void AudioPolicyManager::clearAudioPatches(uid_t uid)
3268{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003269 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003270 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3271 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003272 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003273 }
3274 }
3275}
3276
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003277void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3278 audio_io_handle_t ouptutToSkip)
3279{
3280 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3281 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3282 for (size_t j = 0; j < mOutputs.size(); j++) {
3283 if (mOutputs.keyAt(j) == ouptutToSkip) {
3284 continue;
3285 }
3286 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3287 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3288 continue;
3289 }
3290 // If the default device for this strategy is on another output mix,
3291 // invalidate all tracks in this strategy to force re connection.
3292 // Otherwise select new device on the output mix.
3293 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003294 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003295 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3296 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3297 }
3298 }
3299 } else {
3300 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3301 setOutputDevice(outputDesc, newDevice, false);
3302 }
3303 }
3304}
3305
3306void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3307{
3308 // remove output routes associated with this uid
3309 SortedVector<routing_strategy> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07003310 for (size_t i = 0; i < mOutputs.size(); i++) {
3311 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003312 for (const auto& client : outputDesc->getClientIterable()) {
3313 if (client->hasPreferredDevice() && client->uid() == uid) {
3314 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3315 affectedStrategies.add(getStrategy(client->stream()));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003316 }
3317 }
3318 }
3319 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003320 for (const auto& strategy : affectedStrategies) {
3321 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003322 }
3323
3324 // remove input routes associated with this uid
3325 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07003326 for (size_t i = 0; i < mInputs.size(); i++) {
3327 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003328 for (const auto& client : inputDesc->getClientIterable()) {
3329 if (client->hasPreferredDevice() && client->uid() == uid) {
3330 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3331 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003332 }
3333 }
3334 }
3335 // reroute inputs if necessary
3336 SortedVector<audio_io_handle_t> inputsToClose;
3337 for (size_t i = 0; i < mInputs.size(); i++) {
3338 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08003339 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003340 inputsToClose.add(inputDesc->mIoHandle);
3341 }
3342 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003343 for (const auto& input : inputsToClose) {
3344 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003345 }
3346}
3347
Eric Laurentd60560a2015-04-10 11:31:20 -07003348void AudioPolicyManager::clearAudioSources(uid_t uid)
3349{
3350 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003351 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3352 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07003353 stopAudioSource(mAudioSources.keyAt(i));
3354 }
3355 }
3356}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003357
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003358status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3359 audio_io_handle_t *ioHandle,
3360 audio_devices_t *device)
3361{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003362 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3363 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003364 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003365
François Gaffiedf372692015-03-19 10:43:27 +01003366 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003367}
3368
Eric Laurentd60560a2015-04-10 11:31:20 -07003369status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003370 const audio_attributes_t *attributes,
3371 audio_port_handle_t *portId,
3372 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003373{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003374 ALOGV("%s", __FUNCTION__);
3375 *portId = AUDIO_PORT_HANDLE_NONE;
3376
3377 if (source == NULL || attributes == NULL || portId == NULL) {
3378 ALOGW("%s invalid argument: source %p attributes %p handle %p",
3379 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003380 return BAD_VALUE;
3381 }
3382
Eric Laurentd60560a2015-04-10 11:31:20 -07003383 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3384 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003385 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
3386 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003387 return INVALID_OPERATION;
3388 }
3389
3390 sp<DeviceDescriptor> srcDeviceDesc =
3391 mAvailableInputDevices.getDevice(source->ext.device.type,
3392 String8(source->ext.device.address));
3393 if (srcDeviceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003394 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003395 return BAD_VALUE;
3396 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003397
3398 *portId = AudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07003399
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003400 struct audio_patch dummyPatch = {};
Eric Laurentd60560a2015-04-10 11:31:20 -07003401 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003402
3403 sp<SourceClientDescriptor> sourceDesc =
3404 new SourceClientDescriptor(*portId, uid, *attributes, patchDesc, srcDeviceDesc,
Eric Laurent97ac8712018-07-27 18:59:02 -07003405 streamTypefromAttributesInt(attributes),
3406 getStrategyForAttr(attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07003407
3408 status_t status = connectAudioSource(sourceDesc);
3409 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003410 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003411 }
3412 return status;
3413}
3414
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003415status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003416{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003417 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003418
3419 // make sure we only have one patch per source.
3420 disconnectAudioSource(sourceDesc);
3421
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003422 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003423 routing_strategy strategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003424 audio_stream_type_t stream = sourceDesc->stream();
3425 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->srcDevice();
Eric Laurentd60560a2015-04-10 11:31:20 -07003426
3427 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3428 sp<DeviceDescriptor> sinkDeviceDesc =
3429 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3430
3431 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003432
3433 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3434 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003435 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003436 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3437 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07003438 // TODO: may explicitly specify whether we should use HW or SW patch
3439 // create patch between src device and output device
3440 // create Hwoutput and add to mHwOutputs
Eric Laurentd60560a2015-04-10 11:31:20 -07003441 } else {
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07003442 audio_attributes_t resultAttr;
3443 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3444 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3445 config.sample_rate = sourceDesc->config().sample_rate;
3446 config.channel_mask = sourceDesc->config().channel_mask;
3447 config.format = sourceDesc->config().format;
3448 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
3449 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3450 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE,
3451 &attributes, &stream, sourceDesc->uid(), &config, &flags, &selectedDeviceId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003452 if (output == AUDIO_IO_HANDLE_NONE) {
3453 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3454 return INVALID_OPERATION;
3455 }
3456 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3457 if (outputDesc->isDuplicated()) {
3458 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3459 return INVALID_OPERATION;
3460 }
Eric Laurent733ce942017-12-07 12:18:25 -08003461 status_t status = outputDesc->start();
3462 if (status != NO_ERROR) {
3463 return status;
3464 }
3465
Eric Laurentd60560a2015-04-10 11:31:20 -07003466 // create a special patch with no sink and two sources:
3467 // - the second source indicates to PatchPanel through which output mix this patch should
3468 // be connected as well as the stream type for volume control
3469 // - the sink is defined by whatever output device is currently selected for the output
3470 // though which this patch is routed.
Mikhail Naganovdc769682018-05-04 15:34:08 -07003471 PatchBuilder patchBuilder;
3472 patchBuilder.addSource(srcDeviceDesc).addSource(outputDesc, { .stream = stream });
3473 status = mpClientInterface->createAudioPatch(patchBuilder.patch(),
Eric Laurentd60560a2015-04-10 11:31:20 -07003474 &afPatchHandle,
3475 0);
3476 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3477 status, afPatchHandle);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003478 sourceDesc->patchDesc()->mPatch = *patchBuilder.patch();
Eric Laurentd60560a2015-04-10 11:31:20 -07003479 if (status != NO_ERROR) {
3480 ALOGW("%s patch panel could not connect device patch, error %d",
3481 __FUNCTION__, status);
3482 return INVALID_OPERATION;
3483 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07003484
3485 if (outputDesc->getClient(sourceDesc->portId()) != nullptr) {
3486 ALOGW("%s source portId has already been attached to outputDesc", __func__);
3487 return INVALID_OPERATION;
3488 }
3489 outputDesc->addClient(sourceDesc);
3490
Eric Laurentd60560a2015-04-10 11:31:20 -07003491 uint32_t delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07003492 status = startSource(outputDesc, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003493
3494 if (status != NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003495 mpClientInterface->releaseAudioPatch(sourceDesc->patchDesc()->mAfPatchHandle, 0);
Eric Laurentd60560a2015-04-10 11:31:20 -07003496 return status;
3497 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003498 sourceDesc->setSwOutput(outputDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003499 if (delayMs != 0) {
3500 usleep(delayMs * 1000);
3501 }
3502 }
3503
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003504 sourceDesc->patchDesc()->mAfPatchHandle = afPatchHandle;
3505 addAudioPatch(sourceDesc->patchDesc()->mHandle, sourceDesc->patchDesc());
Eric Laurentd60560a2015-04-10 11:31:20 -07003506
3507 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003508}
3509
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003510status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07003511{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003512 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
3513 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003514 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003515 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003516 return BAD_VALUE;
3517 }
3518 status_t status = disconnectAudioSource(sourceDesc);
3519
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003520 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003521 return status;
3522}
3523
Andy Hung2ddee192015-12-18 17:34:44 -08003524status_t AudioPolicyManager::setMasterMono(bool mono)
3525{
3526 if (mMasterMono == mono) {
3527 return NO_ERROR;
3528 }
3529 mMasterMono = mono;
3530 // if enabling mono we close all offloaded devices, which will invalidate the
3531 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3532 // for recreating the new AudioTrack as non-offloaded PCM.
3533 //
3534 // If disabling mono, we leave all tracks as is: we don't know which clients
3535 // and tracks are able to be recreated as offloaded. The next "song" should
3536 // play back offloaded.
3537 if (mMasterMono) {
3538 Vector<audio_io_handle_t> offloaded;
3539 for (size_t i = 0; i < mOutputs.size(); ++i) {
3540 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3541 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3542 offloaded.push(desc->mIoHandle);
3543 }
3544 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003545 for (const auto& handle : offloaded) {
3546 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003547 }
3548 }
3549 // update master mono for all remaining outputs
3550 for (size_t i = 0; i < mOutputs.size(); ++i) {
3551 updateMono(mOutputs.keyAt(i));
3552 }
3553 return NO_ERROR;
3554}
3555
3556status_t AudioPolicyManager::getMasterMono(bool *mono)
3557{
3558 *mono = mMasterMono;
3559 return NO_ERROR;
3560}
3561
Eric Laurentac9cef52017-06-09 15:46:26 -07003562float AudioPolicyManager::getStreamVolumeDB(
3563 audio_stream_type_t stream, int index, audio_devices_t device)
3564{
3565 return computeVolume(stream, index, device);
3566}
3567
jiabin81772902018-04-02 17:52:27 -07003568status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3569 audio_format_t *surroundFormats,
3570 bool *surroundFormatsEnabled,
3571 bool reported)
3572{
3573 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3574 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3575 return BAD_VALUE;
3576 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003577 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p reported %d",
3578 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled, reported);
jiabin81772902018-04-02 17:52:27 -07003579
3580 size_t formatsWritten = 0;
3581 size_t formatsMax = *numSurroundFormats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08003582 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
jiabin81772902018-04-02 17:52:27 -07003583 if (reported) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003584 // Return formats from all device profiles that have already been resolved by
Mikhail Naganov2563f232018-09-27 14:48:01 -07003585 // checkOutputsForDevice().
Mikhail Naganov100f0122018-11-29 11:22:16 -08003586 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
3587 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
3588 FormatVector supportedFormats =
3589 device->getAudioPort()->getAudioProfiles().getSupportedFormats();
3590 for (size_t j = 0; j < supportedFormats.size(); j++) {
3591 if (mConfig.getSurroundFormats().count(supportedFormats[j]) != 0) {
3592 formats.insert(supportedFormats[j]);
3593 } else {
3594 for (const auto& pair : mConfig.getSurroundFormats()) {
3595 if (pair.second.count(supportedFormats[j]) != 0) {
3596 formats.insert(pair.first);
3597 break;
3598 }
3599 }
3600 }
3601 }
jiabin81772902018-04-02 17:52:27 -07003602 }
3603 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003604 for (const auto& pair : mConfig.getSurroundFormats()) {
3605 formats.insert(pair.first);
jiabin81772902018-04-02 17:52:27 -07003606 }
3607 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003608 *numSurroundFormats = formats.size();
3609 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3610 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov2563f232018-09-27 14:48:01 -07003611 for (const auto& format: formats) {
jiabin81772902018-04-02 17:52:27 -07003612 if (formatsWritten < formatsMax) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003613 surroundFormats[formatsWritten] = format;
Mikhail Naganov100f0122018-11-29 11:22:16 -08003614 bool formatEnabled = true;
3615 switch (forceUse) {
3616 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
3617 formatEnabled = mManualSurroundFormats.count(format) != 0;
3618 break;
3619 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
3620 formatEnabled = false;
3621 break;
3622 default: // AUTO or ALWAYS => true
3623 break;
jiabin81772902018-04-02 17:52:27 -07003624 }
3625 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3626 }
jiabin81772902018-04-02 17:52:27 -07003627 }
3628 return NO_ERROR;
3629}
3630
3631status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3632{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003633 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003634 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
3635 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003636 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07003637 return BAD_VALUE;
3638 }
3639
Mikhail Naganov100f0122018-11-29 11:22:16 -08003640 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
3641 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003642 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07003643 return INVALID_OPERATION;
3644 }
3645
Mikhail Naganov100f0122018-11-29 11:22:16 -08003646 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07003647 return NO_ERROR;
3648 }
3649
Mikhail Naganov100f0122018-11-29 11:22:16 -08003650 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07003651 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003652 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003653 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003654 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07003655 }
3656 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003657 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003658 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003659 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07003660 }
3661 }
3662
3663 sp<SwAudioOutputDescriptor> outputDesc;
3664 bool profileUpdated = false;
Mikhail Naganov708e0382018-05-30 09:53:04 -07003665 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003666 AUDIO_DEVICE_OUT_HDMI);
3667 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3668 // Simulate reconnection to update enabled surround sound formats.
3669 String8 address = hdmiOutputDevices[i]->mAddress;
3670 String8 name = hdmiOutputDevices[i]->getName();
3671 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3672 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3673 address.c_str(),
3674 name.c_str());
3675 if (status != NO_ERROR) {
3676 continue;
3677 }
3678 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3679 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3680 address.c_str(),
3681 name.c_str());
3682 profileUpdated |= (status == NO_ERROR);
3683 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003684 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
Mikhail Naganov708e0382018-05-30 09:53:04 -07003685 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003686 AUDIO_DEVICE_IN_HDMI);
3687 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3688 // Simulate reconnection to update enabled surround sound formats.
3689 String8 address = hdmiInputDevices[i]->mAddress;
3690 String8 name = hdmiInputDevices[i]->getName();
3691 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3692 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3693 address.c_str(),
3694 name.c_str());
3695 if (status != NO_ERROR) {
3696 continue;
3697 }
3698 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3699 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3700 address.c_str(),
3701 name.c_str());
3702 profileUpdated |= (status == NO_ERROR);
3703 }
3704
jiabin81772902018-04-02 17:52:27 -07003705 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003706 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08003707 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07003708 }
3709
3710 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3711}
3712
Eric Laurentf32108e2018-10-04 17:22:04 -07003713void AudioPolicyManager::setAppState(uid_t uid, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003714{
Eric Laurentf32108e2018-10-04 17:22:04 -07003715 Vector<sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
Eric Laurentf32108e2018-10-04 17:22:04 -07003716
Eric Laurent4eb58f12018-12-07 16:41:02 -08003717 ALOGV("%s(uid:%d, state:%d)", __func__, uid, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003718
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003719 for (size_t i = 0; i < activeInputs.size(); i++) {
3720 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
Eric Laurent8f42ea12018-08-08 09:08:25 -07003721 RecordClientVector clients = activeDesc->clientsList(true /*activeOnly*/);
3722 for (const auto& client : clients) {
3723 if (uid == client->uid()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003724 client->setAppState(state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003725 }
3726 }
3727 }
3728}
3729
jiabin6012f912018-11-02 17:06:30 -07003730bool AudioPolicyManager::isHapticPlaybackSupported()
3731{
3732 for (const auto& hwModule : mHwModules) {
3733 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
3734 for (const auto &outProfile : outputProfiles) {
3735 struct audio_port audioPort;
3736 outProfile->toAudioPort(&audioPort);
3737 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
3738 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
3739 return true;
3740 }
3741 }
3742 }
3743 }
3744 return false;
3745}
3746
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003747status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003748{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003749 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003750
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003751 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003752 if (patchDesc == 0) {
3753 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003754 sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003755 return BAD_VALUE;
3756 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003757 removeAudioPatch(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003758
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003759 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003760 if (swOutputDesc != 0) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003761 status_t status = stopSource(swOutputDesc, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08003762 if (status == NO_ERROR) {
3763 swOutputDesc->stop();
3764 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003765 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3766 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003767 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003768 if (hwOutputDesc != 0) {
3769 // release patch between src device and output device
3770 // close Hwoutput and remove from mHwOutputs
3771 } else {
3772 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3773 }
3774 }
3775 return NO_ERROR;
3776}
3777
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003778sp<SourceClientDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
Eric Laurentd60560a2015-04-10 11:31:20 -07003779 audio_io_handle_t output, routing_strategy strategy)
3780{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003781 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07003782 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003783 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3784 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003785 routing_strategy sourceStrategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003786 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003787 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3788 source = sourceDesc;
3789 break;
3790 }
3791 }
3792 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003793}
3794
Eric Laurente552edb2014-03-10 17:42:56 -07003795// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003796// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003797// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003798uint32_t AudioPolicyManager::nextAudioPortGeneration()
3799{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003800 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003801}
3802
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003803// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3804static const char *kConfigLocationList[] =
3805 {"/odm/etc", "/vendor/etc", "/system/etc"};
3806static const int kConfigLocationListSize =
3807 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3808
3809static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3810 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07003811 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003812 status_t ret;
3813
Petri Gyntherf497f292018-04-17 18:46:10 -07003814 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
3815 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
3816 // A2DP offload supported but disabled: try to use special XML file
3817 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
3818 }
3819 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3820
3821 for (const char* fileName : fileNames) {
3822 for (int i = 0; i < kConfigLocationListSize; i++) {
Petri Gyntherf497f292018-04-17 18:46:10 -07003823 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
3824 "%s/%s", kConfigLocationList[i], fileName);
Mikhail Naganova289aea2018-09-17 15:26:23 -07003825 ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile, &config);
Petri Gyntherf497f292018-04-17 18:46:10 -07003826 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003827 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07003828 return ret;
3829 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003830 }
3831 }
3832 return ret;
3833}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003834
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003835AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
3836 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07003837 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07003838 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003839 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07003840 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003841 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003842 mVolumeCurves(new VolumeCurvesCollection()),
3843 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08003844 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003845 mAudioPortGeneration(1),
3846 mBeaconMuteRefCount(0),
3847 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003848 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003849 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003850 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08003851 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07003852{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003853}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003854
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003855AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
3856 : AudioPolicyManager(clientInterface, false /*forTesting*/)
3857{
3858 loadConfig();
3859 initialize();
3860}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003861
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07003862// This check is to catch any legacy platform updating to Q without having
3863// switched to XML since its deprecation on O.
3864// TODO: after Q release, remove this check and flag as XML is now the only
3865// option and all legacy platform should have transitioned to XML.
3866#ifndef USE_XML_AUDIO_POLICY_CONF
3867#error Audio policy no longer supports legacy .conf configuration format
François Gaffied1ab2bd2015-12-02 18:20:06 +01003868#endif
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07003869
3870void AudioPolicyManager::loadConfig() {
3871 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003872 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003873 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01003874 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003875}
3876
3877status_t AudioPolicyManager::initialize() {
3878 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01003879
3880 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003881 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3882 if (!engineInstance) {
3883 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003884 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003885 }
3886 // Retrieve the Policy Manager Interface
3887 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3888 if (mEngine == NULL) {
3889 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003890 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003891 }
3892 mEngine->setObserver(this);
3893 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003894 if (status != NO_ERROR) {
3895 LOG_FATAL("Policy engine not initialized(err=%d)", status);
3896 return status;
3897 }
François Gaffie2110e042015-03-24 08:41:51 +01003898
Eric Laurent3a4311c2014-03-17 12:00:47 -07003899 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003900 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003901 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3902 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Mikhail Naganovd4120142017-12-06 15:49:22 -08003903 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003904 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08003905 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
3906 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003907 continue;
3908 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08003909 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07003910 // open all output streams needed to access attached devices
3911 // except for direct output streams that are only opened when they are actually
3912 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003913 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003914 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003915 if (!outProfile->canOpenNewIo()) {
3916 ALOGE("Invalid Output profile max open count %u for profile %s",
3917 outProfile->maxOpenCount, outProfile->getTagName().c_str());
3918 continue;
3919 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003920 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003921 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003922 continue;
3923 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003924 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003925 mTtsOutputAvailable = true;
3926 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003927
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003928 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003929 continue;
3930 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003931 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003932 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3933 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003934 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003935 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003936 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003937 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003938 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003939 if ((profileType & outputDeviceTypes) == 0) {
3940 continue;
3941 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003942 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3943 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003944 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov708e0382018-05-30 09:53:04 -07003945 const DeviceVector &devicesForType = supportedDevices.getDevicesFromTypeMask(
3946 profileType);
Eric Laurentc40d9692016-04-13 19:14:13 -07003947 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3948 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003949 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08003950 status_t status = outputDesc->open(nullptr, profileType, address,
3951 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07003952
3953 if (status != NO_ERROR) {
3954 ALOGW("Cannot open output stream for device %08x on hw module %s",
3955 outputDesc->mDevice,
Mikhail Naganovd4120142017-12-06 15:49:22 -08003956 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003957 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003958 for (const auto& dev : supportedDevices) {
3959 ssize_t index = mAvailableOutputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07003960 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003961 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003962 mAvailableOutputDevices[index]->attach(hwModule);
Eric Laurentd78f1532014-09-16 16:38:20 -07003963 }
3964 }
3965 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003966 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003967 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003968 }
3969 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003970 setOutputDevice(outputDesc,
Eric Laurentfe231122017-11-17 17:48:06 -08003971 profileType,
Eric Laurentc40d9692016-04-13 19:14:13 -07003972 true,
3973 0,
3974 NULL,
Eric Laurentfe231122017-11-17 17:48:06 -08003975 address);
Eric Laurentd78f1532014-09-16 16:38:20 -07003976 }
Eric Laurente552edb2014-03-10 17:42:56 -07003977 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003978 // open input streams needed to access attached devices to validate
3979 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003980 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003981 if (!inProfile->canOpenNewIo()) {
3982 ALOGE("Invalid Input profile max open count %u for profile %s",
3983 inProfile->maxOpenCount, inProfile->getTagName().c_str());
3984 continue;
3985 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003986 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003987 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003988 continue;
3989 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003990 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003991 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003992 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
3993
Eric Laurentd78f1532014-09-16 16:38:20 -07003994 if ((profileType & inputDeviceTypes) == 0) {
3995 continue;
3996 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08003997 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08003998 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07003999
Mikhail Naganov708e0382018-05-30 09:53:04 -07004000 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(profileType);
Eric Laurent53b810e2017-12-10 17:25:10 -08004001 // the inputs vector must be of size >= 1, but we don't want to crash here
4002 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
4003 : String8("");
4004 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
4005 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
4006
Eric Laurentd78f1532014-09-16 16:38:20 -07004007 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004008 status_t status = inputDesc->open(nullptr,
4009 profileType,
Eric Laurent53b810e2017-12-10 17:25:10 -08004010 address,
Eric Laurentfe231122017-11-17 17:48:06 -08004011 AUDIO_SOURCE_MIC,
4012 AUDIO_INPUT_FLAG_NONE,
4013 &input);
Eric Laurentd78f1532014-09-16 16:38:20 -07004014
4015 if (status == NO_ERROR) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004016 for (const auto& dev : inProfile->getSupportedDevices()) {
4017 ssize_t index = mAvailableInputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07004018 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07004019 if (index >= 0) {
4020 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
4021 if (!devDesc->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004022 devDesc->attach(hwModule);
Eric Laurent83efe1c2017-07-09 16:51:08 -07004023 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07004024 }
Eric Laurentd78f1532014-09-16 16:38:20 -07004025 }
4026 }
Eric Laurentfe231122017-11-17 17:48:06 -08004027 inputDesc->close();
Eric Laurentd78f1532014-09-16 16:38:20 -07004028 } else {
4029 ALOGW("Cannot open input stream for device %08x on hw module %s",
Eric Laurentfe231122017-11-17 17:48:06 -08004030 profileType,
Mikhail Naganovd4120142017-12-06 15:49:22 -08004031 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07004032 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004033 }
4034 }
4035 // make sure all attached devices have been allocated a unique ID
4036 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004037 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004038 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004039 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
4040 continue;
4041 }
François Gaffie2110e042015-03-24 08:41:51 +01004042 // The device is now validated and can be appended to the available devices of the engine
4043 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
4044 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004045 i++;
4046 }
4047 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004048 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01004049 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004050 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
4051 continue;
4052 }
François Gaffie2110e042015-03-24 08:41:51 +01004053 // The device is now validated and can be appended to the available devices of the engine
4054 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
4055 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004056 i++;
4057 }
4058 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004059 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01004060 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004061 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004062 }
jiabin9ff780e2018-03-19 18:19:52 -07004063 // If microphones address is empty, set it according to device type
4064 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
4065 if (mAvailableInputDevices[i]->mAddress.isEmpty()) {
4066 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
4067 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
4068 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
4069 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BACK_MICROPHONE_ADDRESS);
4070 }
4071 }
4072 }
Eric Laurente552edb2014-03-10 17:42:56 -07004073
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004074 if (mPrimaryOutput == 0) {
4075 ALOGE("Failed to open primary output");
4076 status = NO_INIT;
4077 }
Eric Laurente552edb2014-03-10 17:42:56 -07004078
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09004079 // Silence ALOGV statements
4080 property_set("log.tag." LOG_TAG, "D");
4081
Eric Laurente552edb2014-03-10 17:42:56 -07004082 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004083 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004084}
4085
Eric Laurente0720872014-03-11 09:30:41 -07004086AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004087{
Eric Laurente552edb2014-03-10 17:42:56 -07004088 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004089 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004090 }
4091 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004092 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004093 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004094 mAvailableOutputDevices.clear();
4095 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004096 mOutputs.clear();
4097 mInputs.clear();
4098 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004099 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004100 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004101}
4102
Eric Laurente0720872014-03-11 09:30:41 -07004103status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004104{
Eric Laurent87ffa392015-05-22 10:32:38 -07004105 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004106}
4107
Eric Laurente552edb2014-03-10 17:42:56 -07004108// ---
4109
Eric Laurent98e38192018-02-15 18:31:53 -08004110void AudioPolicyManager::addOutput(audio_io_handle_t output,
4111 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004112{
Eric Laurent1c333e22014-05-20 10:48:17 -07004113 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08004114 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004115 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004116 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004117 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004118}
4119
François Gaffie53615e22015-03-19 09:24:12 +01004120void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4121{
4122 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004123 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004124}
4125
Eric Laurent98e38192018-02-15 18:31:53 -08004126void AudioPolicyManager::addInput(audio_io_handle_t input,
4127 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004128{
Eric Laurent1c333e22014-05-20 10:48:17 -07004129 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004130 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004131}
Eric Laurente552edb2014-03-10 17:42:56 -07004132
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004133void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08004134 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004135 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004136 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08004137 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004138 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08004139 if (devDesc != 0) {
4140 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
4141 desc->mIoHandle, address.string());
4142 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004143 }
4144}
4145
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004146status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004147 audio_policy_dev_state_t state,
4148 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004149 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07004150{
François Gaffie53615e22015-03-19 09:24:12 +01004151 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07004152 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004153
4154 if (audio_device_is_digital(device)) {
4155 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004156 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004157 }
Eric Laurente552edb2014-03-10 17:42:56 -07004158
Eric Laurent3b73df72014-03-11 09:06:29 -07004159 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004160 // first list already open outputs that can be routed to this device
4161 for (size_t i = 0; i < mOutputs.size(); i++) {
4162 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07004163 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004164 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004165 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
4166 outputs.add(mOutputs.keyAt(i));
4167 } else {
4168 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08004169 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004170 }
Eric Laurente552edb2014-03-10 17:42:56 -07004171 }
4172 }
4173 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004174 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004175 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004176 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4177 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004178 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004179 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004180 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004181 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004182 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4183 j, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004184 }
Eric Laurente552edb2014-03-10 17:42:56 -07004185 }
4186 }
4187 }
4188
Eric Laurent7b279bb2015-12-14 10:18:23 -08004189 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004190
Eric Laurente552edb2014-03-10 17:42:56 -07004191 if (profiles.isEmpty() && outputs.isEmpty()) {
4192 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4193 return BAD_VALUE;
4194 }
4195
4196 // open outputs for matching profiles if needed. Direct outputs are also opened to
4197 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4198 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004199 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004200
4201 // nothing to do if one output is already opened for this profile
4202 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004203 for (j = 0; j < outputs.size(); j++) {
4204 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004205 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004206 // matching profile: save the sample rates, format and channel masks supported
4207 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07004208 if (audio_device_is_digital(device)) {
4209 devDesc->importAudioPort(profile);
4210 }
Eric Laurente552edb2014-03-10 17:42:56 -07004211 break;
4212 }
4213 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004214 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004215 continue;
4216 }
4217
Eric Laurent3974e3b2017-12-07 17:58:43 -08004218 if (!profile->canOpenNewIo()) {
4219 ALOGW("Max Output number %u already opened for this profile %s",
4220 profile->maxOpenCount, profile->getTagName().c_str());
4221 continue;
4222 }
4223
Eric Laurent83efe1c2017-07-09 16:51:08 -07004224 ALOGV("opening output for device %08x with params %s profile %p name %s",
4225 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004226 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004227 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004228 status_t status = desc->open(nullptr, device, address,
4229 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004230
Eric Laurentfe231122017-11-17 17:48:06 -08004231 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004232 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004233 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004234 char *param = audio_device_address_to_parameter(device, address);
4235 mpClientInterface->setParameters(output, String8(param));
4236 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004237 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08004238 updateAudioProfiles(devDesc, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004239 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004240 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004241 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004242 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004243 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004244 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004245 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004246 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4247 profile->pickAudioProfile(
4248 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004249 config.offload_info.sample_rate = config.sample_rate;
4250 config.offload_info.channel_mask = config.channel_mask;
4251 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004252
4253 status_t status = desc->open(&config, device, address, AUDIO_STREAM_DEFAULT,
4254 AUDIO_OUTPUT_FLAG_NONE, &output);
4255 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004256 output = AUDIO_IO_HANDLE_NONE;
4257 }
Eric Laurentd4692962014-05-05 18:13:44 -07004258 }
4259
Eric Laurentcf2c0212014-07-25 16:20:43 -07004260 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004261 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01004262 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004263 sp<AudioPolicyMix> policyMix;
4264 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004265 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
4266 address.string());
4267 }
François Gaffie036e1e92015-03-19 10:16:24 +01004268 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07004269 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01004270
Eric Laurent87ffa392015-05-22 10:32:38 -07004271 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4272 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004273 // no duplicated output for direct outputs and
4274 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004275 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004276
Eric Laurentd4692962014-05-05 18:13:44 -07004277 //TODO: configure audio effect output stage here
4278
4279 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004280 sp<SwAudioOutputDescriptor> dupOutputDesc =
4281 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4282 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4283 &duplicatedOutput);
4284 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004285 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004286 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004287 } else {
4288 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004289 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004290 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004291 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004292 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004293 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004294 }
Eric Laurente552edb2014-03-10 17:42:56 -07004295 }
4296 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004297 } else {
4298 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004299 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004300 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004301 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004302 profiles.removeAt(profile_index);
4303 profile_index--;
4304 } else {
4305 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004306 // Load digital format info only for digital devices
4307 if (audio_device_is_digital(device)) {
4308 devDesc->importAudioPort(profile);
4309 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004310
François Gaffie53615e22015-03-19 09:24:12 +01004311 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004312 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4313 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004314 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004315 NULL/*patch handle*/, address.string());
4316 }
Eric Laurente552edb2014-03-10 17:42:56 -07004317 ALOGV("checkOutputsForDevice(): adding output %d", output);
4318 }
4319 }
4320
4321 if (profiles.isEmpty()) {
4322 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4323 return BAD_VALUE;
4324 }
Eric Laurentd4692962014-05-05 18:13:44 -07004325 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004326 // check if one opened output is not needed any more after disconnecting one device
4327 for (size_t i = 0; i < mOutputs.size(); i++) {
4328 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004329 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004330 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004331 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004332 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004333 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004334 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004335 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4336 mOutputs.keyAt(i));
4337 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004338 }
Eric Laurente552edb2014-03-10 17:42:56 -07004339 }
4340 }
Eric Laurentd4692962014-05-05 18:13:44 -07004341 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004342 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004343 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4344 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004345 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004346 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004347 "clearing direct output profile %zu on module %s",
4348 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004349 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004350 }
4351 }
4352 }
4353 }
4354 return NO_ERROR;
4355}
4356
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004357status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004358 audio_policy_dev_state_t state,
4359 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004360 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004361{
Paul McLean9080a4c2015-06-18 08:24:02 -07004362 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004363 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004364
4365 if (audio_device_is_digital(device)) {
4366 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004367 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004368 }
4369
Eric Laurentd4692962014-05-05 18:13:44 -07004370 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4371 // first list already open inputs that can be routed to this device
4372 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4373 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004374 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004375 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4376 inputs.add(mInputs.keyAt(input_index));
4377 }
4378 }
4379
4380 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004381 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004382 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004383 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004384 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004385 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004386 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004387
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004388 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004389 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004390 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004391 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004392 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4393 profile_index, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004394 }
Eric Laurentd4692962014-05-05 18:13:44 -07004395 }
4396 }
4397 }
4398
4399 if (profiles.isEmpty() && inputs.isEmpty()) {
4400 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4401 return BAD_VALUE;
4402 }
4403
4404 // open inputs for matching profiles if needed. Direct inputs are also opened to
4405 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4406 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4407
Eric Laurent1c333e22014-05-20 10:48:17 -07004408 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004409
Eric Laurentd4692962014-05-05 18:13:44 -07004410 // nothing to do if one input is already opened for this profile
4411 size_t input_index;
4412 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4413 desc = mInputs.valueAt(input_index);
4414 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004415 if (audio_device_is_digital(device)) {
4416 devDesc->importAudioPort(profile);
4417 }
Eric Laurentd4692962014-05-05 18:13:44 -07004418 break;
4419 }
4420 }
4421 if (input_index != mInputs.size()) {
4422 continue;
4423 }
4424
Eric Laurent3974e3b2017-12-07 17:58:43 -08004425 if (!profile->canOpenNewIo()) {
4426 ALOGW("Max Input number %u already opened for this profile %s",
4427 profile->maxOpenCount, profile->getTagName().c_str());
4428 continue;
4429 }
4430
Eric Laurentfe231122017-11-17 17:48:06 -08004431 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004432 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004433 status_t status = desc->open(nullptr,
4434 device,
4435 address,
4436 AUDIO_SOURCE_MIC,
4437 AUDIO_INPUT_FLAG_NONE,
4438 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004439
Eric Laurentcf2c0212014-07-25 16:20:43 -07004440 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004441 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004442 char *param = audio_device_address_to_parameter(device, address);
4443 mpClientInterface->setParameters(input, String8(param));
4444 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004445 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08004446 updateAudioProfiles(devDesc, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004447 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004448 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004449 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004450 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004451 }
4452
4453 if (input != 0) {
4454 addInput(input, desc);
4455 }
4456 } // endif input != 0
4457
Eric Laurentcf2c0212014-07-25 16:20:43 -07004458 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004459 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004460 profiles.removeAt(profile_index);
4461 profile_index--;
4462 } else {
4463 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004464 if (audio_device_is_digital(device)) {
4465 devDesc->importAudioPort(profile);
4466 }
Eric Laurentd4692962014-05-05 18:13:44 -07004467 ALOGV("checkInputsForDevice(): adding input %d", input);
4468 }
4469 } // end scan profiles
4470
4471 if (profiles.isEmpty()) {
4472 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4473 return BAD_VALUE;
4474 }
4475 } else {
4476 // Disconnect
4477 // check if one opened input is not needed any more after disconnecting one device
4478 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4479 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004480 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004481 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4482 mInputs.keyAt(input_index));
4483 inputs.add(mInputs.keyAt(input_index));
4484 }
4485 }
4486 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004487 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004488 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004489 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004490 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004491 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004492 if (profile->supportDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004493 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4494 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004495 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004496 }
4497 }
4498 }
4499 } // end disconnect
4500
4501 return NO_ERROR;
4502}
4503
4504
Eric Laurente0720872014-03-11 09:30:41 -07004505void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004506{
4507 ALOGV("closeOutput(%d)", output);
4508
Eric Laurentc75307b2015-03-17 15:29:32 -07004509 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004510 if (outputDesc == NULL) {
4511 ALOGW("closeOutput() unknown output %d", output);
4512 return;
4513 }
François Gaffie036e1e92015-03-19 10:16:24 +01004514 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004515
Eric Laurente552edb2014-03-10 17:42:56 -07004516 // look for duplicated outputs connected to the output being removed.
4517 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004518 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004519 if (dupOutputDesc->isDuplicated() &&
4520 (dupOutputDesc->mOutput1 == outputDesc ||
4521 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004522 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004523 if (dupOutputDesc->mOutput1 == outputDesc) {
4524 outputDesc2 = dupOutputDesc->mOutput2;
4525 } else {
4526 outputDesc2 = dupOutputDesc->mOutput1;
4527 }
4528 // As all active tracks on duplicated output will be deleted,
4529 // and as they were also referenced on the other output, the reference
4530 // count for their stream type must be adjusted accordingly on
4531 // the other output.
Andy Hungaf036da2018-09-21 10:46:21 -07004532 const bool wasActive = outputDesc2->isActive();
4533 for (const auto &clientPair : dupOutputDesc->getActiveClients()) {
4534 outputDesc2->changeStreamActiveCount(clientPair.first, -clientPair.second);
Eric Laurente552edb2014-03-10 17:42:56 -07004535 }
Eric Laurent733ce942017-12-07 12:18:25 -08004536 // stop() will be a no op if the output is still active but is needed in case all
4537 // active streams refcounts where cleared above
4538 if (wasActive) {
4539 outputDesc2->stop();
4540 }
Eric Laurente552edb2014-03-10 17:42:56 -07004541 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4542 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4543
4544 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004545 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004546 }
4547 }
4548
Eric Laurent05b90f82014-08-27 15:32:29 -07004549 nextAudioPortGeneration();
4550
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004551 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004552 if (index >= 0) {
4553 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004554 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004555 mAudioPatches.removeItemsAt(index);
4556 mpClientInterface->onAudioPatchListUpdate();
4557 }
4558
Eric Laurentfe231122017-11-17 17:48:06 -08004559 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004560
François Gaffie53615e22015-03-19 09:24:12 +01004561 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004562 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10004563
4564 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
4565 // no direct outputs are open.
Mikhail Naganov100f0122018-11-29 11:22:16 -08004566 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Dean Wheatley3023b382018-08-09 07:42:40 +10004567 bool directOutputOpen = false;
4568 for (size_t i = 0; i < mOutputs.size(); i++) {
4569 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
4570 directOutputOpen = true;
4571 break;
4572 }
4573 }
4574 if (!directOutputOpen) {
4575 ALOGV("no direct outputs open, reset MSD patch");
4576 setMsdPatch();
4577 }
4578 }
Eric Laurent05b90f82014-08-27 15:32:29 -07004579}
4580
4581void AudioPolicyManager::closeInput(audio_io_handle_t input)
4582{
4583 ALOGV("closeInput(%d)", input);
4584
4585 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4586 if (inputDesc == NULL) {
4587 ALOGW("closeInput() unknown input %d", input);
4588 return;
4589 }
4590
Eric Laurent6a94d692014-05-20 11:18:06 -07004591 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004592
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004593 audio_devices_t device = inputDesc->mDevice;
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004594 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004595 if (index >= 0) {
4596 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004597 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004598 mAudioPatches.removeItemsAt(index);
4599 mpClientInterface->onAudioPatchListUpdate();
4600 }
4601
Eric Laurentfe231122017-11-17 17:48:06 -08004602 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004603 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004604
4605 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
4606 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
4607 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
4608 SoundTrigger::setCaptureState(false);
4609 }
Eric Laurente552edb2014-03-10 17:42:56 -07004610}
4611
Eric Laurentc75307b2015-03-17 15:29:32 -07004612SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4613 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004614 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004615{
4616 SortedVector<audio_io_handle_t> outputs;
4617
4618 ALOGVV("getOutputsForDevice() device %04x", device);
4619 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004620 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004621 i, openOutputs.valueAt(i)->isDuplicated(),
4622 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004623 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4624 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4625 outputs.add(openOutputs.keyAt(i));
4626 }
4627 }
4628 return outputs;
4629}
4630
Mikhail Naganov37977152018-07-11 15:54:44 -07004631void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
4632{
4633 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
4634 // output is suspended before any tracks are moved to it
4635 checkA2dpSuspend();
4636 checkOutputForAllStrategies();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004637 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07004638 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00004639 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004640 setMsdPatch();
4641 }
Mikhail Naganov37977152018-07-11 15:54:44 -07004642}
4643
Eric Laurente0720872014-03-11 09:30:41 -07004644void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004645{
4646 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4647 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4648 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4649 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4650
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004651 // also take into account external policy-related changes: add all outputs which are
4652 // associated with policies in the "before" and "after" output vectors
4653 ALOGVV("checkOutputForStrategy(): policy related outputs");
4654 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004655 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004656 if (desc != 0 && desc->mPolicyMix != NULL) {
4657 srcOutputs.add(desc->mIoHandle);
4658 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4659 }
4660 }
4661 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004662 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004663 if (desc != 0 && desc->mPolicyMix != NULL) {
4664 dstOutputs.add(desc->mIoHandle);
4665 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4666 }
4667 }
4668
Mikhail Naganov9de8bd12018-07-23 16:41:31 -07004669 if (srcOutputs != dstOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004670 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4671 // audio from invalidated tracks will be rendered when unmuting
4672 uint32_t maxLatency = 0;
4673 for (audio_io_handle_t srcOut : srcOutputs) {
4674 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4675 if (desc != 0 && maxLatency < desc->latency()) {
4676 maxLatency = desc->latency();
4677 }
4678 }
Eric Laurente552edb2014-03-10 17:42:56 -07004679 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4680 strategy, srcOutputs[0], dstOutputs[0]);
4681 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004682 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004683 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4684 if (desc != 0 && isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004685 setStrategyMute(strategy, true, desc);
Eric Laurentac3a6902018-05-11 16:39:10 -07004686 setStrategyMute(strategy, false, desc, maxLatency * LATENCY_MUTE_FACTOR, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004687 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004688 sp<SourceClientDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004689 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004690 if (source != 0){
4691 connectAudioSource(source);
4692 }
Eric Laurente552edb2014-03-10 17:42:56 -07004693 }
4694
4695 // Move effects associated to this strategy from previous output to new output
4696 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004697 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004698 }
4699 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004700 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004701 if (getStrategy((audio_stream_type_t)i) == strategy) {
4702 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004703 }
4704 }
4705 }
4706}
4707
Eric Laurente0720872014-03-11 09:30:41 -07004708void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004709{
François Gaffie2110e042015-03-24 08:41:51 +01004710 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004711 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004712 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004713 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004714 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004715 checkOutputForStrategy(STRATEGY_SONIFICATION);
4716 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004717 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004718 checkOutputForStrategy(STRATEGY_MEDIA);
4719 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004720 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004721}
4722
Eric Laurente0720872014-03-11 09:30:41 -07004723void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004724{
François Gaffie53615e22015-03-19 09:24:12 +01004725 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004726 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004727 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004728 return;
4729 }
4730
Eric Laurent3a4311c2014-03-17 12:00:47 -07004731 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004732 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4733 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4734 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004735
4736 // if suspended, restore A2DP output if:
4737 // ((SCO device is NOT connected) ||
4738 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4739 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004740 //
Eric Laurentf732e072016-08-03 19:30:28 -07004741 // if not suspended, suspend A2DP output if:
4742 // (SCO device is connected) &&
4743 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4744 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004745 //
4746 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004747 if (!isScoConnected ||
4748 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4749 AUDIO_POLICY_FORCE_BT_SCO) &&
4750 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4751 AUDIO_POLICY_FORCE_BT_SCO) &&
4752 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004753 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004754
4755 mpClientInterface->restoreOutput(a2dpOutput);
4756 mA2dpSuspended = false;
4757 }
4758 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004759 if (isScoConnected &&
4760 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4761 AUDIO_POLICY_FORCE_BT_SCO) ||
4762 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4763 AUDIO_POLICY_FORCE_BT_SCO) ||
4764 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004765 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004766
4767 mpClientInterface->suspendOutput(a2dpOutput);
4768 mA2dpSuspended = true;
4769 }
4770 }
4771}
4772
Eric Laurent97ac8712018-07-27 18:59:02 -07004773template <class IoDescriptor, class Filter>
4774sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4775 IoDescriptor& desc, Filter filter, bool& active, const DeviceVector& devices)
4776{
4777 auto activeClients = desc->clientsList(true /*activeOnly*/);
4778 auto activeClientsWithRoute =
4779 desc->clientsList(true /*activeOnly*/, filter, true /*preferredDevice*/);
4780 active = activeClients.size() > 0;
4781 if (active && activeClients.size() == activeClientsWithRoute.size()) {
4782 return devices.getDeviceFromId(activeClientsWithRoute[0]->preferredDeviceId());
4783 }
4784 return nullptr;
4785}
4786
4787template <class IoCollection, class Filter>
4788sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4789 IoCollection& ioCollection, Filter filter, const DeviceVector& devices)
4790{
4791 sp<DeviceDescriptor> device;
4792 for (size_t i = 0; i < ioCollection.size(); i++) {
4793 auto desc = ioCollection.valueAt(i);
4794 bool active;
4795 sp<DeviceDescriptor> curDevice = findPreferredDevice(desc, filter, active, devices);
4796 if (active && curDevice == nullptr) {
4797 return nullptr;
4798 } else if (curDevice != nullptr) {
4799 device = curDevice;
4800 }
4801 }
4802 return device;
4803}
4804
Eric Laurentc75307b2015-03-17 15:29:32 -07004805audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4806 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004807{
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004808 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004809 if (index >= 0) {
4810 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4811 if (patchDesc->mUid != mUidCached) {
4812 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004813 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004814 return outputDesc->device();
4815 }
4816 }
4817
Eric Laurent97ac8712018-07-27 18:59:02 -07004818 // Honor explicit routing requests only if no client using default routing is active on this
4819 // input: a specific app can not force routing for other apps by setting a preferred device.
4820 bool active; // unused
4821 sp<DeviceDescriptor> deviceDesc =
4822 findPreferredDevice(outputDesc, STRATEGY_NONE, active, mAvailableOutputDevices);
4823 if (deviceDesc != nullptr) {
4824 return deviceDesc->type();
Eric Laurentf3a5a602018-05-22 18:42:55 -07004825 }
4826
Eric Laurente552edb2014-03-10 17:42:56 -07004827 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004828 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004829 // use device for strategy enforced audible
4830 // 2: we are in call or the strategy phone is active on the output:
4831 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004832 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004833 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004834 // 4: the strategy for enforced audible is active but not enforced on the output:
4835 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004836 // 5: the strategy accessibility is active on the output:
4837 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004838 // 6: the strategy "respectful" sonification is active on the output:
4839 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004840 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004841 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004842 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004843 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004844 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004845 // use device for strategy t-t-s
Eric Laurent484e9272018-06-07 17:29:23 -07004846
4847 // FIXME: extend use of isStrategyActiveOnSameModule() to all strategies
4848 // with a refined rule considering mutually exclusive devices (using same backend)
4849 // as opposed to all streams on the same audio HAL module.
Eric Laurent97ac8712018-07-27 18:59:02 -07004850 audio_devices_t device = AUDIO_DEVICE_NONE;
François Gaffiead3183e2015-03-18 16:55:35 +01004851 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004852 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004853 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4854 } else if (isInCall() ||
Eric Laurent484e9272018-06-07 17:29:23 -07004855 isStrategyActiveOnSameModule(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004856 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
Yung Ti Su3e7eb5e2018-06-13 11:48:42 +08004857 } else if (isStrategyActiveOnSameModule(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004858 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004859 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
4860 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004861 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4862 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004863 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004864 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004865 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004866 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004867 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004868 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004869 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004870 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004871 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004872 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004873 }
4874
Eric Laurent1c333e22014-05-20 10:48:17 -07004875 ALOGV("getNewOutputDevice() selected device %x", device);
4876 return device;
4877}
4878
Eric Laurentfb66dd92016-01-28 18:32:03 -08004879audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004880{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004881 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004882
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004883 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004884 if (index >= 0) {
4885 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4886 if (patchDesc->mUid != mUidCached) {
4887 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004888 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004889 return inputDesc->mDevice;
4890 }
4891 }
4892
Eric Laurent97ac8712018-07-27 18:59:02 -07004893 // Honor explicit routing requests only if no client using default routing is active on this
4894 // input: a specific app can not force routing for other apps by setting a preferred device.
4895 bool active;
4896 sp<DeviceDescriptor> deviceDesc =
4897 findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
4898 if (deviceDesc != nullptr) {
4899 return deviceDesc->type();
4900 }
4901
Eric Laurentdc95a252018-04-12 12:46:56 -07004902 // If we are not in call and no client is active on this input, this methods returns
4903 // AUDIO_DEVICE_NONE, causing the patch on the input stream to be released.
Eric Laurent4eb58f12018-12-07 16:41:02 -08004904 audio_source_t source = inputDesc->source();
Eric Laurentdc95a252018-04-12 12:46:56 -07004905 if (source == AUDIO_SOURCE_DEFAULT && isInCall()) {
4906 source = AUDIO_SOURCE_VOICE_COMMUNICATION;
4907 }
4908 if (source != AUDIO_SOURCE_DEFAULT) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08004909 device = getDeviceAndMixForInputSource(source);
4910 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004911
Eric Laurente552edb2014-03-10 17:42:56 -07004912 return device;
4913}
4914
Eric Laurent794fde22016-03-11 09:50:45 -08004915bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4916 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004917 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004918}
4919
Eric Laurente0720872014-03-11 09:30:41 -07004920uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004921 return (uint32_t)getStrategy(stream);
4922}
4923
Eric Laurente0720872014-03-11 09:30:41 -07004924audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004925 // By checking the range of stream before calling getStrategy, we avoid
4926 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4927 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004928 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004929 return AUDIO_DEVICE_NONE;
4930 }
Eric Laurentb0688d62018-08-14 15:49:18 -07004931 audio_devices_t activeDevices = AUDIO_DEVICE_NONE;
Eric Laurent28d09f02016-03-08 10:43:05 -08004932 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004933 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4934 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004935 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004936 }
Eric Laurent794fde22016-03-11 09:50:45 -08004937 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004938 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004939 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Eric Laurentb0688d62018-08-14 15:49:18 -07004940 devices |= curDevices;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004941 for (audio_io_handle_t output : getOutputsForDevice(curDevices, mOutputs)) {
4942 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08004943 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurentb0688d62018-08-14 15:49:18 -07004944 activeDevices |= outputDesc->device();
Eric Laurent28d09f02016-03-08 10:43:05 -08004945 }
4946 }
Eric Laurente552edb2014-03-10 17:42:56 -07004947 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004948
Eric Laurentb0688d62018-08-14 15:49:18 -07004949 // Favor devices selected on active streams if any to report correct device in case of
4950 // explicit device selection
4951 if (activeDevices != AUDIO_DEVICE_NONE) {
4952 devices = activeDevices;
4953 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004954 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4955 and doesn't really need to.*/
4956 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4957 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4958 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4959 }
Eric Laurente552edb2014-03-10 17:42:56 -07004960 return devices;
4961}
4962
François Gaffie2110e042015-03-24 08:41:51 +01004963routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4964{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004965 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004966 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004967}
4968
Eric Laurent97ac8712018-07-27 18:59:02 -07004969routing_strategy AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004970 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004971 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004972 return STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004973 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004974 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004975 return STRATEGY_ENFORCED_AUDIBLE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004976 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004977 // usage to strategy mapping
Eric Laurent97ac8712018-07-27 18:59:02 -07004978 return mEngine->getStrategyForUsage(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004979}
4980
Eric Laurente0720872014-03-11 09:30:41 -07004981void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004982 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004983 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004984 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4985 updateDevicesAndOutputs();
4986 break;
4987 default:
4988 break;
4989 }
4990}
4991
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004992uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004993
4994 // skip beacon mute management if a dedicated TTS output is available
4995 if (mTtsOutputAvailable) {
4996 return 0;
4997 }
4998
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004999 switch(event) {
5000 case STARTING_OUTPUT:
5001 mBeaconMuteRefCount++;
5002 break;
5003 case STOPPING_OUTPUT:
5004 if (mBeaconMuteRefCount > 0) {
5005 mBeaconMuteRefCount--;
5006 }
5007 break;
5008 case STARTING_BEACON:
5009 mBeaconPlayingRefCount++;
5010 break;
5011 case STOPPING_BEACON:
5012 if (mBeaconPlayingRefCount > 0) {
5013 mBeaconPlayingRefCount--;
5014 }
5015 break;
5016 }
5017
5018 if (mBeaconMuteRefCount > 0) {
5019 // any playback causes beacon to be muted
5020 return setBeaconMute(true);
5021 } else {
5022 // no other playback: unmute when beacon starts playing, mute when it stops
5023 return setBeaconMute(mBeaconPlayingRefCount == 0);
5024 }
5025}
5026
5027uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5028 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5029 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5030 // keep track of muted state to avoid repeating mute/unmute operations
5031 if (mBeaconMuted != mute) {
5032 // mute/unmute AUDIO_STREAM_TTS on all outputs
5033 ALOGV("\t muting %d", mute);
5034 uint32_t maxLatency = 0;
5035 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005036 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005037 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07005038 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005039 0 /*delay*/, AUDIO_DEVICE_NONE);
5040 const uint32_t latency = desc->latency() * 2;
5041 if (latency > maxLatency) {
5042 maxLatency = latency;
5043 }
5044 }
5045 mBeaconMuted = mute;
5046 return maxLatency;
5047 }
5048 return 0;
5049}
5050
Eric Laurente0720872014-03-11 09:30:41 -07005051audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01005052 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005053{
Eric Laurent97ac8712018-07-27 18:59:02 -07005054 // Honor explicit routing requests only if all active clients have a preferred route in which
5055 // case the last active client route is used
5056 sp<DeviceDescriptor> deviceDesc = findPreferredDevice(mOutputs, strategy, mAvailableOutputDevices);
5057 if (deviceDesc != nullptr) {
5058 return deviceDesc->type();
Paul McLeanaa981192015-03-21 09:55:15 -07005059 }
5060
Eric Laurente552edb2014-03-10 17:42:56 -07005061 if (fromCache) {
5062 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
5063 strategy, mDeviceForStrategy[strategy]);
5064 return mDeviceForStrategy[strategy];
5065 }
François Gaffie2110e042015-03-24 08:41:51 +01005066 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07005067}
5068
Eric Laurente0720872014-03-11 09:30:41 -07005069void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005070{
5071 for (int i = 0; i < NUM_STRATEGIES; i++) {
5072 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
5073 }
5074 mPreviousOutputs = mOutputs;
5075}
5076
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005077uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005078 audio_devices_t prevDevice,
5079 uint32_t delayMs)
5080{
5081 // mute/unmute strategies using an incompatible device combination
5082 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5083 // if unmuting, unmute only after the specified delay
5084 if (outputDesc->isDuplicated()) {
5085 return 0;
5086 }
5087
5088 uint32_t muteWaitMs = 0;
5089 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07005090 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005091
5092 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
5093 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07005094 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07005095 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
5096 bool doMute = false;
5097
5098 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
5099 doMute = true;
5100 outputDesc->mStrategyMutedByDevice[i] = true;
5101 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
5102 doMute = true;
5103 outputDesc->mStrategyMutedByDevice[i] = false;
5104 }
Eric Laurent99401132014-05-07 19:48:15 -07005105 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005106 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005107 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005108 // skip output if it does not share any device with current output
5109 if ((desc->supportedDevices() & outputDesc->supportedDevices())
5110 == AUDIO_DEVICE_NONE) {
5111 continue;
5112 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005113 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07005114 mute ? "muting" : "unmuting", i, curDevice);
5115 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005116 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005117 if (mute) {
5118 // FIXME: should not need to double latency if volume could be applied
5119 // immediately by the audioflinger mixer. We must account for the delay
5120 // between now and the next time the audioflinger thread for this output
5121 // will process a buffer (which corresponds to one buffer size,
5122 // usually 1/2 or 1/4 of the latency).
5123 if (muteWaitMs < desc->latency() * 2) {
5124 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005125 }
5126 }
5127 }
5128 }
5129 }
5130 }
5131
Eric Laurent99401132014-05-07 19:48:15 -07005132 // temporary mute output if device selection changes to avoid volume bursts due to
5133 // different per device volumes
5134 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005135 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5136 // temporary mute duration is conservatively set to 4 times the reported latency
5137 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5138 if (muteWaitMs < tempMuteWaitMs) {
5139 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005140 }
Eric Laurentdc462862016-07-19 12:29:53 -07005141
Eric Laurent99401132014-05-07 19:48:15 -07005142 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005143 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005144 // make sure that we do not start the temporary mute period too early in case of
5145 // delayed device change
5146 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005147 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07005148 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07005149 }
5150 }
5151 }
5152
Eric Laurente552edb2014-03-10 17:42:56 -07005153 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5154 if (muteWaitMs > delayMs) {
5155 muteWaitMs -= delayMs;
5156 usleep(muteWaitMs * 1000);
5157 return muteWaitMs;
5158 }
5159 return 0;
5160}
5161
Eric Laurentc75307b2015-03-17 15:29:32 -07005162uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005163 audio_devices_t device,
5164 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07005165 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005166 audio_patch_handle_t *patchHandle,
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005167 const char *address,
5168 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005169{
Eric Laurentc75307b2015-03-17 15:29:32 -07005170 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005171 AudioParameter param;
5172 uint32_t muteWaitMs;
5173
5174 if (outputDesc->isDuplicated()) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005175 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs,
5176 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
5177 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs,
5178 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005179 return muteWaitMs;
5180 }
5181 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5182 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07005183 if ((device != AUDIO_DEVICE_NONE) &&
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005184 ((device & outputDesc->supportedDevices()) == AUDIO_DEVICE_NONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005185 return 0;
5186 }
5187
5188 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07005189 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07005190
5191 audio_devices_t prevDevice = outputDesc->mDevice;
5192
Paul McLeanaa981192015-03-21 09:55:15 -07005193 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005194
5195 if (device != AUDIO_DEVICE_NONE) {
5196 outputDesc->mDevice = device;
5197 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005198
5199 // if the outputs are not materially active, there is no need to mute.
5200 if (requiresMuteCheck) {
5201 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
5202 } else {
5203 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5204 muteWaitMs = 0;
5205 }
Eric Laurente552edb2014-03-10 17:42:56 -07005206
5207 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005208 // the requested device is AUDIO_DEVICE_NONE
5209 // OR the requested device is the same as current device
5210 // AND force is not specified
5211 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07005212 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07005213 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
5214 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005215 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005216 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005217 return muteWaitMs;
5218 }
5219
5220 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07005221
Eric Laurente552edb2014-03-10 17:42:56 -07005222 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07005223 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005224 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005225 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07005226 DeviceVector deviceList;
5227 if ((address == NULL) || (strlen(address) == 0)) {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005228 deviceList = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurentc40d9692016-04-13 19:14:13 -07005229 } else {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005230 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
5231 device, String8(address));
5232 if (deviceDesc) deviceList.add(deviceDesc);
Eric Laurentc40d9692016-04-13 19:14:13 -07005233 }
5234
Eric Laurent1c333e22014-05-20 10:48:17 -07005235 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005236 PatchBuilder patchBuilder;
5237 patchBuilder.addSource(outputDesc);
Eric Laurent1c333e22014-05-20 10:48:17 -07005238 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005239 patchBuilder.addSink(deviceList.itemAt(i));
Eric Laurent1c333e22014-05-20 10:48:17 -07005240 }
Mikhail Naganovdc769682018-05-04 15:34:08 -07005241 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005242 }
5243 }
Eric Laurente552edb2014-03-10 17:42:56 -07005244
5245 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07005246 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005247
5248 return muteWaitMs;
5249}
5250
Eric Laurentc75307b2015-03-17 15:29:32 -07005251status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005252 int delayMs,
5253 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005254{
Eric Laurent6a94d692014-05-20 11:18:06 -07005255 ssize_t index;
5256 if (patchHandle) {
5257 index = mAudioPatches.indexOfKey(*patchHandle);
5258 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005259 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005260 }
5261 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005262 return INVALID_OPERATION;
5263 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005264 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5265 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005266 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005267 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005268 removeAudioPatch(patchDesc->mHandle);
5269 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005270 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005271 return status;
5272}
5273
5274status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5275 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005276 bool force,
5277 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005278{
5279 status_t status = NO_ERROR;
5280
Eric Laurent1f2f2232014-06-02 12:01:23 -07005281 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005282 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5283 inputDesc->mDevice = device;
5284
Mikhail Naganov708e0382018-05-30 09:53:04 -07005285 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005286 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005287 PatchBuilder patchBuilder;
5288 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005289 // AUDIO_SOURCE_HOTWORD is for internal use only:
5290 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07005291 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5292 auto result = usecase;
5293 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5294 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5295 }
5296 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07005297 //only one input device for now
Mikhail Naganovdc769682018-05-04 15:34:08 -07005298 addSource(deviceList.itemAt(0));
5299 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005300 }
5301 }
5302 return status;
5303}
5304
Eric Laurent6a94d692014-05-20 11:18:06 -07005305status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5306 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005307{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005308 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005309 ssize_t index;
5310 if (patchHandle) {
5311 index = mAudioPatches.indexOfKey(*patchHandle);
5312 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005313 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005314 }
5315 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005316 return INVALID_OPERATION;
5317 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005318 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5319 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005320 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005321 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005322 removeAudioPatch(patchDesc->mHandle);
5323 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005324 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005325 return status;
5326}
5327
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005328sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005329 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005330 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005331 audio_format_t& format,
5332 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005333 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005334{
5335 // Choose an input profile based on the requested capture parameters: select the first available
5336 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005337 //
5338 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5339 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005340
Glenn Kasten730b9262018-03-29 15:01:26 -07005341 sp<IOProfile> firstInexact;
5342 uint32_t updatedSamplingRate = 0;
5343 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5344 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005345 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005346 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005347 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005348 //updatedFormat = format;
Eric Laurent275e8e92014-11-30 15:14:47 -08005349 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005350 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005351 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005352 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005353 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005354 &channelMask /*updatedChannelMask*/,
5355 // FIXME ugly cast
5356 (audio_output_flags_t) flags,
5357 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005358 return profile;
5359 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005360 if (firstInexact == nullptr && profile->isCompatibleProfile(device, address,
5361 samplingRate,
5362 &updatedSamplingRate,
5363 format,
5364 &updatedFormat,
5365 channelMask,
5366 &updatedChannelMask,
5367 // FIXME ugly cast
5368 (audio_output_flags_t) flags,
5369 false /*exactMatchRequiredForInputFlags*/)) {
5370 firstInexact = profile;
5371 }
5372
Eric Laurente552edb2014-03-10 17:42:56 -07005373 }
5374 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005375 if (firstInexact != nullptr) {
5376 samplingRate = updatedSamplingRate;
5377 format = updatedFormat;
5378 channelMask = updatedChannelMask;
5379 return firstInexact;
5380 }
Eric Laurente552edb2014-03-10 17:42:56 -07005381 return NULL;
5382}
5383
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005384
5385audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005386 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005387{
Eric Laurent97ac8712018-07-27 18:59:02 -07005388 // Honor explicit routing requests only if all active clients have a preferred route in which
5389 // case the last active client route is used
5390 sp<DeviceDescriptor> deviceDesc =
5391 findPreferredDevice(mInputs, inputSource, mAvailableInputDevices);
5392 if (deviceDesc != nullptr) {
5393 return deviceDesc->type();
5394 }
5395
5396
François Gaffie036e1e92015-03-19 10:16:24 +01005397 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5398 audio_devices_t selectedDeviceFromMix =
5399 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005400
François Gaffie036e1e92015-03-19 10:16:24 +01005401 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5402 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005403 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005404 return getDeviceForInputSource(inputSource);
5405}
5406
5407audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5408{
Eric Laurent97ac8712018-07-27 18:59:02 -07005409 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005410}
5411
Eric Laurente0720872014-03-11 09:30:41 -07005412float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005413 int index,
5414 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005415{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005416 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005417
5418 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5419 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5420 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5421 // the ringtone volume
5422 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5423 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5424 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5425 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5426 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5427 }
5428
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005429 // in-call: always cap volume by voice volume + some low headroom
5430 if ((stream != AUDIO_STREAM_VOICE_CALL) &&
Eric Laurent7731b5a2018-04-06 15:47:22 -07005431 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005432 switch (stream) {
5433 case AUDIO_STREAM_SYSTEM:
5434 case AUDIO_STREAM_RING:
5435 case AUDIO_STREAM_MUSIC:
5436 case AUDIO_STREAM_ALARM:
5437 case AUDIO_STREAM_NOTIFICATION:
5438 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5439 case AUDIO_STREAM_DTMF:
5440 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005441 int voiceVolumeIndex =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005442 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, device);
Eric Laurent7731b5a2018-04-06 15:47:22 -07005443 const float maxVoiceVolDb =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005444 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, device)
Eric Laurent7731b5a2018-04-06 15:47:22 -07005445 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005446 if (volumeDB > maxVoiceVolDb) {
5447 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5448 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5449 volumeDB = maxVoiceVolDb;
5450 }
5451 } break;
5452 default:
5453 break;
5454 }
5455 }
5456
Eric Laurente552edb2014-03-10 17:42:56 -07005457 // if a headset is connected, apply the following rules to ring tones and notifications
5458 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005459 // - always attenuate notifications volume by 6dB
5460 // - attenuate ring tones volume by 6dB unless music is not playing and
5461 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005462 // - if music is playing, always limit the volume to current music volume,
5463 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005464 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005465 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5466 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5467 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005468 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005469 AUDIO_DEVICE_OUT_USB_HEADSET |
5470 AUDIO_DEVICE_OUT_HEARING_AID)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005471 ((stream_strategy == STRATEGY_SONIFICATION)
5472 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005473 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005474 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005475 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005476 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005477 // when the phone is ringing we must consider that music could have been paused just before
5478 // by the music application and behave as if music was active if the last music track was
5479 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005480 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005481 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005482 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005483 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005484 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005485 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5486 musicDevice),
5487 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005488 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5489 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005490 if (volumeDB > minVolDB) {
5491 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005492 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005493 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005494 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5495 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5496 // on A2DP, also ensure notification volume is not too low compared to media when
5497 // intended to be played
5498 if ((volumeDB > -96.0f) &&
5499 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5500 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5501 stream, device,
5502 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5503 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5504 }
5505 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005506 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5507 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005508 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005509 }
5510 }
5511
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005512 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005513}
5514
Eric Laurent3839bc02018-07-10 18:33:34 -07005515int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
5516 audio_stream_type_t srcStream,
5517 audio_stream_type_t dstStream)
5518{
5519 if (srcStream == dstStream) {
5520 return srcIndex;
5521 }
5522 float minSrc = (float)mVolumeCurves->getVolumeIndexMin(srcStream);
5523 float maxSrc = (float)mVolumeCurves->getVolumeIndexMax(srcStream);
5524 float minDst = (float)mVolumeCurves->getVolumeIndexMin(dstStream);
5525 float maxDst = (float)mVolumeCurves->getVolumeIndexMax(dstStream);
5526
5527 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
5528}
5529
Eric Laurente0720872014-03-11 09:30:41 -07005530status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005531 int index,
5532 const sp<AudioOutputDescriptor>& outputDesc,
5533 audio_devices_t device,
5534 int delayMs,
5535 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005536{
Eric Laurente552edb2014-03-10 17:42:56 -07005537 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005538 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005539 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005540 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005541 return NO_ERROR;
5542 }
François Gaffie2110e042015-03-24 08:41:51 +01005543 audio_policy_forced_cfg_t forceUseForComm =
5544 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005545 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005546 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5547 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005548 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005549 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005550 return INVALID_OPERATION;
5551 }
5552
Eric Laurentc75307b2015-03-17 15:29:32 -07005553 if (device == AUDIO_DEVICE_NONE) {
5554 device = outputDesc->device();
5555 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005556
Eric Laurentffbc80f2015-03-18 18:30:19 -07005557 float volumeDb = computeVolume(stream, index, device);
HW Leeda7581e2018-05-22 18:31:34 +08005558 if (outputDesc->isFixedVolume(device) ||
5559 // Force VoIP volume to max for bluetooth SCO
5560 ((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
5561 (device & AUDIO_DEVICE_OUT_ALL_SCO) != 0)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005562 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005563 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005564
Eric Laurentffbc80f2015-03-18 18:30:19 -07005565 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005566
Eric Laurent3b73df72014-03-11 09:06:29 -07005567 if (stream == AUDIO_STREAM_VOICE_CALL ||
5568 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005569 float voiceVolume;
5570 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005571 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurent3839bc02018-07-10 18:33:34 -07005572 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005573 } else {
5574 voiceVolume = 1.0;
5575 }
5576
Eric Laurent18fba842016-03-31 14:41:26 -07005577 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005578 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5579 mLastVoiceVolume = voiceVolume;
5580 }
5581 }
5582
5583 return NO_ERROR;
5584}
5585
Eric Laurentc75307b2015-03-17 15:29:32 -07005586void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5587 audio_devices_t device,
5588 int delayMs,
5589 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005590{
Eric Laurentc75307b2015-03-17 15:29:32 -07005591 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005592
Eric Laurent794fde22016-03-11 09:50:45 -08005593 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005594 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005595 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005596 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005597 device,
5598 delayMs,
5599 force);
5600 }
5601}
5602
Eric Laurente0720872014-03-11 09:30:41 -07005603void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005604 bool on,
5605 const sp<AudioOutputDescriptor>& outputDesc,
5606 int delayMs,
5607 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005608{
Eric Laurent72249d52015-06-08 11:12:15 -07005609 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5610 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005611 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005612 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005613 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005614 }
5615 }
5616}
5617
Eric Laurente0720872014-03-11 09:30:41 -07005618void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005619 bool on,
5620 const sp<AudioOutputDescriptor>& outputDesc,
5621 int delayMs,
5622 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005623{
Eric Laurente552edb2014-03-10 17:42:56 -07005624 if (device == AUDIO_DEVICE_NONE) {
5625 device = outputDesc->device();
5626 }
5627
Eric Laurentc75307b2015-03-17 15:29:32 -07005628 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5629 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005630
5631 if (on) {
5632 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005633 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005634 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005635 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005636 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005637 }
5638 }
5639 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5640 outputDesc->mMuteCount[stream]++;
5641 } else {
5642 if (outputDesc->mMuteCount[stream] == 0) {
5643 ALOGV("setStreamMute() unmuting non muted stream!");
5644 return;
5645 }
5646 if (--outputDesc->mMuteCount[stream] == 0) {
5647 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005648 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005649 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005650 device,
5651 delayMs);
5652 }
5653 }
5654}
5655
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005656audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5657{
5658 // flags to stream type mapping
5659 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5660 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5661 }
5662 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5663 return AUDIO_STREAM_BLUETOOTH_SCO;
5664 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005665 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5666 return AUDIO_STREAM_TTS;
5667 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005668
Ari Hausman-Cohen5c00d012018-06-26 17:09:11 -07005669 return audio_usage_to_stream_type(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005670}
Eric Laurente83b55d2014-11-14 10:06:21 -08005671
François Gaffie53615e22015-03-19 09:24:12 +01005672bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5673{
Eric Laurente83b55d2014-11-14 10:06:21 -08005674 // has flags that map to a strategy?
5675 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5676 return true;
5677 }
5678
5679 // has known usage?
5680 switch (paa->usage) {
5681 case AUDIO_USAGE_UNKNOWN:
5682 case AUDIO_USAGE_MEDIA:
5683 case AUDIO_USAGE_VOICE_COMMUNICATION:
5684 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5685 case AUDIO_USAGE_ALARM:
5686 case AUDIO_USAGE_NOTIFICATION:
5687 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5688 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5689 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5690 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5691 case AUDIO_USAGE_NOTIFICATION_EVENT:
5692 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5693 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5694 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5695 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005696 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005697 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005698 break;
5699 default:
5700 return false;
5701 }
5702 return true;
5703}
5704
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005705bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005706 routing_strategy strategy, uint32_t inPastMs,
5707 nsecs_t sysTime) const
5708{
5709 if ((sysTime == 0) && (inPastMs != 0)) {
5710 sysTime = systemTime();
5711 }
Eric Laurent794fde22016-03-11 09:50:45 -08005712 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005713 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurent97ac8712018-07-27 18:59:02 -07005714 (STRATEGY_NONE == strategy)) &&
François Gaffiead3183e2015-03-18 16:55:35 +01005715 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5716 return true;
5717 }
5718 }
5719 return false;
5720}
5721
Eric Laurent484e9272018-06-07 17:29:23 -07005722bool AudioPolicyManager::isStrategyActiveOnSameModule(const sp<AudioOutputDescriptor>& outputDesc,
5723 routing_strategy strategy, uint32_t inPastMs,
5724 nsecs_t sysTime) const
5725{
5726 for (size_t i = 0; i < mOutputs.size(); i++) {
5727 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5728 if (outputDesc->sharesHwModuleWith(desc)
5729 && isStrategyActive(desc, strategy, inPastMs, sysTime)) {
5730 return true;
5731 }
5732 }
5733 return false;
5734}
5735
François Gaffie2110e042015-03-24 08:41:51 +01005736audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5737{
5738 return mEngine->getForceUse(usage);
5739}
5740
5741bool AudioPolicyManager::isInCall()
5742{
5743 return isStateInCall(mEngine->getPhoneState());
5744}
5745
5746bool AudioPolicyManager::isStateInCall(int state)
5747{
5748 return is_state_in_call(state);
5749}
5750
Eric Laurentd60560a2015-04-10 11:31:20 -07005751void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5752{
5753 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005754 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5755 if (sourceDesc->srcDevice()->equals(deviceDesc)) {
5756 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->portId());
5757 stopAudioSource(sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005758 }
5759 }
5760
5761 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5762 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5763 bool release = false;
5764 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5765 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5766 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5767 source->ext.device.type == deviceDesc->type()) {
5768 release = true;
5769 }
5770 }
5771 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5772 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5773 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5774 sink->ext.device.type == deviceDesc->type()) {
5775 release = true;
5776 }
5777 }
5778 if (release) {
5779 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5780 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5781 }
5782 }
5783}
5784
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005785void AudioPolicyManager::modifySurroundFormats(
5786 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005787 std::unordered_set<audio_format_t> enforcedSurround(
5788 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08005789 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
5790 for (const auto& pair : mConfig.getSurroundFormats()) {
5791 allSurround.insert(pair.first);
5792 for (const auto& subformat : pair.second) allSurround.insert(subformat);
5793 }
Phil Burk09bc4612016-02-24 15:58:15 -08005794
5795 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5796 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005797 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005798 // This is the resulting set of formats depending on the surround mode:
5799 // 'all surround' = allSurround
5800 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
5801 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
5802 // 'manual surround' = mManualSurroundFormats
5803 // AUTO: formats v 'enforced surround'
5804 // ALWAYS: formats v 'all surround' v 'enforced surround'
5805 // NEVER: formats ^ 'non-surround'
5806 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08005807
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005808 std::unordered_set<audio_format_t> formatSet;
5809 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
5810 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005811 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005812 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005813 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005814 formatSet.insert(*formatIter);
5815 }
5816 }
5817 } else {
5818 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
5819 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005820 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005821
jiabin81772902018-04-02 17:52:27 -07005822 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005823 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005824 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
5825 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
5826 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08005827 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005828 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
5829 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5830 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07005831 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005832 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08005833 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005834 for (const auto& format : formatSet) {
5835 formatsPtr->push(format);
5836 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005837}
5838
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005839void AudioPolicyManager::modifySurroundChannelMasks(ChannelsVector *channelMasksPtr) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005840 ChannelsVector &channelMasks = *channelMasksPtr;
5841 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5842 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5843
5844 // If NEVER, then remove support for channelMasks > stereo.
5845 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5846 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5847 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5848 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5849 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5850 channelMasks.removeAt(maskIndex);
5851 } else {
5852 maskIndex++;
5853 }
5854 }
jiabin81772902018-04-02 17:52:27 -07005855 // If ALWAYS or MANUAL, then make sure we at least support 5.1
5856 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
5857 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005858 bool supports5dot1 = false;
5859 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005860 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005861 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5862 supports5dot1 = true;
5863 break;
5864 }
5865 }
5866 // If not then add 5.1 support.
5867 if (!supports5dot1) {
5868 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005869 ALOGI("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07005870 }
Phil Burk09bc4612016-02-24 15:58:15 -08005871 }
5872}
5873
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005874void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07005875 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005876 AudioProfileVector &profiles)
5877{
5878 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005879 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07005880
François Gaffie112b0af2015-11-19 16:13:25 +01005881 // Format MUST be checked first to update the list of AudioProfile
5882 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005883 reply = mpClientInterface->getParameters(
5884 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07005885 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005886 AudioParameter repliedParameters(reply);
5887 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005888 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005889 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5890 return;
5891 }
Phil Burk09bc4612016-02-24 15:58:15 -08005892 FormatVector formats = formatsFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08005893 if (device == AUDIO_DEVICE_OUT_HDMI
5894 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005895 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005896 }
Phil Burk09bc4612016-02-24 15:58:15 -08005897 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005898 }
François Gaffie112b0af2015-11-19 16:13:25 +01005899
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005900 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08005901 ChannelsVector channelMasks;
5902 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005903 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07005904 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01005905
5906 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005907 reply = mpClientInterface->getParameters(
5908 ioHandle,
5909 requestedParameters.toString() + ";" +
5910 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01005911 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005912 AudioParameter repliedParameters(reply);
5913 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005914 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005915 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005916 }
5917 }
5918 if (profiles.hasDynamicChannelsFor(format)) {
5919 reply = mpClientInterface->getParameters(ioHandle,
5920 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07005921 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01005922 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005923 AudioParameter repliedParameters(reply);
5924 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005925 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005926 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08005927 if (device == AUDIO_DEVICE_OUT_HDMI
5928 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005929 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07005930 }
François Gaffie112b0af2015-11-19 16:13:25 +01005931 }
5932 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08005933 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01005934 }
5935}
Eric Laurentd60560a2015-04-10 11:31:20 -07005936
Mikhail Naganovdc769682018-05-04 15:34:08 -07005937status_t AudioPolicyManager::installPatch(const char *caller,
5938 audio_patch_handle_t *patchHandle,
5939 AudioIODescriptorInterface *ioDescriptor,
5940 const struct audio_patch *patch,
5941 int delayMs)
5942{
5943 ssize_t index = mAudioPatches.indexOfKey(
5944 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
5945 *patchHandle : ioDescriptor->getPatchHandle());
5946 sp<AudioPatch> patchDesc;
5947 status_t status = installPatch(
5948 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
5949 if (status == NO_ERROR) {
5950 ioDescriptor->setPatchHandle(patchDesc->mHandle);
5951 }
5952 return status;
5953}
5954
5955status_t AudioPolicyManager::installPatch(const char *caller,
5956 ssize_t index,
5957 audio_patch_handle_t *patchHandle,
5958 const struct audio_patch *patch,
5959 int delayMs,
5960 uid_t uid,
5961 sp<AudioPatch> *patchDescPtr)
5962{
5963 sp<AudioPatch> patchDesc;
5964 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
5965 if (index >= 0) {
5966 patchDesc = mAudioPatches.valueAt(index);
5967 afPatchHandle = patchDesc->mAfPatchHandle;
5968 }
5969
5970 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
5971 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
5972 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
5973 if (status == NO_ERROR) {
5974 if (index < 0) {
5975 patchDesc = new AudioPatch(patch, uid);
5976 addAudioPatch(patchDesc->mHandle, patchDesc);
5977 } else {
5978 patchDesc->mPatch = *patch;
5979 }
5980 patchDesc->mAfPatchHandle = afPatchHandle;
5981 if (patchHandle) {
5982 *patchHandle = patchDesc->mHandle;
5983 }
5984 nextAudioPortGeneration();
5985 mpClientInterface->onAudioPatchListUpdate();
5986 }
5987 if (patchDescPtr) *patchDescPtr = patchDesc;
5988 return status;
5989}
5990
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08005991} // namespace android